steid

@jamesgill /

steid/install.sh
Bourne Again Shell (bash)38.8 KBCode·Blame·History·Raw
1#!/bin/sh
2#
3# Steid installer for a fresh Debian/Ubuntu server.
4#
5# curl -fsSL https://releases.steid.dev/install.sh | sh -s -- --domain git.example.com
6#
7# It installs Steid to /opt/steid, keeps state in /var/lib/steid, runs it as an
8# unprivileged system user under systemd, and puts Caddy in front of it with an
9# automatic HTTPS certificate for the domain you give.
10#
11# Re-running it is an upgrade: it downloads the requested version, replaces the
12# binary and assets, rewrites the unit and the Caddyfile, and restarts. It never
13# touches /var/lib/steid, and it never overwrites /etc/steid/steid.env once that
14# exists, so anything you have edited there survives.
15#
16# ON `curl | sh`: you are being asked to run a script you have not read, as root,
17# from a URL. That is a real trust decision and "it's convenient" is not an
18# answer to it. Two honest alternatives: download it first and read it
19# (`curl -fsSL … -o install.sh; less install.sh; sh install.sh --domain …`), or
20# follow the manual path in README.md, which is the same dozen commands written
21# out. Nothing here is magic; the script exists to save typing, not to be trusted
22# blindly.
23
24set -eu
25
26# --- WHERE RELEASES COME FROM -----------------------------------------------
27#
28# Since 0.6.0: **https://releases.steid.dev** — an S3 bucket behind CloudFront,
29# run by the project. `jpgill.dev` serves the same files as a mirror and will
30# keep doing so until the author's instance moves onto the managed fleet; see
31# plans/decisions/0009-releases-from-releases-steid-dev.md for why the release
32# host stopped being a Steid instance.
33#
34# The short version: from 0.4.0 the artefacts came off jpgill.dev, which is the
35# author's live site *and* an instance of Steid. Serving Steid from Steid was the
36# point. But the control plane now installs boxes headlessly from cloud-init, so
37# every provision depends on that one instance being up, and an install that
38# 404s reads as a broken product rather than a busy weekend. A dumb static host
39# is the right dependency for a download; the demonstration was made and does not
40# need making on every install.
41#
42# `--tarball` is still the bootstrap for the very first instance of a *new*
43# distribution host, and the offline path.
44#
45# The layout expected here, and produced by release.sh, is unchanged from 0.4.0:
46#
47# ${RELEASE_BASE_URL}/v${VERSION}/steid-${VERSION}-${TARGET}.tar.gz
48# ${RELEASE_BASE_URL}/v${VERSION}/steid-${VERSION}-${TARGET}.tar.gz.sha256
49#
50# so a link published against the old host still resolves against the mirror,
51# and the two hosts differ only in their base.
52#
53# This is the *project's* distribution host — a constant, and NOT the `--domain`
54# the person running this installs onto. Everyone downloads Steid from here; each
55# installer then runs their own instance on their own hostname. Point
56# STEID_RELEASE_BASE_URL at your own mirror to install from somewhere else; the
57# path layout below is the whole contract.
58#
59# The version lives at the root of this host rather than under a repository path
60# because the host is not an instance of Steid and has no /{handle} namespace to
61# squat. On the mirror the old scoped path stays exactly as it was.
62RELEASE_BASE_URL="${STEID_RELEASE_BASE_URL:-https://releases.steid.dev}"
63
64# The version to install. Pinned rather than "latest" because there is no
65# redirect to resolve "latest" against, and a pinned default makes the upgrade
66# path explicit: `--version 0.8.2`.
67VERSION="${STEID_VERSION:-0.8.2}"
68# ----------------------------------------------------------------------------
69
70# The build target to fetch. musl is preferred — one static binary that does not
71# care which glibc the host has — but whether Steid builds against musl at all is
72# still being established, so the choice is a variable rather than a fact.
73# Override with --flavour gnu if the published artefacts are glibc.
74# gnu, matching what release.sh builds. musl was tried and rejected: it fails on
75# `ring` with Debian's musl-gcc wrapper, and — the decisive part — musl buys a
76# binary with no runtime dependencies while Steid hard-requires `git` on PATH, so
77# the portability cannot be used. THIS MUST AGREE WITH release.sh: they were
78# briefly out of step and the symptom was a confusing "checksum mismatch",
79# because the installer was looking for a musl tarball that was never built.
80FLAVOUR="gnu"
81
82DOMAIN=""
83WWW=0
84FORCE_CADDYFILE=0
85# A local artefact to install instead of downloading one. This exists because of
86# a bootstrap: the very first instance is what will *serve* the releases, so at
87# that moment there is nowhere to download from. It doubles as the offline and
88# air-gapped path.
89TARBALL=""
90PORT="3000"
91# Scheduled backups are OFF unless asked for. A timer that appears without being
92# asked for is a surprise, and this one writes a full copy of the instance to
93# disk every night — which is exactly what somebody with a small volume needs to
94# have agreed to. Omitting the flag on a later run leaves whatever is already
95# installed alone, the way the Caddyfile and the env file are left alone;
96# `--backups off` is how you actually remove it.
97BACKUPS=""
98# The owner to create at boot, written into steid.env. Both or neither: half of
99# an owner is refused below rather than quietly installing an instance that comes
100# up unclaimed, which is the state these exist to avoid.
101OWNER_EMAIL=""
102OWNER_HANDLE=""
103# The organisation the instance is for, written into steid.env beside the owner.
104# Optional, and only meaningful with an owner — an organisation with nobody to
105# own it is not a state Steid has, so it is refused below rather than written.
106# With it, the instance comes up as a company's Steid: the root lands on the
107# organisation and the setup wizard has nothing left to ask.
108OWNER_ORG=""
109OWNER_ORG_NAME=""
110# The operator surface's bearer token. Unlike everything else in steid.env this one
111# IS rewritten on a later run when the flag is given — see the note above
112# set_env_secret. Empty means "leave whatever is there alone", which is what an
113# ordinary upgrade does.
114OPERATOR_TOKEN=""
115INSTALL_DIR="/opt/steid"
116STATE_DIR="/var/lib/steid"
117CONF_DIR="/etc/steid"
118STEID_USER="steid"
119INSTALL_CADDY=1
120
121die() { echo "install.sh: $*" >&2; exit 1; }
122say() { echo "==> $*"; }
123
124# Writes a value into steid.env as one double-quoted word.
125#
126# **steid.env has two readers, and they must agree.** systemd reads it for the service
127# (`EnvironmentFile=`), and POSIX sh reads it with `.`: the Steid Cloud console sources
128# it as root before every command it runs on this box, and so does anyone at a root
129# shell. Inside double quotes both take a backslash before `"`, `\`, `$` or a backtick
130# as that character and keep everything else as it is, so escaping exactly those four
131# is the whole rule. The other spellings do not agree: unquoted, sh splits on a space
132# and runs `$(…)` where systemd keeps the text; and no single-quoted spelling holds a
133# `'` both read alike, which an address like o'brien@example.com needs.
134#
135# Checked against both readers on Debian 13 (systemd 257, dash) for `'`, `"`, `$`,
136# backticks, backslashes and spaces — see plans/progress.md. Values that no quoting
137# can make them agree on are refused first, by check_env_value.
138env_quote() {
139 printf '"%s"' "$(printf '%s' "$1" | sed 's/[\\"$`]/\\&/g')"
140}
141
142# Refuses a value env_quote cannot write so that both readers agree. Called on every
143# value this script writes into steid.env, before anything is installed.
144#
145# - **Control characters, line breaks among them.** A quoted line break is read alike
146# by both parsers, but this file has line-oriented readers too: set_env_secret's
147# grep, and the console's sed for STEID_PUBLIC_URL.
148# - **What systemd will not read.** One value that is not valid UTF-8, or holds a
149# Unicode noncharacter or a code point past U+10FFFF, makes systemd refuse the
150# *whole* file, so steid.service could never start, while sh reads it happily.
151# glibc's iconv catches invalid UTF-8; the grep catches the rest, which iconv
152# passes.
153#
154# The message names the flag and never the value: one of them is a secret.
155check_env_value() {
156 case "$2" in
157 *[[:cntrl:]]*) die "$1 must be one line, with no tabs or other control characters" ;;
158 esac
159 printf '%s' "$2" | iconv -f UTF-8 -t UTF-8 >/dev/null 2>&1 \
160 || die "$1 is not valid UTF-8, and systemd would refuse the whole of steid.env"
161 if printf '%s' "$2" | LC_ALL=C grep -q \
162 -e "$(printf '\357\267[\220-\257]')" \
163 -e "$(printf '\357\277[\276\277]')" \
164 -e "$(printf '[\360-\364][\217\237\257\277]\277[\276\277]')" \
165 -e "$(printf '\364[\220-\277]')" \
166 -e "$(printf '[\365-\377]')"; then
167 die "$1 holds a character systemd will not read (a Unicode noncharacter, or past U+10FFFF), and it would refuse the whole of steid.env"
168 fi
169}
170
171# Sets one variable in steid.env, replacing the line if it is already there.
172#
173# **The one exception to "written once and left alone".** Every other setting in that
174# file is written on the first install and never touched again, so an upgrade cannot
175# revert something somebody deliberately changed. The operator token is different
176# because it is not somebody's edit: it is a machine credential the thing that
177# provisioned this box holds, it gets rotated, and a box that comes up with the
178# operator surface off is a box a control plane cannot see. Only a run that passes the
179# flag rewrites it; an upgrade without it leaves the line exactly where it was.
180#
181# **The value never reaches the terminal, a log or `ps`.** It is expanded into a
182# here-doc inside this function and nowhere else; no `echo`, no `say`, no error
183# message carries it. `set -x` is off — turning it on would print this like anything
184# else, which is the ordinary hazard of tracing a script that handles a secret.
185#
186# The replacement is written beside the file under `umask 077` and moved into place,
187# so the token is never briefly world-readable and an interrupted run cannot leave a
188# truncated env file.
189set_env_secret() {
190 _key="$1"
191 _value="$2"
192 _file="${CONF_DIR}/steid.env"
193 _tmp="${_file}.new"
194
195 (umask 077; : > "$_tmp")
196
197 if [ -f "$_file" ]; then
198 # Both the line and the comment this function wrote above it, or a rotation
199 # would stack a fresh comment on every run. `|| true`: grep exits 1 when it
200 # prints nothing, which under `set -e` would end the install.
201 grep -v -e "^${_key}=" -e "^# Written by install.sh --operator-token\.\$" \
202 "$_file" >> "$_tmp" || true
203 fi
204
205 # `printf`, not a here-doc: a here-doc expands `$…` and backticks in the value, and
206 # the value is a token somebody else generated. printf's %s takes it literally, and
207 # env_quote makes systemd and sh read it alike whatever it holds.
208 printf '%s\n' "# Written by install.sh --operator-token." "${_key}=$(env_quote "$_value")" >> "$_tmp"
209
210 mv "$_tmp" "$_file"
211 chmod 640 "$_file"
212 chown "root:${STEID_USER}" "$_file"
213}
214
215usage() {
216 cat >&2 <<'USAGE'
217Usage: install.sh --domain <hostname> [options]
218
219 --tarball <path> install from a local tarball instead of downloading.
220 Needed for the first install, which has nowhere to
221 download from yet, and for offline installs.
222 --www also serve www.<hostname>, redirecting it to the bare
223 hostname. Requires a www DNS record pointing here —
224 without one Caddy retries a certificate it cannot get.
225 --force-caddyfile overwrite an existing /etc/caddy/Caddyfile. Off by
226 default so an upgrade cannot silently discard your edits.
227 --domain <hostname> the public hostname, e.g. git.example.com. Its DNS must
228 already point at this machine or the certificate cannot
229 be issued. Required.
230 --version <v> release to install (default: the pinned one above)
231 --flavour <musl|gnu> which build to fetch (default: gnu — see below; musl
232 is not built, and asking for it gets a 404)
233 --backups daily install a systemd timer that runs `steid backup` into
234 /var/lib/steid/backups every night, keeps the most
235 recent 14, and tells the settings page when it last
236 ran. Off unless you ask. `--backups off` removes it.
237 These stay on the same machine — see the note at the
238 end for copying them somewhere else.
239 --owner-email <addr> create this owner at first boot, so the instance is
240 --owner-handle <name> never unclaimed on the internet. Both or neither. The
241 owner gets no usable password: get in with
242 `steid reset-password <handle>` on this machine.
243 --owner-org <handle> also create this organisation at first boot, owned by
244 that owner, and land the root of the instance on it.
245 Needs the two flags above. Without it the root lands on
246 the owner's own page, which is what a one-person
247 instance wants.
248 --owner-org-name <n> the organisation's display name, e.g. "Acme Inc". Needs
249 --owner-org. Quote it if it has spaces.
250 --operator-token <t> bearer token for the operator surface (/metrics and the
251 detailed /api/instance). Written into steid.env before
252 Steid is started, so the instance never serves with that
253 surface off. This is the one setting a later run WILL
254 rewrite — pass it again to rotate the token; omit it and
255 the existing line is left alone like everything else.
256 Generate one with `openssl rand -hex 32`. It is never
257 printed.
258 --port <n> loopback port Steid listens on (default: 3000)
259 --no-caddy install and run Steid but do not touch Caddy. Only for
260 putting your own TLS-terminating proxy in front. Steid
261 has no TLS of its own; without a proxy, access tokens
262 cross the network in cleartext.
263 -h, --help this
264USAGE
265 exit "${1:-0}"
266}
267
268# --- arguments --------------------------------------------------------------
269
270while [ $# -gt 0 ]; do
271 case "$1" in
272 --domain) DOMAIN="${2:-}"; [ -n "$DOMAIN" ] || die "--domain needs a hostname"; shift 2 ;;
273 --tarball) TARBALL="${2:-}"; [ -n "$TARBALL" ] || die "--tarball needs a path"; shift 2 ;;
274 --www) WWW=1; shift ;;
275 --force-caddyfile) FORCE_CADDYFILE=1; shift ;;
276 --version) VERSION="${2:-}"; [ -n "$VERSION" ] || die "--version needs a value"; shift 2 ;;
277 --flavour) FLAVOUR="${2:-}"; [ -n "$FLAVOUR" ] || die "--flavour needs a value"; shift 2 ;;
278 --port) PORT="${2:-}"; [ -n "$PORT" ] || die "--port needs a number"; shift 2 ;;
279 --owner-email) OWNER_EMAIL="${2:-}"; [ -n "$OWNER_EMAIL" ] || die "--owner-email needs an address"; shift 2 ;;
280 --owner-handle) OWNER_HANDLE="${2:-}"; [ -n "$OWNER_HANDLE" ] || die "--owner-handle needs a handle"; shift 2 ;;
281 --owner-org) OWNER_ORG="${2:-}"; [ -n "$OWNER_ORG" ] || die "--owner-org needs a handle"; shift 2 ;;
282 --owner-org-name) OWNER_ORG_NAME="${2:-}"; [ -n "$OWNER_ORG_NAME" ] || die "--owner-org-name needs a name"; shift 2 ;;
283 # Deliberately no value in the die message, here or anywhere below.
284 --operator-token) OPERATOR_TOKEN="${2:-}"; [ -n "$OPERATOR_TOKEN" ] || die "--operator-token needs a value"; shift 2 ;;
285 --backups) BACKUPS="${2:-}"; [ -n "$BACKUPS" ] || die "--backups needs daily or off"; shift 2 ;;
286 --no-caddy) INSTALL_CADDY=0; shift ;;
287 -h|--help) usage 0 ;;
288 *) echo "install.sh: unknown argument: $1" >&2; usage 1 ;;
289 esac
290done
291
292# Fail early and loudly rather than half-installing. Everything below this point
293# assumes these hold.
294[ "$(id -u)" = "0" ] || die "must run as root (try: sudo sh install.sh --domain …)"
295
296if [ "$INSTALL_CADDY" = 1 ]; then
297 [ -n "$DOMAIN" ] || die "--domain is required. Caddy needs a real hostname to
298 obtain a certificate for, and Steid has no TLS of its own. If you are putting
299 your own proxy in front, pass --no-caddy."
300fi
301
302if [ -n "$DOMAIN" ]; then
303 case "$DOMAIN" in
304 *[!A-Za-z0-9.-]*|-*|.*|*.) die "'$DOMAIN' does not look like a hostname" ;;
305 esac
306fi
307
308case "$PORT" in
309 ''|*[!0-9]*) die "--port must be a number" ;;
310esac
311
312case "$FLAVOUR" in
313 musl|gnu) ;;
314 *) die "--flavour must be 'musl' or 'gnu'" ;;
315esac
316
317case "$BACKUPS" in
318 ''|daily|off) ;;
319 *) die "--backups must be 'daily' or 'off'" ;;
320esac
321
322# Both or neither, and Steid itself refuses to start on half of them — so this is
323# the same rule said at the moment it can still be fixed by retyping the command.
324# Steid validates the values (the handle's shape, the reserved list, the email);
325# this only checks that you gave both.
326if [ -n "$OWNER_EMAIL" ] && [ -z "$OWNER_HANDLE" ]; then
327 die "--owner-email needs --owner-handle too. Pass both or neither."
328fi
329if [ -n "$OWNER_HANDLE" ] && [ -z "$OWNER_EMAIL" ]; then
330 die "--owner-handle needs --owner-email too. Pass both or neither."
331fi
332
333# An organisation with nobody to own it is not a state Steid has, so the same rule
334# is said here rather than at the first boot that would have to refuse it. Steid
335# validates the handle itself — the shape, and the reserved list.
336if [ -n "$OWNER_ORG" ] && { [ -z "$OWNER_EMAIL" ] || [ -z "$OWNER_HANDLE" ]; }; then
337 die "--owner-org needs --owner-email and --owner-handle too."
338fi
339if [ -n "$OWNER_ORG_NAME" ] && [ -z "$OWNER_ORG" ]; then
340 die "--owner-org-name needs --owner-org too."
341fi
342
343# Every value this script writes into steid.env, checked before anything is installed:
344# a value systemd and sh would read differently is refused here, where retyping the
345# command fixes it, rather than written into a file a later run never rewrites.
346[ -z "$OWNER_EMAIL" ] || check_env_value --owner-email "$OWNER_EMAIL"
347[ -z "$OWNER_HANDLE" ] || check_env_value --owner-handle "$OWNER_HANDLE"
348[ -z "$OWNER_ORG" ] || check_env_value --owner-org "$OWNER_ORG"
349[ -z "$OWNER_ORG_NAME" ] || check_env_value --owner-org-name "$OWNER_ORG_NAME"
350[ -z "$OPERATOR_TOKEN" ] || check_env_value --operator-token "$OPERATOR_TOKEN"
351
352# Where the timer writes, how many it keeps, and the file it touches afterwards.
353# Steid reads only the marker's modification time, so this and the settings page
354# cannot drift into disagreeing about a format.
355BACKUP_DIR="${STATE_DIR}/backups"
356BACKUP_KEEP=14
357BACKUP_MARKER="${BACKUP_DIR}/.last-backup"
358
359case "${TARBALL:+local}${RELEASE_BASE_URL}" in
360 local*) : ;; # installing from a file; the download URL is irrelevant
361 *REPLACE-ME*) die "RELEASE_BASE_URL is still the placeholder. Edit the top of
362 this script (or set STEID_RELEASE_BASE_URL) to point at real release artefacts,
363 or pass --tarball to install from a local file." ;;
364esac
365
366command -v systemctl >/dev/null 2>&1 || die "no systemd here; follow the manual path in README.md"
367command -v apt-get >/dev/null 2>&1 || die "this installer only knows apt (Debian/Ubuntu).
368 The manual path in README.md works on anything with systemd."
369
370case "$(uname -m)" in
371 x86_64|amd64) ARCH="x86_64" ;;
372 aarch64|arm64) ARCH="aarch64" ;;
373 *) die "unsupported architecture: $(uname -m). Only x86_64 and aarch64 are built." ;;
374esac
375
376TARGET="${ARCH}-unknown-linux-${FLAVOUR}"
377NAME="steid-${VERSION}-${TARGET}"
378URL="${RELEASE_BASE_URL}/v${VERSION}/${NAME}.tar.gz"
379
380say "installing Steid ${VERSION} (${TARGET}) for ${DOMAIN:-<no domain>}"
381
382# --- prerequisites ----------------------------------------------------------
383
384# git is not optional and not a runtime nicety: Steid shells out to `git init
385# --bare` to create a repository and to `git http-backend` to serve every clone
386# and push. Without it the install succeeds and the first repository fails.
387say "installing prerequisites (git, curl, ca-certificates)"
388export DEBIAN_FRONTEND=noninteractive
389apt-get update -qq
390apt-get install -y -qq --no-install-recommends git curl ca-certificates
391
392# --- download ---------------------------------------------------------------
393
394TMP="$(mktemp -d)"
395# shellcheck disable=SC2064 # $TMP is expanded now on purpose: it never changes.
396trap "rm -rf '$TMP'" EXIT INT TERM
397
398if [ -n "$TARBALL" ]; then
399 [ -f "$TARBALL" ] || die "--tarball: no such file: ${TARBALL}"
400 say "installing from ${TARBALL}"
401 cp "$TARBALL" "${TMP}/${NAME}.tar.gz"
402
403 # A checksum beside a local file is verified when present, but not demanded:
404 # whoever passes --tarball already chose the bytes, so refusing to proceed
405 # without a .sha256 would block the bootstrap this option exists for.
406 if [ -f "${TARBALL}.sha256" ]; then
407 say "verifying checksum"
408 # Compared by value, not with `sha256sum -c`: that matches on the filename
409 # recorded inside the .sha256, which need not be what the file is called
410 # by the time someone passes it here.
411 EXPECTED="$(cut -d" " -f1 < "${TARBALL}.sha256")"
412 ACTUAL="$(sha256sum < "${TMP}/${NAME}.tar.gz" | cut -d" " -f1)"
413 [ "$EXPECTED" = "$ACTUAL" ] \
414 || die "checksum mismatch — ${TARBALL} does not match its .sha256"
415 else
416 say "no ${TARBALL}.sha256 beside it; installing unverified"
417 fi
418else
419 say "downloading ${URL}"
420 curl -fsSL "$URL" -o "${TMP}/${NAME}.tar.gz" \
421 || die "download failed. Is version ${VERSION} published for ${TARGET}?"
422 curl -fsSL "${URL}.sha256" -o "${TMP}/${NAME}.tar.gz.sha256" \
423 || die "checksum file missing next to the tarball; refusing to install unverified"
424
425 say "verifying checksum"
426 ( cd "$TMP" && sha256sum -c "${NAME}.tar.gz.sha256" >/dev/null ) \
427 || die "checksum mismatch — the download is corrupt or tampered with"
428fi
429
430tar -xzf "${TMP}/${NAME}.tar.gz" -C "$TMP"
431[ -x "${TMP}/${NAME}/steid" ] || die "tarball has no steid binary at ${NAME}/steid"
432# The bundle must ship and must land beside the binary: AssetBundle::load() walks
433# up from the executable looking for assets/manifest.toml and the process exits
434# at startup without it.
435[ -f "${TMP}/${NAME}/assets/manifest.toml" ] || die "tarball has no assets/manifest.toml"
436
437# --- user and directories ---------------------------------------------------
438
439if ! id "$STEID_USER" >/dev/null 2>&1; then
440 say "creating system user ${STEID_USER}"
441 # --home is the state directory: git wants a HOME, and giving it the one
442 # directory the service can write keeps that from being a surprise later.
443 useradd --system --home-dir "$STATE_DIR" --shell /usr/sbin/nologin "$STEID_USER"
444fi
445
446mkdir -p "$INSTALL_DIR" "$STATE_DIR" "$CONF_DIR"
447# State is exactly two things: the SQLite database file and the repository
448# directory. Both live here, and together they are the entire backup surface.
449mkdir -p "${STATE_DIR}/repos"
450chown -R "${STEID_USER}:${STEID_USER}" "$STATE_DIR"
451chmod 750 "$STATE_DIR"
452
453# --- install files ----------------------------------------------------------
454
455# Stop before replacing the binary: overwriting a running executable in place
456# fails with ETXTBSY, and a half-swapped install/assets pair would serve stale
457# hashed CSS until the next restart anyway.
458if systemctl is-active --quiet steid 2>/dev/null; then
459 say "stopping steid for the upgrade"
460 systemctl stop steid
461fi
462
463say "installing to ${INSTALL_DIR}"
464install -m 0755 "${TMP}/${NAME}/steid" "${INSTALL_DIR}/steid"
465rm -rf "${INSTALL_DIR}/assets"
466cp -R "${TMP}/${NAME}/assets" "${INSTALL_DIR}/assets"
467if [ -f "${TMP}/${NAME}/README.md" ]; then
468 cp "${TMP}/${NAME}/README.md" "${INSTALL_DIR}/README.md"
469fi
470chown -R root:root "$INSTALL_DIR"
471# Read-only to the service user on purpose: Steid never writes here.
472chmod -R a+rX "$INSTALL_DIR"
473
474# --- configuration ----------------------------------------------------------
475
476# Written once and then left alone, so an upgrade cannot silently revert a
477# setting someone deliberately changed.
478# Whether this run wrote the env file, which is also whether the owner flags did
479# anything: they are only ever written on the first write, like every other
480# setting here.
481ENV_WRITTEN=0
482if [ ! -f "${CONF_DIR}/steid.env" ]; then
483 ENV_WRITTEN=1
484 say "writing ${CONF_DIR}/steid.env"
485 cat > "${CONF_DIR}/steid.env" <<EOF
486# Steid configuration. Restart after editing: systemctl restart steid
487
488# All state lives under ${STATE_DIR}. SQLite writes -wal and -shm siblings, so
489# the directory must be writable, not just the file.
490STEID_DATABASE_URL=sqlite:${STATE_DIR}/steid.db?mode=rwc
491STEID_DATA_DIR=${STATE_DIR}/repos
492
493# HOST and PORT are read by the web framework itself and are deliberately not
494# STEID_-prefixed. Loopback only: Caddy is the way in, and binding 0.0.0.0 would
495# expose plain HTTP — and therefore access tokens in cleartext — to the internet.
496HOST=127.0.0.1
497PORT=${PORT}
498
499# Caddy sits in front and appends the address it accepted the connection from to
500# X-Forwarded-For, so the rate limiters may trust that header to tell one caller
501# from another. Turn this OFF if you ever put Steid on a public port directly:
502# with nothing appending the header a caller can invent one per request and buy
503# itself a fresh rate-limit budget each time.
504STEID_TRUSTED_PROXY=true
505
506# The address this instance answers on, used by \`steid reset-password\` to print a
507# whole link. Every link built while serving is derived from the request instead,
508# so this is read by the command line and nothing else.
509STEID_PUBLIC_URL=https://${DOMAIN}
510
511# Outgoing mail, for password reset. Both are needed or neither does anything:
512# without them the forgot-password page says so and points at
513# \`steid reset-password <handle>\`, which prints a one-time link on this machine.
514# The URL carries the submission password, which is why this file is mode 640. Quote
515# any value containing spaces or angle brackets.
516# STEID_SMTP_URL=smtps://user:password@smtp.example.com:465
517# STEID_MAIL_FROM="Steid <steid@${DOMAIN}>"
518
519# Deliberately absent: STEID_INSECURE_COOKIES. It strips Secure from the session
520# cookie and exists only for plain-HTTP local development. Setting it here would
521# hand out a session cookie that any network hop can read.
522EOF
523
524 # Only when asked for, and only here — inside the "first write" branch, like
525 # everything else in this file. An upgrade must not re-seed anything, and in
526 # any case Steid ignores these the moment an owner exists. Each value goes
527 # through env_quote: an address may hold a `'`, and a name spaces and quotes.
528 if [ -n "$OWNER_EMAIL" ]; then
529 cat >> "${CONF_DIR}/steid.env" <<EOF
530
531# The owner, created on the first boot that finds this instance unclaimed. Read
532# together — Steid refuses to start with one of them set and not the other — and
533# inert from the moment an owner exists, so they can stay here for the life of
534# the instance. This is what makes an unattended install come up already claimed
535# rather than serving a setup page to whoever finds it first.
536#
537# The owner created this way has NO usable password. The way in is
538# ${INSTALL_DIR}/steid reset-password ${OWNER_HANDLE}
539# run on this machine, which prints a one-time link.
540STEID_OWNER_EMAIL=$(env_quote "$OWNER_EMAIL")
541STEID_OWNER_HANDLE=$(env_quote "$OWNER_HANDLE")
542EOF
543 # Beside the owner, in the same first-write branch and inert for the same
544 # reason: once an owner exists Steid reads none of these again.
545 if [ -n "$OWNER_ORG" ]; then
546 cat >> "${CONF_DIR}/steid.env" <<EOF
547# The organisation this instance is for, created at the same first boot and set
548# as the home page — so the root lands on it rather than on the owner's own
549# page. Inert once an owner exists, like the two above.
550STEID_OWNER_ORG=$(env_quote "$OWNER_ORG")
551EOF
552 if [ -n "$OWNER_ORG_NAME" ]; then
553 cat >> "${CONF_DIR}/steid.env" <<EOF
554STEID_OWNER_ORG_NAME=$(env_quote "$OWNER_ORG_NAME")
555EOF
556 fi
557 fi
558 fi
559 chmod 640 "${CONF_DIR}/steid.env"
560 chown "root:${STEID_USER}" "${CONF_DIR}/steid.env"
561else
562 say "keeping existing ${CONF_DIR}/steid.env"
563 if [ -n "$OWNER_EMAIL" ]; then
564 say "--owner-email/--owner-handle/--owner-org ignored: ${CONF_DIR}/steid.env already exists"
565 fi
566fi
567
568# After the branch, so it applies to a first install and to a later run alike — and
569# before the unit is written and Steid is restarted, which is the whole point: the
570# instance must never serve with the operator surface off waiting for something to
571# come along afterwards and set this. The key is named; the value is not.
572if [ -n "$OPERATOR_TOKEN" ]; then
573 say "setting STEID_OPERATOR_TOKEN in ${CONF_DIR}/steid.env"
574 set_env_secret STEID_OPERATOR_TOKEN "$OPERATOR_TOKEN"
575fi
576
577say "writing /etc/systemd/system/steid.service"
578cat > /etc/systemd/system/steid.service <<EOF
579# Managed by install.sh. Re-running the installer rewrites this file.
580[Unit]
581Description=Steid
582After=network-online.target
583Wants=network-online.target
584
585[Service]
586Type=simple
587User=${STEID_USER}
588Group=${STEID_USER}
589WorkingDirectory=${INSTALL_DIR}
590ExecStart=${INSTALL_DIR}/steid
591EnvironmentFile=${CONF_DIR}/steid.env
592Environment=HOME=${STATE_DIR}
593Restart=on-failure
594RestartSec=2s
595
596NoNewPrivileges=true
597PrivateTmp=true
598PrivateDevices=true
599ProtectSystem=strict
600ProtectHome=true
601ProtectKernelTunables=true
602ProtectKernelModules=true
603ProtectControlGroups=true
604RestrictSUIDSGID=true
605RestrictNamespaces=true
606LockPersonality=true
607RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
608ReadWritePaths=${STATE_DIR}
609
610[Install]
611WantedBy=multi-user.target
612EOF
613
614systemctl daemon-reload
615systemctl enable --quiet steid
616say "starting steid"
617systemctl restart steid
618
619# --- scheduled backups ------------------------------------------------------
620
621if [ "$BACKUPS" = "daily" ]; then
622 say "installing the nightly backup timer"
623
624 mkdir -p "$BACKUP_DIR"
625 chown "${STEID_USER}:${STEID_USER}" "$BACKUP_DIR"
626 # 700: an archive here is every row and every private repository in one file.
627 chmod 700 "$BACKUP_DIR"
628
629 # The env file is never rewritten, so the marker is appended rather than
630 # written with the rest — and only once, so re-running is idempotent.
631 if ! grep -q '^STEID_BACKUP_MARKER=' "${CONF_DIR}/steid.env"; then
632 cat >> "${CONF_DIR}/steid.env" <<EOF
633
634# Added by install.sh --backups daily. Steid reads this file's modification
635# time to show the last automatic backup on the settings page, and nothing else
636# about it. Removing the line makes the page say "none configured".
637STEID_BACKUP_MARKER=${BACKUP_MARKER}
638EOF
639 fi
640
641 cat > /etc/systemd/system/steid-backup.service <<EOF
642# Managed by install.sh --backups daily.
643[Unit]
644Description=Steid backup
645# The backup is taken through SQLite's own VACUUM INTO, so it is consistent with
646# the service running — this deliberately does not stop Steid.
647After=steid.service
648
649[Service]
650Type=oneshot
651User=${STEID_USER}
652Group=${STEID_USER}
653WorkingDirectory=${INSTALL_DIR}
654EnvironmentFile=${CONF_DIR}/steid.env
655Environment=HOME=${STATE_DIR}
656ExecStart=${INSTALL_DIR}/steid backup ${BACKUP_DIR}
657# Pruning and the marker run only if the backup succeeded, which is the point of
658# ExecStartPost: a failed run must not look like a successful one on the page.
659# The \`;\` before touch is deliberate — an empty glob must not fail the unit.
660ExecStartPost=/bin/sh -c 'cd ${BACKUP_DIR} && ls -1t steid-*.tar.gz 2>/dev/null | tail -n +$((BACKUP_KEEP + 1)) | xargs -r rm -f; touch ${BACKUP_MARKER}'
661
662NoNewPrivileges=true
663PrivateTmp=true
664PrivateDevices=true
665ProtectSystem=strict
666ProtectHome=true
667ProtectKernelTunables=true
668ProtectKernelModules=true
669ProtectControlGroups=true
670RestrictSUIDSGID=true
671RestrictNamespaces=true
672LockPersonality=true
673RestrictAddressFamilies=AF_UNIX
674ReadWritePaths=${STATE_DIR}
675EOF
676
677 cat > /etc/systemd/system/steid-backup.timer <<'EOF'
678# Managed by install.sh --backups daily.
679[Unit]
680Description=Nightly Steid backup
681
682[Timer]
683OnCalendar=daily
684# Spread across the hour so a fleet of instances does not all gzip themselves at
685# once, and catch up after a reboot rather than skipping the night.
686RandomizedDelaySec=1h
687Persistent=true
688
689[Install]
690WantedBy=timers.target
691EOF
692
693 systemctl daemon-reload
694 systemctl enable --quiet --now steid-backup.timer
695elif [ "$BACKUPS" = "off" ]; then
696 if [ -f /etc/systemd/system/steid-backup.timer ]; then
697 say "removing the backup timer (archives in ${BACKUP_DIR} are left alone)"
698 systemctl disable --quiet --now steid-backup.timer 2>/dev/null || true
699 rm -f /etc/systemd/system/steid-backup.timer /etc/systemd/system/steid-backup.service
700 systemctl daemon-reload
701 fi
702fi
703
704# --- caddy ------------------------------------------------------------------
705
706if [ "$INSTALL_CADDY" = 1 ]; then
707 # Whether Caddy was here *before* this run decides whether /etc/caddy/Caddyfile
708 # is somebody's configuration or the one the .deb ships. It has to be sampled
709 # here, because thirty lines later the package has been installed either way.
710 CADDY_WAS_INSTALLED=1
711 if ! command -v caddy >/dev/null 2>&1; then
712 CADDY_WAS_INSTALLED=0
713 say "installing Caddy from its official apt repository"
714 apt-get install -y -qq --no-install-recommends debian-keyring debian-archive-keyring apt-transport-https gnupg
715 curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
716 | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
717 curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
718 > /etc/apt/sources.list.d/caddy-stable.list
719 apt-get update -qq
720 apt-get install -y -qq caddy
721 else
722 say "Caddy already installed"
723 fi
724
725 # NOT rewritten on upgrade. This used to be overwritten every run, which
726 # silently discarded operator edits — a www redirect added by hand vanished on
727 # the next install and took the site's www hostname with it, with nothing in the
728 # output to say so. The env file was already treated this way; the two now agree.
729 #
730 # CADDY_WAS_INSTALLED is the whole point of the second condition. The Caddy
731 # package ships its own /etc/caddy/Caddyfile — a placeholder site on :80 — so
732 # on a first install the file always exists by the time we look, and "keep
733 # what is there" quietly meant "keep the placeholder". The stranger's install
734 # then succeeded, Steid ran, and the domain served Caddy's welcome page with
735 # nothing anywhere saying why. Found in a container running the published
736 # one-liner, which is the only way it shows up: an upgrade never hits it.
737 if [ -f /etc/caddy/Caddyfile ] && [ "$FORCE_CADDYFILE" = 0 ] && [ "$CADDY_WAS_INSTALLED" = 1 ]; then
738 say "keeping existing /etc/caddy/Caddyfile (--force-caddyfile to replace)"
739 # And say so when that file cannot possibly be serving Steid, rather than
740 # leaving the operator to find out from a browser.
741 if ! grep -q "127.0.0.1:${PORT}" /etc/caddy/Caddyfile; then
742 echo "install.sh: WARNING — /etc/caddy/Caddyfile does not proxy 127.0.0.1:${PORT}," >&2
743 echo " so ${DOMAIN} will not reach Steid. Add a reverse_proxy to it (see" >&2
744 echo " deploy/Caddyfile in the source tree), or re-run with --force-caddyfile" >&2
745 echo " to have this installer write a fresh one." >&2
746 fi
747 else
748 say "writing /etc/caddy/Caddyfile for ${DOMAIN}"
749 mkdir -p /etc/caddy
750
751 WWW_BLOCK=""
752 if [ "$WWW" = 1 ]; then
753 WWW_BLOCK="
754# www redirects to the bare hostname so there is one canonical URL.
755www.${DOMAIN} {
756 redir https://${DOMAIN}{uri} permanent
757}"
758 fi
759
760 cat > /etc/caddy/Caddyfile <<EOF
761# Written by install.sh on first install only. Later runs leave it alone, so edits
762# here survive an upgrade. Use --force-caddyfile to have the installer replace it.
763#
764# Steid has no TLS of its own (Topcoat 0.5 ships none), and it authenticates git
765# over HTTP Basic — so without this proxy every push would send a personal access
766# token in cleartext. Caddy obtains and renews the certificate automatically,
767# provided ${DOMAIN} resolves here and ports 80 and 443 are open.
768${DOMAIN} {
769 reverse_proxy 127.0.0.1:${PORT} {
770 # Git's smart HTTP is a streaming protocol in both directions; buffering
771 # it turns a clone into a long silence and can stall negotiation.
772 flush_interval -1
773 }
774}
775${WWW_BLOCK}
776EOF
777 fi
778
779 systemctl enable --quiet caddy
780 systemctl reload caddy 2>/dev/null || systemctl restart caddy
781fi
782
783# --- report -----------------------------------------------------------------
784
785# A moment for the service to either come up or fall over, so the message below
786# reflects reality rather than optimism.
787sleep 2
788if ! systemctl is-active --quiet steid; then
789 echo >&2
790 echo "install.sh: steid is installed but not running. Look at:" >&2
791 echo " journalctl -u steid -n 50 --no-pager" >&2
792 exit 1
793fi
794
795if [ "$INSTALL_CADDY" = 1 ]; then
796 BASE_URL="https://${DOMAIN}"
797else
798 BASE_URL="http://127.0.0.1:${PORT} (put your own TLS proxy in front of this)"
799fi
800
801# Said only when a timer was installed, and said with the offsite caveat
802# attached: a nightly archive that never leaves the machine survives a mistake
803# and does not survive the machine.
804if [ -f /etc/systemd/system/steid-backup.timer ]; then
805 BACKUP_REPORT=" Backups nightly into ${BACKUP_DIR}, keeping ${BACKUP_KEEP}
806 systemctl list-timers steid-backup.timer
807 Take one now: ${INSTALL_DIR}/steid backup ${BACKUP_DIR}
808
809 !! These sit on this machine's disk. Copy them somewhere else — any
810 !! rclone remote will do, as a second timer or from your laptop:
811 !! rclone sync ${BACKUP_DIR} remote:steid-backups
812"
813else
814 BACKUP_REPORT=" Backups none scheduled. Re-run with --backups daily, or take one by
815 hand: ${INSTALL_DIR}/steid backup /var/backups
816"
817fi
818
819# Two different next steps, because a seeded instance has no token and no setup
820# page: it is already owned, and what its owner needs is a way in rather than a
821# way to claim.
822if [ -n "$OWNER_EMAIL" ] && [ "$ENV_WRITTEN" = 1 ]; then
823 CLAIM_REPORT="This instance is already claimed: ${OWNER_HANDLE} <${OWNER_EMAIL}> was created
824at first boot, so there was never a moment when a stranger could claim it.${OWNER_ORG:+
825It is owned by the organisation ${OWNER_ORG}, which the root lands on.}
826
827 That owner has no password. Mint a one-time sign-in link on this machine:
828
829 ${INSTALL_DIR}/steid reset-password ${OWNER_HANDLE}
830
831 It works once and expires in 30 minutes, and it is as good as the password —
832 hand it over the way you would one.
833"
834else
835 CLAIM_REPORT="Next: claim the instance.
836
837 The setup token is printed to the log at startup, and ONLY while the instance
838 is unclaimed. It is held in memory, so every restart mints a new one:
839
840 journalctl -u steid --no-pager | tail -n 30
841
842 Then open ${BASE_URL}/auth/setup and paste it in.
843"
844fi
845
846cat <<EOF
847
848Steid ${VERSION} is running.
849
850 Service systemctl status steid
851 Logs journalctl -u steid -f
852 Config ${CONF_DIR}/steid.env
853 State ${STATE_DIR} (the database and the repos — back up this directory)
854${BACKUP_REPORT}
855${CLAIM_REPORT}
856To upgrade later, re-run this script with a newer --version. It replaces the
857binary and assets and leaves ${STATE_DIR} untouched.
858EOF