diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4e10f48 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +target +**/node_modules +**/dist +.git +.fabrica +bench +*.log +result +result-* diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile new file mode 100644 index 0000000..2097535 --- /dev/null +++ b/deploy/docker/Dockerfile @@ -0,0 +1,110 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# Ianitor Domi on Docker (T4): one image with both programs; deploy/docker/compose.yaml runs +# it twice (edge, and control in edge's network so the API stays on loopback). +# +# docker build -f deploy/docker/Dockerfile -t ianitor . the image +# docker build -f deploy/docker/Dockerfile --target ci -t ianitor-ci . Linux test runner +# +# Build context: the repository (see .dockerignore: no target/, node_modules/ or .git/). + +ARG RUST=1.99-bookworm +ARG CADDY=2.11.7 +ARG PEBBLE=v2.10.3 + +# ------------------------------------------------------------------ Rust toolchain + native deps +FROM rust:${RUST} AS rust +RUN apt-get update \ + && apt-get install -y --no-install-recommends cmake git ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +# ------------------------------------------------------------------ Caddy (the fallback, and the diff suite's other engine) +FROM debian:bookworm-slim AS caddy +ARG CADDY +RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /caddy +RUN curl -fsSLo caddy.tar.gz "https://github.com/caddyserver/caddy/releases/download/v${CADDY}/caddy_${CADDY}_linux_amd64.tar.gz" \ + && curl -fsSLo sums.txt "https://github.com/caddyserver/caddy/releases/download/v${CADDY}/caddy_${CADDY}_checksums.txt" \ + && grep " caddy_${CADDY}_linux_amd64.tar.gz\$" sums.txt | sed "s/caddy_${CADDY}_linux_amd64.tar.gz/caddy.tar.gz/" | sha512sum -c - \ + && tar -xzf caddy.tar.gz caddy && ./caddy version + +# ------------------------------------------------------------------ the Linux test runner (layers 1–3 in CI) +FROM rust AS ci +ARG PEBBLE +RUN apt-get update && apt-get install -y --no-install-recommends curl unzip \ + && rm -rf /var/lib/apt/lists/* +COPY --from=caddy /caddy/caddy /usr/local/bin/caddy +RUN set -e; cd /tmp; for b in pebble pebble-challtestsrv; do \ + curl -fsSLo "$b.tar.gz" "https://github.com/letsencrypt/pebble/releases/download/${PEBBLE}/$b-linux-amd64.tar.gz"; \ + mkdir "$b.d"; tar -xzf "$b.tar.gz" -C "$b.d"; \ + install -m 0755 "$(find "$b.d" -type f -name "$b" | head -n1)" "/usr/local/bin/$b"; \ + done; rm -rf /tmp/*; pebble -version || true +ENV CARGO_TARGET_DIR=/target +WORKDIR /src +COPY . . +CMD ["cargo", "test", "--workspace", "--locked"] + +# ------------------------------------------------------------------ release build +FROM rust AS build +# Two jobs: the default (every core) runs Docker Desktop out of memory on Pingora's crates. +ARG JOBS=2 +ENV CARGO_BUILD_JOBS=${JOBS} +WORKDIR /src +COPY . . +RUN cargo build --release --locked -p ianitor-edge \ + && cargo build --release --locked -p ianitor-control --no-default-features \ + && strip target/release/ianitor-edge target/release/ianitor-control + +FROM node:22-bookworm-slim AS web +RUN corepack enable +WORKDIR /src +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ +COPY apps/web/package.json apps/web/package.json +COPY packages/ui/package.json packages/ui/package.json +RUN pnpm install --frozen-lockfile +COPY apps/web apps/web +COPY packages/ui packages/ui +RUN pnpm --filter web build + +# ------------------------------------------------------------------ the Linux release files +# docker build -f deploy/docker/Dockerfile --target dist --output type=local,dest=target/dist . +FROM debian:bookworm-slim AS dist-files +WORKDIR /out +COPY --from=build /src/target/release/ianitor-edge /src/target/release/ianitor-control /tmp/bin/ +COPY --from=web /src/apps/web/dist /tmp/web +COPY deploy/linux /tmp/linux +COPY Cargo.toml /tmp/Cargo.toml +RUN set -e; v=$(sed -n 's/^version = "\(.*\)"/\1/p' /tmp/Cargo.toml | head -n1); d="ianitor-$v"; \ + mkdir -p "$d/bin" "$d/lib"; cp /tmp/bin/* "$d/bin/"; cp -r /tmp/web "$d/web"; \ + cp /tmp/linux/setup.sh /tmp/linux/*.service "$d/lib/"; \ + tar --owner=0 --group=0 --numeric-owner --sort=name --mtime=@0 -czf "ianitor-$v-linux-x86_64.tar.gz" "$d"; \ + sed "s/__VERSION__/$v/" /tmp/linux/install.sh > install.sh; rm -rf "$d" +FROM scratch AS dist +COPY --from=dist-files /out/ / + +# ------------------------------------------------------------------ the image +FROM debian:bookworm-slim +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates tini \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --uid 10001 --home-dir /var/lib/ianitor --shell /usr/sbin/nologin ianitor \ + && mkdir -p /var/lib/ianitor /run/ianitor /usr/share/ianitor \ + && chown ianitor:ianitor /var/lib/ianitor /run/ianitor +COPY --from=build /src/target/release/ianitor-edge /src/target/release/ianitor-control /usr/local/bin/ +COPY --from=web /src/apps/web/dist /usr/share/ianitor/web +COPY deploy/docker/entrypoint.sh /usr/local/bin/ianitor-entrypoint +COPY deploy/linux/setup.sh /usr/local/lib/ianitor/setup.sh +LABEL org.opencontainers.image.title="Ianitor Domi" \ + org.opencontainers.image.description="Reverse proxy on Pingora with the Domi CA, a web UI and branch previews for Fabrica" \ + org.opencontainers.image.licenses="MPL-2.0" \ + org.opencontainers.image.source="https://gitea.marek-novak.cz/mnovak/Ianitor" +USER ianitor +VOLUME ["/var/lib/ianitor"] +# Docker lets an unprivileged user bind 80 and 443 inside the container +# (net.ipv4.ip_unprivileged_port_start = 0 by default since Docker 20.10). +EXPOSE 80 443 +ENTRYPOINT ["tini", "--", "/usr/local/bin/ianitor-entrypoint"] +CMD ["edge"] diff --git a/deploy/docker/compose.yaml b/deploy/docker/compose.yaml new file mode 100644 index 0000000..b9f7eec --- /dev/null +++ b/deploy/docker/compose.yaml @@ -0,0 +1,57 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# Ianitor Domi on Docker (T4). Set the variables in .env next to this file (see +# deploy/linux/setup.sh for all of them), then: +# +# docker compose up -d && docker compose exec control ianitor-entrypoint setup-link +# +# and open the link it prints. Edge serves 80/443; control runs in edge's network namespace, +# so its API stays on 127.0.0.1 and only edge (the admin host) reaches it. + +name: ianitor + +x-common: &common + image: ${IANITOR_IMAGE:-ianitor:latest} + restart: unless-stopped + environment: &env + IANITOR_LOG: info + CREDENTIALS_DIRECTORY: /var/lib/ianitor/credentials + IANITOR_ADMIN_HOST: ${IANITOR_ADMIN_HOST:?set IANITOR_ADMIN_HOST in .env (the web UI's address)} + IANITOR_TLS: ${IANITOR_TLS:-letsencrypt} + IANITOR_DOMI_ROOT: ${IANITOR_DOMI_ROOT:-} + IANITOR_PREVIEW_DOMAIN: ${IANITOR_PREVIEW_DOMAIN:-} + IANITOR_PREVIEW_UPSTREAMS: ${IANITOR_PREVIEW_UPSTREAMS:-} + IANITOR_PREVIEW_TLS: ${IANITOR_PREVIEW_TLS:-} + IANITOR_ROUTES_REMOTE: ${IANITOR_ROUTES_REMOTE:-} + IANITOR_ROUTES_HOST: ${IANITOR_ROUTES_HOST:-gitea} + volumes: + - state:/var/lib/ianitor + - run:/run/ianitor + read_only: true + tmpfs: [/tmp] + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + +services: + edge: + <<: *common + command: ["edge"] + ports: + - "${IANITOR_HTTP_PORT:-80}:80" + - "${IANITOR_HTTPS_PORT:-443}:443" + # Unprivileged port binding inside the container (Docker's default since 20.10, set here + # so a daemon with another default works too). + sysctls: + net.ipv4.ip_unprivileged_port_start: "0" + + control: + <<: *common + command: ["control"] + network_mode: "service:edge" + depends_on: [edge] + +volumes: + state: + run: diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh new file mode 100644 index 0000000..00f220e --- /dev/null +++ b/deploy/docker/entrypoint.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# The image's entrypoint (deploy/docker/compose.yaml runs it twice): +# control write control.toml from the environment once (deploy/linux/setup.sh), then +# run the control plane on 127.0.0.1:7878 (in edge's network namespace) +# edge wait for control's first edge.json, then serve 80 and 443 +# setup-link print the first admin's sign-in link +# run it (ianitor-control token create ..., a shell) +set -eu + +ROOT=/var/lib/ianitor +export IANITOR_ROOT=$ROOT IANITOR_CONFIG=$ROOT/control.toml IANITOR_EDGE_SOCKET=/run/ianitor/admin.sock + +case "${1:-edge}" in + control) + sh /usr/local/lib/ianitor/setup.sh + exec ianitor-control --config "$IANITOR_CONFIG" + ;; + edge) + i=0 + while [ ! -s "$ROOT/edge/edge.json" ]; do + i=$((i + 1)) + [ $i -le 120 ] || { echo "edge: no edge.json from control after 120 s" >&2; exit 1; } + sleep 1 + done + exec ianitor-edge --config "$ROOT/edge/edge.json" \ + --admin-socket /run/ianitor/admin.sock \ + --share-revocations "$ROOT/edge/share-revocations.json" + ;; + setup-link) + exec ianitor-control team setup-link --config "$IANITOR_CONFIG" + ;; + *) + exec "$@" + ;; +esac diff --git a/deploy/linux/ianitor-control.service b/deploy/linux/ianitor-control.service new file mode 100644 index 0000000..f85848a --- /dev/null +++ b/deploy/linux/ianitor-control.service @@ -0,0 +1,34 @@ +# Ianitor control: API and web UI on 127.0.0.1:7878 (deploy/linux/install.sh writes this). +[Unit] +Description=Ianitor control (API and UI on loopback) +After=network-online.target +Wants=network-online.target + +[Service] +User=ianitor +Group=ianitor +Environment=IANITOR_LOG=info +ExecStart=/usr/local/bin/ianitor-control --config /etc/ianitor/control.toml +# After every stop, a crash included: a trial still loaded into Caddy goes back at once. +ExecStopPost=/usr/local/bin/ianitor-control caddy-revert --config /etc/ianitor/control.toml +Restart=on-failure +RestartSec=2 +ReadWritePaths=/var/lib/ianitor +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +RestrictNamespaces=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +SystemCallArchitectures=native +CapabilityBoundingSet= +UMask=0027 + +[Install] +WantedBy=multi-user.target diff --git a/deploy/linux/ianitor-edge.service b/deploy/linux/ianitor-edge.service new file mode 100644 index 0000000..09cb308 --- /dev/null +++ b/deploy/linux/ianitor-edge.service @@ -0,0 +1,39 @@ +# Ianitor edge: the Pingora data plane on 80 and 443 (deploy/linux/install.sh writes this). +# Header-rule secrets: add one LoadCredential=:/var/lib/ianitor/credentials/ each +# (systemctl edit ianitor-edge). +[Unit] +Description=Ianitor edge (Pingora) +After=network-online.target ianitor-control.service +Wants=network-online.target +StartLimitIntervalSec=0 + +[Service] +User=ianitor-edge +Group=ianitor +Environment=IANITOR_LOG=info +ExecStart=/usr/local/bin/ianitor-edge --config /var/lib/ianitor/edge/edge.json --admin-socket /run/ianitor-edge/admin.sock --share-revocations /var/lib/ianitor/edge/share-revocations.json +LoadCredential=share-link-key:/var/lib/ianitor/credentials/share-link-key +RuntimeDirectory=ianitor-edge +RuntimeDirectoryMode=0750 +ReadWritePaths=/var/lib/ianitor/edge-state /var/lib/ianitor/logs +AmbientCapabilities=CAP_NET_BIND_SERVICE +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +# The first start may come before control has written edge.json. +Restart=always +RestartSec=2 +LimitNOFILE=65536 +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +RestrictNamespaces=yes +LockPersonality=yes +SystemCallArchitectures=native + +[Install] +WantedBy=multi-user.target diff --git a/deploy/linux/install.sh b/deploy/linux/install.sh new file mode 100644 index 0000000..5bbe005 --- /dev/null +++ b/deploy/linux/install.sh @@ -0,0 +1,81 @@ +#!/bin/sh +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# Ianitor Domi on plain Linux with systemd (T4), in one line: +# +# curl -fsSL https://gitea.marek-novak.cz/mnovak/Ianitor/releases/download/vX.Y.Z/install.sh \ +# | sudo IANITOR_ADMIN_HOST=ianitor.example.org sh +# +# It downloads the release tarball and SHA256SUMS of the same release, checks the sum, installs +# the binaries, the web UI and two systemd units (ianitor-control, ianitor-edge), writes +# /etc/ianitor/control.toml once (deploy/linux/setup.sh: every IANITOR_* variable), starts both, +# and prints the first admin's sign-in link. Running it again upgrades the binaries and keeps +# the config and the state. IANITOR_TARBALL= installs a local tarball instead (no download). +set -eu + +VERSION="${IANITOR_VERSION:-__VERSION__}" +BASE="${IANITOR_RELEASES:-https://gitea.marek-novak.cz/mnovak/Ianitor/releases/download}/v$VERSION" +ARCH="$(uname -m)" +NAME="ianitor-$VERSION-linux-$ARCH.tar.gz" + +die() { echo "ianitor install: $*" >&2; exit 1; } +[ "$(id -u)" = 0 ] || die "run it as root (sudo)" +command -v systemctl >/dev/null || die "this installer needs systemd; use the Docker image otherwise (deploy/docker)" +command -v git >/dev/null || die "install git first (apt install git / dnf install git)" +[ "$ARCH" = x86_64 ] || die "only x86_64 builds are published so far" + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +if [ -n "${IANITOR_TARBALL:-}" ]; then + cp "$IANITOR_TARBALL" "$work/$NAME" +else + command -v curl >/dev/null || die "install curl first" + curl -fsSLo "$work/$NAME" "$BASE/$NAME" + curl -fsSLo "$work/SHA256SUMS" "$BASE/SHA256SUMS" + (cd "$work" && grep " $NAME\$" SHA256SUMS | sha256sum -c -) || die "the download does not match SHA256SUMS" +fi +tar -xzf "$work/$NAME" -C "$work" +src="$work/ianitor-$VERSION" +[ -x "$src/bin/ianitor-control" ] || die "the tarball has no bin/ianitor-control" + +getent group ianitor >/dev/null || groupadd --system ianitor +id ianitor >/dev/null 2>&1 || useradd --system --gid ianitor --home-dir /var/lib/ianitor --shell /usr/sbin/nologin ianitor +id ianitor-edge >/dev/null 2>&1 || useradd --system --gid ianitor --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin ianitor-edge + +install -m 0755 "$src/bin/ianitor-control" "$src/bin/ianitor-edge" /usr/local/bin/ +install -d -m 0755 /usr/local/lib/ianitor /usr/share/ianitor +install -m 0755 "$src/lib/setup.sh" /usr/local/lib/ianitor/setup.sh +rm -rf /usr/share/ianitor/web && cp -r "$src/web" /usr/share/ianitor/web +install -m 0644 "$src/lib/ianitor-control.service" "$src/lib/ianitor-edge.service" /etc/systemd/system/ + +IANITOR_ROOT=/var/lib/ianitor IANITOR_CONFIG=/etc/ianitor/control.toml \ +IANITOR_EDGE_SOCKET=/run/ianitor-edge/admin.sock sh /usr/local/lib/ianitor/setup.sh + +# Who may read what (as the NixOS module's tmpfiles): control owns the state, edge reads its +# config and the certificates through the group and writes only its own state and logs. +chown -R ianitor:ianitor /var/lib/ianitor +chmod 0755 /var/lib/ianitor +chmod 0700 /var/lib/ianitor/control /var/lib/ianitor/credentials +chmod 0750 /var/lib/ianitor/edge /var/lib/ianitor/certs /var/lib/ianitor/caddy +chown -R ianitor-edge:ianitor /var/lib/ianitor/edge-state /var/lib/ianitor/logs +chmod 0700 /var/lib/ianitor/edge-state +chmod 0770 /var/lib/ianitor/logs +chown root:ianitor /etc/ianitor /etc/ianitor/control.toml +chmod 0750 /etc/ianitor +chmod 0640 /etc/ianitor/control.toml + +systemctl daemon-reload +systemctl enable --now ianitor-control.service ianitor-edge.service +systemctl restart ianitor-control.service ianitor-edge.service + +i=0 +until curl -s -o /dev/null http://127.0.0.1:7878/api/v1/health 2>/dev/null; do + i=$((i + 1)); [ $i -le 30 ] || die "control did not start; see journalctl -u ianitor-control" + sleep 1 +done +echo +echo "Ianitor $VERSION is running. Open this link to sign in as the first admin:" +runuser -u ianitor -- /usr/local/bin/ianitor-control team setup-link --config /etc/ianitor/control.toml 2>/dev/null \ + || echo "(the team already has an admin; they invite you from Settings → Team)" diff --git a/deploy/linux/setup.sh b/deploy/linux/setup.sh new file mode 100644 index 0000000..f02b3da --- /dev/null +++ b/deploy/linux/setup.sh @@ -0,0 +1,144 @@ +#!/bin/sh +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# Writes Ianitor's control.toml and its first secrets from environment variables, once. +# Shared by the Linux installer (deploy/linux/install.sh) and the Docker image's entrypoint. +# An existing control.toml is never touched; secrets are random files (0600), never values in +# the config, the image or a log. +# +# IANITOR_ADMIN_HOST the web UI's address, e.g. ianitor.example.org (required) +# IANITOR_TLS letsencrypt (default) or domi, for the admin host +# IANITOR_DOMI_ROOT the Domi root certificate (public) for tls = domi (docs/pki.md) +# IANITOR_PREVIEW_DOMAIN branch previews live under it, e.g. preview.example.org +# IANITOR_PREVIEW_UPSTREAMS comma list of what previews may point at (10.0.0.0/8,app.internal) +# IANITOR_PREVIEW_TLS letsencrypt or domi (default: IANITOR_TLS) +# IANITOR_ROUTES_REMOTE where the routes repository is pushed (https URL on Gitea, GitHub, GitLab) +# IANITOR_ROUTES_HOST gitea (default), github or gitlab: the push user name and the UI's label +# IANITOR_ROUTES_USER overrides the push user name +# IANITOR_ROOT state root (default /var/lib/ianitor) +# IANITOR_CONFIG where control.toml goes (default /etc/ianitor/control.toml) +# IANITOR_CREDENTIALS the credentials folder (default $IANITOR_ROOT/credentials) +# IANITOR_EDGE_SOCKET edge's admin socket (default /run/ianitor/admin.sock) +# IANITOR_WEB the built web UI (default /usr/share/ianitor/web) +# IANITOR_HTTP, IANITOR_HTTPS listen addresses (default 0.0.0.0:80, 0.0.0.0:443) +set -eu + +ROOT="${IANITOR_ROOT:-/var/lib/ianitor}" +CONFIG="${IANITOR_CONFIG:-/etc/ianitor/control.toml}" +CREDS="${IANITOR_CREDENTIALS:-$ROOT/credentials}" +SOCKET="${IANITOR_EDGE_SOCKET:-/run/ianitor/admin.sock}" +WEB="${IANITOR_WEB:-/usr/share/ianitor/web}" +TLS="${IANITOR_TLS:-letsencrypt}" + +die() { echo "ianitor setup: $*" >&2; exit 1; } + +# Only plain values reach the TOML: no quotes, backslashes, dollars or newlines. +plain() { + case "$1" in + *[\"\\\'\`\$]*) die "$2 contains a character that is not allowed" ;; + esac + if [ "$(printf '%s' "$1" | wc -l)" -ne 0 ]; then die "$2 must be one line"; fi +} + +for d in "$ROOT" "$ROOT/control" "$ROOT/edge" "$ROOT/caddy" "$ROOT/certs" "$ROOT/edge-state" \ + "$ROOT/caddy-state" "$ROOT/logs" "$CREDS"; do + mkdir -p "$d" +done +chmod 0700 "$CREDS" "$ROOT/control" + +# Secrets: made here once, random, readable by their owner only. +umask 077 +[ -s "$CREDS/share-link-key" ] || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$CREDS/share-link-key" +[ -s "$CREDS/pki-password" ] || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$CREDS/pki-password" +umask 022 +[ -f "$ROOT/edge/share-revocations.json" ] || echo '{"epoch":0,"deny":[]}' > "$ROOT/edge/share-revocations.json" +[ -f "$ROOT/engine" ] || echo pingora > "$ROOT/engine" + +if [ -f "$CONFIG" ]; then + echo "ianitor setup: $CONFIG exists; leaving it as it is." >&2 + exit 0 +fi + +[ -n "${IANITOR_ADMIN_HOST:-}" ] || die "IANITOR_ADMIN_HOST is required (the web UI's address, e.g. ianitor.example.org)" +plain "$IANITOR_ADMIN_HOST" IANITOR_ADMIN_HOST +case "$TLS" in letsencrypt|domi) ;; *) die "IANITOR_TLS must be letsencrypt or domi" ;; esac +PTLS="${IANITOR_PREVIEW_TLS:-$TLS}" +case "$PTLS" in letsencrypt|domi) ;; *) die "IANITOR_PREVIEW_TLS must be letsencrypt or domi" ;; esac + +routes_remote="" +if [ -n "${IANITOR_ROUTES_REMOTE:-}" ]; then + plain "$IANITOR_ROUTES_REMOTE" IANITOR_ROUTES_REMOTE + case "${IANITOR_ROUTES_HOST:-gitea}" in + github) user=x-access-token; label=GitHub ;; + gitlab) user=oauth2; label=GitLab ;; + gitea) user=ianitor; label=Gitea ;; + *) die "IANITOR_ROUTES_HOST must be gitea, github or gitlab" ;; + esac + user="${IANITOR_ROUTES_USER:-$user}" + plain "$user" IANITOR_ROUTES_USER + routes_remote="remote = \"$IANITOR_ROUTES_REMOTE\" +remote_name = \"$label\" +push_username = \"$user\" +push_credential = \"routes-token\"" +fi + +pki="" +if [ "$TLS" = domi ] || [ "$PTLS" = domi ]; then + [ -n "${IANITOR_DOMI_ROOT:-}" ] || die "tls = domi needs IANITOR_DOMI_ROOT (the Domi root certificate; docs/pki.md)" + plain "$IANITOR_DOMI_ROOT" IANITOR_DOMI_ROOT + pki="[pki] +root_cert = \"$IANITOR_DOMI_ROOT\"" +fi + +previews="" +if [ -n "${IANITOR_PREVIEW_DOMAIN:-}" ]; then + plain "$IANITOR_PREVIEW_DOMAIN" IANITOR_PREVIEW_DOMAIN + plain "${IANITOR_PREVIEW_UPSTREAMS:-}" IANITOR_PREVIEW_UPSTREAMS + list=$(printf '%s\n' "${IANITOR_PREVIEW_UPSTREAMS:-}" | tr ',' '\n' | sed '/^ *$/d; s/^ *//; s/ *$//; s/.*/"&"/' | paste -sd, -) + previews="[previews] +domain = \"$IANITOR_PREVIEW_DOMAIN\" +tls = \"$PTLS\" +upstreams = [$list]" +fi + +mkdir -p "$(dirname "$CONFIG")" +cat > "$CONFIG.new" <&2 diff --git a/deploy/windows/install.ps1 b/deploy/windows/install.ps1 new file mode 100644 index 0000000..aeee8ba --- /dev/null +++ b/deploy/windows/install.ps1 @@ -0,0 +1,208 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# Ianitor Domi on Windows Server, Caddy mode (Fabrica docs/32_coherence.md §2.5, T4). +# Pingora's Windows support is preliminary upstream, so Windows runs ianitor-control with Caddy +# as the data plane: same UI, same TOML, compiled to Caddy JSON, kept honest by the +# differential suite (which runs on Windows with Windows paths). +# +# From the unpacked release zip, in an elevated PowerShell: +# +# .\install.ps1 -AdminHost ianitor.example.org [-Tls letsencrypt|domi] [-DomiRoot ] +# [-PreviewDomain preview.example.org -PreviewUpstreams "10.0.0.0/8,127.0.0.1:20000-29999"] +# [-RoutesRemote https://github.com/team/routes.git -RoutesHost github] +# +# It installs the binaries to %ProgramFiles%\Ianitor, Caddy (pinned, SHA-512 checked) next to +# them, the state to %ProgramData%\Ianitor (ACL: Administrators, SYSTEM, LocalService), writes +# control.toml once, registers three services as LocalService (IanitorCaddy, IanitorControl, +# IanitorGuard; restart on failure), starts them and prints the first admin's sign-in link. +# -NoService runs the same setup but starts nothing (tests, or a manual start). + +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][string]$AdminHost, + [ValidateSet('letsencrypt', 'domi')][string]$Tls = 'letsencrypt', + [string]$DomiRoot = '', + [string]$PreviewDomain = '', + [string]$PreviewUpstreams = '', + [ValidateSet('', 'letsencrypt', 'domi')][string]$PreviewTls = '', + [string]$RoutesRemote = '', + [ValidateSet('gitea', 'github', 'gitlab')][string]$RoutesHost = 'gitea', + [string]$Root = (Join-Path $env:ProgramData 'Ianitor'), + [string]$Bin = (Join-Path $env:ProgramFiles 'Ianitor'), + [int]$HttpPort = 80, + [int]$HttpsPort = 443, + [int]$ApiPort = 7878, + [int]$CaddyAdminPort = 2019, + [string]$Caddy = '', + [switch]$NoService +) +$ErrorActionPreference = 'Stop' + +$CaddyVersion = '2.11.7' +$CaddySha512 = 'c308154504e53755958ffc62d8a2657ab17eefd6dd25c45dbb2c3d93d29519971f77ca652f7d0f2bcb7f980b9ba3822478865e29969d0272d7613550a43152b1' + +function Fail($m) { Write-Error "ianitor install: $m"; exit 1 } +function Plain($v, $name) { + if ($v -match '["\\''`$\r\n]') { Fail "$name contains a character that is not allowed" } +} +# Paths in TOML with forward slashes (control and Caddy read C:/ProgramData/... as is). +function Fwd($p) { return ($p -replace '\\', '/') } + +if (-not $NoService) { + $me = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() + if (-not $me.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Fail 'run it in an elevated PowerShell (Run as administrator)' } +} +Plain $AdminHost 'AdminHost'; Plain $PreviewDomain 'PreviewDomain'; Plain $PreviewUpstreams 'PreviewUpstreams' +Plain $RoutesRemote 'RoutesRemote'; Plain $DomiRoot 'DomiRoot' +$git = (Get-Command git.exe -ErrorAction SilentlyContinue) +if (-not $git) { Fail 'install Git for Windows first (https://git-scm.com/download/win); control keeps the routes in git' } +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +if (-not (Test-Path (Join-Path $here 'ianitor-control.exe'))) { Fail "ianitor-control.exe is not next to install.ps1 ($here)" } + +# ---------------------------------------------------------------- files +New-Item -ItemType Directory -Force $Bin | Out-Null +Copy-Item (Join-Path $here 'ianitor-control.exe') $Bin -Force +if (Test-Path (Join-Path $here 'web')) { + if (Test-Path (Join-Path $Bin 'web')) { Remove-Item -Recurse -Force (Join-Path $Bin 'web') } + Copy-Item -Recurse (Join-Path $here 'web') (Join-Path $Bin 'web') +} +$caddyExe = Join-Path $Bin 'caddy.exe' +if ($Caddy) { + Copy-Item $Caddy $caddyExe -Force +} elseif (-not (Test-Path $caddyExe)) { + $zip = Join-Path $env:TEMP "caddy_$CaddyVersion.zip" + $url = "https://github.com/caddyserver/caddy/releases/download/v$CaddyVersion/caddy_${CaddyVersion}_windows_amd64.zip" + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $zip + $got = (Get-FileHash -Algorithm SHA512 $zip).Hash.ToLower() + if ($got -ne $CaddySha512) { Remove-Item $zip; Fail "Caddy $CaddyVersion does not match its pinned SHA-512" } + $x = Join-Path $env:TEMP "caddy_$CaddyVersion" + Expand-Archive -Force $zip $x + Copy-Item (Join-Path $x 'caddy.exe') $caddyExe -Force + Remove-Item -Recurse -Force $zip, $x +} + +foreach ($d in 'control', 'edge', 'caddy', 'certs', 'caddy-state', 'logs', 'credentials') { + New-Item -ItemType Directory -Force (Join-Path $Root $d) | Out-Null +} +# Only Administrators, SYSTEM and the services' account (LocalService) see the state. +icacls $Root /inheritance:r /grant:r '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-18:(OI)(CI)F' '*S-1-5-19:(OI)(CI)M' | Out-Null + +function Secret($name) { + $f = Join-Path $Root "credentials\$name" + if (-not (Test-Path $f) -or (Get-Item $f).Length -eq 0) { + $b = New-Object byte[] 32 + [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($b) + [IO.File]::WriteAllText($f, (($b | ForEach-Object { $_.ToString('x2') }) -join '')) + } +} +Secret 'share-link-key'; Secret 'pki-password' +$engine = Join-Path $Root 'engine' +if (-not (Test-Path $engine)) { [IO.File]::WriteAllText($engine, "caddy`n") } +$rev = Join-Path $Root 'edge\share-revocations.json' +if (-not (Test-Path $rev)) { [IO.File]::WriteAllText($rev, '{"epoch":0,"deny":[]}') } +# Caddy starts with only its admin API; control loads the rest and keeps caddy.json current. +$caddyJson = Join-Path $Root 'caddy\caddy.json' +if (-not (Test-Path $caddyJson)) { + [IO.File]::WriteAllText($caddyJson, "{`"admin`":{`"listen`":`"127.0.0.1:$CaddyAdminPort`"}}") +} + +# ---------------------------------------------------------------- control.toml (once) +$config = Join-Path $Root 'control.toml' +if (Test-Path $config) { + Write-Host "ianitor install: $config exists; leaving it as it is." +} else { + $R = Fwd $Root + if (-not $PreviewTls) { $PreviewTls = $Tls } + $routes = '' + if ($RoutesRemote) { + $user = @{ github = 'x-access-token'; gitlab = 'oauth2'; gitea = 'ianitor' }[$RoutesHost] + $label = @{ github = 'GitHub'; gitlab = 'GitLab'; gitea = 'Gitea' }[$RoutesHost] + $routes = "remote = `"$RoutesRemote`"`nremote_name = `"$label`"`npush_username = `"$user`"`npush_credential = `"routes-token`"" + } + $pki = '' + if ($Tls -eq 'domi' -or $PreviewTls -eq 'domi') { + if (-not $DomiRoot) { Fail 'tls domi needs -DomiRoot (the Domi root certificate; docs/pki.md)' } + $pki = "[pki]`nroot_cert = `"$(Fwd $DomiRoot)`"" + } + $previews = '' + if ($PreviewDomain) { + $list = ($PreviewUpstreams -split ',' | Where-Object { $_.Trim() } | ForEach-Object { "`"$($_.Trim())`"" }) -join ', ' + $previews = "[previews]`ndomain = `"$PreviewDomain`"`ntls = `"$PreviewTls`"`nupstreams = [$list]" + } + $text = @" +# Written by Ianitor's Windows installer on $(Get-Date -Format yyyy-MM-dd). Edit freely; the +# installer never rewrites it. Secrets are files in $R/credentials, never values here. +listen = "127.0.0.1:$ApiPort" +state_dir = "$R/control" +credentials_dir = "$R/credentials" +git = "$(Fwd $git.Source)" + +[routes] +repo = "$R/routes.git" +$routes + +[edge] +config = "$R/edge/edge.json" +share_revocations = "$R/edge/share-revocations.json" + +[caddy] +config = "$R/caddy/caddy.json" + +[compile] +http_listen = "0.0.0.0:$HttpPort" +https_listen = "0.0.0.0:$HttpsPort" +cert_dir = "$R/certs" +state_dir = "$R/caddy-state" +access_log = "$R/logs/access.log" +caddy_credentials_dir = "$R/credentials" +caddy_admin = "127.0.0.1:$CaddyAdminPort" + +[engine] +file = "$R/engine" +units = "none" + +[ui] +hostname = "$AdminHost" +static_dir = "$(Fwd (Join-Path $Bin 'web'))" +admin_tls = "$Tls" + +$pki + +$previews +"@ + [IO.File]::WriteAllText($config, $text) + Write-Host "ianitor install: wrote $config" +} +& (Join-Path $Bin 'ianitor-control.exe') check --config $config +if ($LASTEXITCODE -ne 0) { Fail "the config does not check out: $config" } + +if ($NoService) { + Write-Host "ianitor install: set up in $Root; no services started (-NoService)." + exit 0 +} + +# ---------------------------------------------------------------- services +$ctl = Join-Path $Bin 'ianitor-control.exe' +$log = Join-Path $Root 'logs' +$services = @( + @{ Name = 'IanitorCaddy'; Display = 'Ianitor Caddy (data plane)'; Path = "`"$caddyExe`" run --config `"$caddyJson`"" }, + @{ Name = 'IanitorControl'; Display = 'Ianitor control (API and UI on loopback)'; Path = "`"$ctl`" service control --config `"$config`" --log-file `"$log\control.log`"" }, + @{ Name = 'IanitorGuard'; Display = 'Ianitor Caddy trial guard'; Path = "`"$ctl`" service caddy-guard --config `"$config`" --log-file `"$log\guard.log`"" } +) +foreach ($s in $services) { + if (Get-Service $s.Name -ErrorAction SilentlyContinue) { + Stop-Service $s.Name -Force -ErrorAction SilentlyContinue + sc.exe config $s.Name binPath= $s.Path | Out-Null + } else { + sc.exe create $s.Name binPath= $s.Path start= auto obj= 'NT AUTHORITY\LocalService' DisplayName= $s.Display | Out-Null + } + sc.exe failure $s.Name reset= 86400 actions= restart/2000/restart/5000/restart/30000 | Out-Null +} +foreach ($s in $services) { Start-Service $s.Name } + +Write-Host '' +Write-Host 'Ianitor is running (Caddy mode). Open this link to sign in as the first admin:' +& $ctl team setup-link --config $config diff --git a/scripts/preview.ps1 b/scripts/preview.ps1 new file mode 100644 index 0000000..b631209 --- /dev/null +++ b/scripts/preview.ps1 @@ -0,0 +1,60 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# The Windows twin of scripts/preview.sh (a Fabrica runner on Windows): +# +# scripts\preview.ps1 open -Project shop -Branch fix-42 -Upstream http://10.0.0.5:8080 [-Ttl 86400] +# scripts\preview.ps1 close -Project shop -Branch fix-42 +# scripts\preview.ps1 list +# +# $env:IANITOR_URL, $env:IANITOR_PREVIEW_TOKEN (a `--scope previews` token from the Custos team +# vault). An internal (Domi) admin host needs the Domi root in the machine's trusted roots. +param( + [Parameter(Mandatory = $true, Position = 0)][ValidateSet('open', 'close', 'list')][string]$Action, + [string]$Project, [string]$Branch, [string]$Upstream, [int]$Ttl = 0 +) +$ErrorActionPreference = 'Stop' +if (-not $env:IANITOR_URL -or -not $env:IANITOR_PREVIEW_TOKEN) { throw 'set IANITOR_URL and IANITOR_PREVIEW_TOKEN' } +$base = $env:IANITOR_URL.TrimEnd('/') +$headers = @{ Authorization = "Bearer $($env:IANITOR_PREVIEW_TOKEN)" } + +function Call($method, $path, $body) { + $p = @{ Method = $method; Uri = "$base$path"; Headers = $headers; UseBasicParsing = $true; ContentType = 'application/json' } + if ($body) { $p.Body = [Text.Encoding]::UTF8.GetBytes(($body | ConvertTo-Json -Compress)) } + try { + $r = Invoke-WebRequest @p + return @{ Code = [int]$r.StatusCode; Json = ($r.Content | ConvertFrom-Json) } + } catch [System.Net.WebException] { + $resp = $_.Exception.Response + if (-not $resp) { throw } + $text = (New-Object IO.StreamReader($resp.GetResponseStream())).ReadToEnd() + return @{ Code = [int]$resp.StatusCode; Json = ($text | ConvertFrom-Json) } + } +} + +switch ($Action) { + 'open' { + $body = @{ project = $Project; branch = $Branch; upstream = $Upstream } + if ($Ttl -gt 0) { $body.ttl = $Ttl } + $r = Call POST '/api/v1/previews' $body + if ($r.Code -ne 202) { throw "preview: $($r.Json.error.message)" } + $host_ = $r.Json.preview.hostname + for ($i = 0; $i -lt 150; $i++) { + $s = Call GET "/api/v1/previews/$host_" $null + if ($s.Code -ne 200) { throw "preview: $($s.Json.error.message)" } + if ($s.Json.preview.state -eq 'live') { Write-Output $r.Json.preview.url; exit 0 } + if ($s.Json.preview.state -eq 'failed') { throw "preview: $($s.Json.preview.problem)" } + Start-Sleep -Seconds 2 + } + throw 'preview: not live after 5 minutes' + } + 'close' { + $r = Call POST '/api/v1/previews/close' @{ project = $Project; branch = $Branch } + if ($r.Code -eq 202) { 'closing' } elseif ($r.Code -eq 404) { 'no preview' } else { throw "preview: $($r.Json.error.message)" } + } + 'list' { + $r = Call GET '/api/v1/previews' $null + $r.Json.items | ForEach-Object { "$($_.url)`t$($_.project)`t$($_.branch)`t$($_.state)`tuntil $($_.expires_at)" } + } +} diff --git a/scripts/preview.sh b/scripts/preview.sh new file mode 100644 index 0000000..39f6b27 --- /dev/null +++ b/scripts/preview.sh @@ -0,0 +1,78 @@ +#!/bin/sh +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# A client of Ianitor's preview API (docs/previews.md) for a Fabrica pipeline step or a script: +# +# scripts/preview.sh open [ttl-seconds] prints the preview's URL +# scripts/preview.sh close +# scripts/preview.sh list +# +# IANITOR_URL Ianitor's admin address, e.g. https://ianitor.example.org +# IANITOR_PREVIEW_TOKEN a token made with `ianitor-control token create --scope previews` +# (kept in the Custos team vault; never in the repository or a log) +# IANITOR_CA optional: a CA file for curl (a Domi root, for an internal admin host) +# +# `open` waits until the preview is live (its apply kept) and fails with Ianitor's reason +# otherwise. Needs curl and jq. +set -eu + +: "${IANITOR_URL:?set IANITOR_URL}" +: "${IANITOR_PREVIEW_TOKEN:?set IANITOR_PREVIEW_TOKEN}" +command -v jq >/dev/null || { echo "preview: needs jq" >&2; exit 2; } + +api() { + # The token goes in a header read from stdin, so it never shows in `ps`. + method=$1; path=$2; body=${3:-} + set -- -sS -X "$method" -H "Content-Type: application/json" -H @- -w '\n%{http_code}' + [ -n "${IANITOR_CA:-}" ] && set -- "$@" --cacert "$IANITOR_CA" + [ -n "$body" ] && set -- "$@" --data "$body" + printf 'Authorization: Bearer %s\n' "$IANITOR_PREVIEW_TOKEN" | curl "$@" "${IANITOR_URL%/}$path" +} + +split() { # sets BODY and CODE from api's output + CODE=$(printf '%s' "$1" | tail -n1) + BODY=$(printf '%s' "$1" | sed '$d') +} + +fail() { + echo "preview: $(printf '%s' "$BODY" | jq -r '.error.message // .' 2>/dev/null || printf '%s' "$BODY")" >&2 + exit 1 +} + +case "${1:-}" in + open) + [ $# -ge 4 ] || { echo "usage: $0 open [ttl]" >&2; exit 2; } + body=$(jq -cn --arg p "$2" --arg b "$3" --arg u "$4" --arg t "${5:-}" \ + '{project:$p, branch:$b, upstream:$u} + (if $t == "" then {} else {ttl: ($t|tonumber)} end)') + split "$(api POST /api/v1/previews "$body")" + [ "$CODE" = 202 ] || fail + host=$(printf '%s' "$BODY" | jq -r .preview.hostname) + url=$(printf '%s' "$BODY" | jq -r .preview.url) + i=0 + while :; do + split "$(api GET "/api/v1/previews/$host")" + [ "$CODE" = 200 ] || fail + state=$(printf '%s' "$BODY" | jq -r .preview.state) + case "$state" in + live) echo "$url"; exit 0 ;; + failed) echo "preview: $(printf '%s' "$BODY" | jq -r '.preview.problem // "the apply failed"')" >&2; exit 1 ;; + esac + i=$((i + 1)); [ $i -le 150 ] || { echo "preview: not live after 5 minutes" >&2; exit 1; } + sleep 2 + done + ;; + close) + [ $# -eq 3 ] || { echo "usage: $0 close " >&2; exit 2; } + split "$(api POST /api/v1/previews/close "$(jq -cn --arg p "$2" --arg b "$3" '{project:$p, branch:$b}')")" + case "$CODE" in 202) echo "closing"; ;; 404) echo "no preview"; ;; *) fail ;; esac + ;; + list) + split "$(api GET /api/v1/previews)" + [ "$CODE" = 200 ] || fail + printf '%s' "$BODY" | jq -r '.items[] | "\(.url)\t\(.project)\t\(.branch)\t\(.state)\tuntil \(.expires_at)"' + ;; + *) + echo "usage: $0 open|close|list ..." >&2; exit 2 ;; +esac diff --git a/scripts/smoke-windows.ps1 b/scripts/smoke-windows.ps1 new file mode 100644 index 0000000..c01abc6 --- /dev/null +++ b/scripts/smoke-windows.ps1 @@ -0,0 +1,129 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# Windows Caddy mode, end to end through the installer (T4). Everything happens in -Work, on +# non-standard ports, with a throw-away Domi root; no service is registered, no certificate is +# trusted, nothing is left running: +# +# 1. deploy\windows\install.ps1 -NoService (the release ianitor-control.exe, a given caddy.exe) +# 2. Caddy and control started in the console, as the services would start them +# 3. the intermediate signed offline with the throw-away root (docs/pki.md), control restarted +# so it adds the admin host +# 4. a previews-only token opens a branch preview with scripts\preview.ps1 (Fabrica's client) +# 5. the preview answers through Caddy with a Domi certificate; the admin host reaches control +# 6. the preview is closed and stops answering +# +# scripts\smoke-windows.ps1 -Control -Caddy -Work +param( + [Parameter(Mandatory = $true)][string]$Control, + [Parameter(Mandatory = $true)][string]$Caddy, + [Parameter(Mandatory = $true)][string]$Work +) +$ErrorActionPreference = 'Stop' +$repo = Split-Path -Parent $PSScriptRoot +$Http = 18080; $Https = 18443; $Api = 17878; $Admin = 12019; $AppPort = 23456 +$procs = @() +function Step($m) { Write-Host "== $m" } +function Check($ok, $m) { if (-not $ok) { throw "FAILED: $m" } ; Write-Host " ok: $m" } + +try { + if (Test-Path $Work) { throw "$Work exists; give an empty, new folder" } + New-Item -ItemType Directory $Work | Out-Null + $pkg = Join-Path $Work 'pkg'; New-Item -ItemType Directory $pkg | Out-Null + Copy-Item $Control (Join-Path $pkg 'ianitor-control.exe') + Copy-Item (Join-Path $repo 'deploy\windows\install.ps1') $pkg + $ctl = Join-Path $Work 'bin\ianitor-control.exe' + $root = Join-Path $Work 'root' + $offline = Join-Path $Work 'offline-root' + $pass = Join-Path $Work 'offline-pass.txt' + [IO.File]::WriteAllText($pass, 'smoke-test-offline-passphrase') + + Step 'a throw-away Domi root (offline step)' + & (Join-Path $pkg 'ianitor-control.exe') ca init --out $offline --passphrase-file $pass + Check ($LASTEXITCODE -eq 0) 'ca init' + + Step 'install.ps1 -NoService' + & (Join-Path $pkg 'install.ps1') -NoService -AdminHost 'ianitor.smoke.test' -Tls domi ` + -DomiRoot (Join-Path $offline 'domi-root.crt') -PreviewDomain 'pv.smoke.test' ` + -PreviewUpstreams "127.0.0.1:20000-29999" -Root $root -Bin (Join-Path $Work 'bin') ` + -HttpPort $Http -HttpsPort $Https -ApiPort $Api -CaddyAdminPort $Admin -Caddy $Caddy + $config = Join-Path $root 'control.toml' + Check (Test-Path $config) 'control.toml written' + + function Start-Control { + $env:IANITOR_LOG_FILE = Join-Path $root 'logs\control.log' + $p = Start-Process -PassThru -WindowStyle Hidden -FilePath $ctl -ArgumentList '--config', "`"$config`"" + Remove-Item Env:\IANITOR_LOG_FILE + for ($i = 0; $i -lt 60; $i++) { + try { $c = New-Object Net.Sockets.TcpClient('127.0.0.1', $Api); $c.Close(); return $p } catch { Start-Sleep -Milliseconds 500 } + } + throw 'control did not listen' + } + + Step 'Caddy and control, as the services start them' + $env:APPDATA = Join-Path $Work 'caddy-appdata' + $procs += Start-Process -PassThru -WindowStyle Hidden -FilePath (Join-Path $Work 'bin\caddy.exe') ` + -ArgumentList 'run', '--config', "`"$(Join-Path $root 'caddy\caddy.json')`"" ` + -RedirectStandardError (Join-Path $root 'logs\caddy.log') -RedirectStandardOutput (Join-Path $root 'logs\caddy.out') + $p = Start-Control; $procs += $p + + $adminTok = (& $ctl token create --name smoke-admin --config $config) | Select-Object -Last 1 + $previewTok = (& $ctl token create --name fabrica-previews --scope previews --config $config) | Select-Object -Last 1 + $auth = @{ Authorization = "Bearer $adminTok" } + $base = "http://127.0.0.1:$Api" + + Step 'the intermediate, signed offline' + $r = Invoke-RestMethod -Method POST -Uri "$base/api/v1/certs/intermediate/renewal" -Headers $auth + $csr = Join-Path $Work 'intermediate.csr' + Invoke-WebRequest -UseBasicParsing -Uri "$base/api/v1/pki-requests/$($r.request_id)/csr" -Headers $auth -OutFile $csr + $crt = Join-Path $Work 'intermediate.crt' + & $ctl ca sign --root $offline --csr $csr --out $crt --yes --passphrase-file $pass + Check ($LASTEXITCODE -eq 0) 'ca sign' + & $ctl pki install $crt --config $config + Check ($LASTEXITCODE -eq 0) 'pki install' + + Step 'control again (it adds the admin host now that it can issue its certificate)' + Stop-Process -Id $p.Id -Force; Start-Sleep 1 + $procs = @($procs | Where-Object { $_.Id -ne $p.Id }) + $p = Start-Control; $procs += $p + $deadline = (Get-Date).AddSeconds(120) + do { + Start-Sleep 2 + $hosts = (Invoke-RestMethod -Uri "$base/api/v1/hosts" -Headers $auth).hosts.hostname + } until (($hosts -contains 'ianitor.smoke.test') -or (Get-Date) -gt $deadline) + Check ($hosts -contains 'ianitor.smoke.test') 'admin host in the routes' + + Step 'a branch build on 127.0.0.1' + $site = Join-Path $Work 'app'; New-Item -ItemType Directory $site | Out-Null + [IO.File]::WriteAllText((Join-Path $site 'index.html'), 'hello from fix-42') + $procs += Start-Process -PassThru -WindowStyle Hidden -FilePath 'python' -ArgumentList '-m', 'http.server', $AppPort, '--bind', '127.0.0.1', '--directory', "`"$site`"" + Start-Sleep 2 + + Step 'Fabrica opens the preview (scripts\preview.ps1, previews-only token)' + $env:IANITOR_URL = $base; $env:IANITOR_PREVIEW_TOKEN = $previewTok + $url = & (Join-Path $repo 'scripts\preview.ps1') open -Project 'shop' -Branch 'fix-42' -Upstream "http://127.0.0.1:$AppPort" -Ttl 3600 + Check ($url -eq 'https://fix-42--shop.pv.smoke.test/') "preview URL $url" + $ca = Join-Path $offline 'domi-root.crt' + $body = & curl.exe -sS --cacert $ca --resolve "fix-42--shop.pv.smoke.test:${Https}:127.0.0.1" "https://fix-42--shop.pv.smoke.test:$Https/" + Check ($body -eq 'hello from fix-42') "the preview answers through Caddy with a Domi certificate ($body)" + $code = & curl.exe -s -o NUL -w '%{http_code}' --cacert $ca --resolve "ianitor.smoke.test:${Https}:127.0.0.1" "https://ianitor.smoke.test:$Https/api/v1/team" + Check ($code -eq '401') "the admin host reaches control and needs a sign-in ($code)" + $deny = & curl.exe -s -o NUL -w '%{http_code}' -H "Authorization: Bearer $previewTok" "$base/api/v1/hosts" + Check ($deny -eq '403') "the preview token cannot read the hosts ($deny)" + $list = & (Join-Path $repo 'scripts\preview.ps1') list + Check ($list -match 'fix-42--shop') 'listed' + + Step 'closed on merge' + & (Join-Path $repo 'scripts\preview.ps1') close -Project 'shop' -Branch 'fix-42' | Out-Null + $deadline = (Get-Date).AddSeconds(90) + do { + Start-Sleep 2 + $code = & curl.exe -s -o NUL -w '%{http_code}' --cacert $ca --resolve "fix-42--shop.pv.smoke.test:${Https}:127.0.0.1" "https://fix-42--shop.pv.smoke.test:$Https/" + } until (($code -ne '200') -or (Get-Date) -gt $deadline) + Check ($code -ne '200') "gone after close ($code)" + Write-Host 'SMOKE PASSED' +} finally { + foreach ($p in $procs) { try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {} } + Remove-Item Env:\IANITOR_PREVIEW_TOKEN -ErrorAction SilentlyContinue +}