diff --git a/compose.yml b/compose.yml index 5e5c4a17..3938f188 100644 --- a/compose.yml +++ b/compose.yml @@ -13,6 +13,8 @@ # Site modes are selected through COMPOSE_PROFILES and are additive: # local ghost + db, Ghost published on 127.0.0.1:${GHOST_PORT} # production ghost + db + caddy (HTTPS ingress) +# no-caddy ghost + db, a production site behind the operator's own proxy +# (nginx, Apache) on 127.0.0.1:${GHOST_PORT} # Optional, per-site profiles: analytics, activitypub, and for local sites # mailpit, and `supervisor`, which runs Ghost updates asked for in Ghost Admin # (docs/upgrade-supervisor.md). @@ -33,13 +35,13 @@ services: # Do not alter this without updating the Tinybird Sync container as well image: ${GHOST_IMAGE_REF:-${GHOST_IMAGE:-ghost}:${GHOST_VERSION:-6-next-alpine}} restart: ${RESTART_POLICY:-unless-stopped} - profiles: [local, production] + profiles: [local, production, no-caddy] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running logging: *default-logging - # Loopback only: production ingress is Caddy, and a bring-your-own proxy - # connects over the host loopback interface. + # Loopback only: production ingress is Caddy, or with the `no-caddy` + # profile, the operator's own proxy, over the host loopback interface. ports: - "127.0.0.1:${GHOST_PORT:-2368}:2368" # Application configuration only. Never `.env`. @@ -112,7 +114,7 @@ services: db: image: mysql:8.0.44@sha256:f37951fc3753a6a22d6c7bf6978c5e5fefcf6f31814d98c582524f98eae52b21 restart: ${RESTART_POLICY:-unless-stopped} - profiles: [local, production] + profiles: [local, production, no-caddy] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running diff --git a/docs/configuration.md b/docs/configuration.md index 895db8b3..a50631b5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -106,13 +106,17 @@ value in either file may be a credential. ## Site modes and profiles -Site mode is selected through `COMPOSE_PROFILES`, and exactly one of `local` -or `production` must be present: +Site mode is selected through `COMPOSE_PROFILES`, and exactly one of `local`, +`production` or `no-caddy` must be present: -| Profile | Services | Ingress | -| --- | --- | --- | -| `local` | `ghost`, `db` | Ghost on `127.0.0.1:${GHOST_PORT}` | -| `production` | `ghost`, `db`, `caddy` | Caddy on `${HTTP_PORT}` / `${HTTPS_PORT}` | +| Profile | Services | Ingress | `SITE_MODE` | +| --- | --- | --- | --- | +| `local` | `ghost`, `db` | Ghost on `127.0.0.1:${GHOST_PORT}` | `local` | +| `production` | `ghost`, `db`, `caddy` | Caddy on `${HTTP_PORT}` / `${HTTPS_PORT}` | `production` | +| `no-caddy` | `ghost`, `db` | [Your own proxy](#your-own-proxy), to Ghost on `127.0.0.1:${GHOST_PORT}` | `production` | + +A `no-caddy` site is a production site in every other way: backup, restore, +update, `self-update` and the upgrade supervisor treat it as one. Optional per-site profiles are added to the same list and are purely additive. Adding one never changes the site mode: @@ -130,10 +134,11 @@ supervisor` writes and `self-update` keeps on the release it installs. Every site's Ghost mounts the `upgrade` volume read-only, where the supervisor's socket is; it stays empty without the supervisor. -`mailpit` is for local sites only: validation rejects it beside `production`, -where it would catch the site's real mail. `analytics` and `activitypub` are -for production sites only: validation rejects them beside `local`, because -only Caddy's routes reach their services, and a local site has no Caddy. Selecting the profile only runs +`mailpit` is for local sites only: validation rejects it beside `production` +or `no-caddy`, where it would catch the site's real mail. `analytics` and +`activitypub` need Caddy's routes: validation rejects them beside `local`, +which has no Caddy, and beside `no-caddy`, whose proxy the manager does not +configure. Selecting the profile only runs Mailpit; Ghost sends to it because `ghost.env` says so (`install --with mailpit` writes those settings; see [install.md](install.md#optional-services)). @@ -145,17 +150,91 @@ ActivityPub and analytics are **per-site**: each site owns its ActivityPub database, storage and serving URL, and its own Tinybird credentials, workspace selection and schema deployment. -Ghost is always published on the loopback interface only, in both modes, so it -is never exposed publicly except through Caddy. - -Caddy is part of `production` rather than an optional profile, deliberately: a -supported bring-your-own-proxy path would mean validating the operator's -forwarded-header configuration, and getting `X-Forwarded-Proto` wrong yields -incorrect absolute URLs and non-secure cookies — a site that half works. If you -already run nginx or Apache, you can still point it at -`127.0.0.1:${GHOST_PORT}` and edit `compose.yml` to drop the caddy service or -move it off 80/443, but that is an unsupported manual customization and stack -updates may touch `compose.yml`. +Ghost is always published on the loopback interface only, in every mode, so +it is never exposed publicly except through Caddy or your own proxy. + +### Your own proxy + +If the host already runs nginx or Apache, `install --domain example.com +--no-caddy` installs a production site without Caddy, as Ghost-CLI's +`ghost install --no-setup-nginx --no-setup-ssl` did. `COMPOSE_PROFILES` is +`no-caddy`; no `caddy/` is written, and ports 80 and 443 stay your proxy's. +Your proxy terminates HTTPS, with a certificate it obtains, and passes +requests to Ghost on `127.0.0.1:${GHOST_PORT}` (`./ghost-docker info` shows +the port). + +The manager does not configure your proxy, and cannot check it: it runs in a +container, which cannot reach the host's loopback port or ask the host's +proxy. Installation and `check` verify Ghost's own health check, and report +the ingress as yours. Opening the site's URL is the check. + +The proxy must send three headers: + +| Header | Value | Why | +| --- | --- | --- | +| `Host` | the requested host | Ghost serves the site, and Ghost Admin on an admin domain, by name | +| `X-Forwarded-For` | the client's address | Ghost's logs, rate limits and member sign-in see the visitor, not `127.0.0.1` | +| `X-Forwarded-Proto` | `https` | Ghost's `URL` is `https://`, and Ghost redirects a request it believes is plain HTTP to HTTPS | + +**A missing or wrong `X-Forwarded-Proto` breaks the site.** Ghost takes +every request for plain HTTP and redirects it to HTTPS, which the proxy +passes back as plain HTTP again: a redirect loop. Where a request does get +through, Ghost treats the connection as insecure, which breaks its secure +session and member cookies: sign-in to Ghost Admin and member sign-in fail. + +For nginx, in place of Ghost-CLI's server block (with a certificate from +certbot or any other ACME client): + +```nginx +server { + listen 80; + listen [::]:80; + server_name example.com; + return 301 https://$host$request_uri; +} + +server { + listen 443 ssl http2; + listen [::]:443 ssl http2; + server_name example.com; + + ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; + + # Ghost accepts image, media and theme uploads larger than nginx's 1 MB default. + client_max_body_size 50m; + + location / { + proxy_pass http://127.0.0.1:2368; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Real-IP $remote_addr; + } +} +``` + +Replace `2368` with the site's `GHOST_PORT`. With `--admin-domain`, add the +same `server` blocks for the admin domain. For Apache, with `mod_proxy`, +`mod_proxy_http` and `mod_headers`, inside the HTTPS `VirtualHost`: + +```apache +ProxyPreserveHost On +RequestHeader set X-Forwarded-Proto "https" +ProxyPass / http://127.0.0.1:2368/ +ProxyPassReverse / http://127.0.0.1:2368/ +``` + +`mod_proxy` adds `X-Forwarded-For` itself. + +ActivityPub and analytics are refused on a `no-caddy` site: they are served by +routes Caddy writes (`/.ghost/activitypub/`, `/.well-known/`, +`/.ghost/analytics/`), which your proxy would have to reproduce. To use them, +install with Caddy instead. + +On Linux, use Docker Engine 28 or later: older engines let other machines on +the local network reach ports published on `127.0.0.1`, and so reach Ghost +around your proxy ([Ports](install.md#ports-and-your-existing-proxy)). ## Lifecycle diff --git a/docs/install.md b/docs/install.md index c4c304fa..4385dfc0 100644 --- a/docs/install.md +++ b/docs/install.md @@ -51,11 +51,11 @@ clone](#updating-a-clone)) rather than `self-update`. ```text ghost-docker install [--local | --domain example.com [--admin-domain admin.example.com] - [--email ops@example.com]] + [--email ops@example.com | --no-caddy]] [--name NAME] [--port 2368] [--version 6.61.0] [--with activitypub,mailpit,supervisor] [--channel stable|beta | --release vX.Y.Z] [--no-prompt] [--no-start] ghost-docker install --import BUNDLE [--name NAME] [--port 2368] [--with mailpit] [--no-prompt] [--no-start] -ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [--email EMAIL] [--no-start] +ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [--email EMAIL | --no-caddy] [--no-start] ``` | Option | Meaning | @@ -64,6 +64,7 @@ ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [ | `--domain DOMAIN` | A production site: Ghost, MySQL and Caddy with HTTPS on `DOMAIN`. Asked for at a terminal when omitted. | | `--admin-domain DOMAIN` | A separate Ghost Admin domain. Production only. | | `--email EMAIL` | The email Caddy registers with Let's Encrypt, which sends expiry notices to it. Production only; optional. | +| `--no-caddy` | A production site behind your own nginx or Apache: no Caddy, and 80 and 443 left to your proxy. See [Your own proxy](#your-own-proxy). | | `--name NAME` | The site's `COMPOSE_PROJECT_NAME`: lowercase letters, digits and dashes, at most 45 characters. Default: `ghost-example-com` in production, a generated `ghost-local-...` name locally. | | `--port PORT` | The loopback port Ghost is published on. Default: the first free port at or above 2368. | | `--version VERSION` | A Ghost version (`6.61.0`) or a full `next` image tag (`6-next-alpine`), pinned to its exact digest. | @@ -77,8 +78,10 @@ ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [ `install` refuses a directory that already holds a site or data, checks the host first (as `./ghost-docker doctor` does), generates fresh database -passwords, then starts the site and verifies it through its own ingress. **A -failed installation removes everything it created**, so the same command can +passwords, then starts the site and verifies it: through Caddy, or with +`--no-caddy`, by Ghost's own health check only, since your proxy cannot be +reached from the manager's container. **A failed installation removes +everything it created**, so the same command can simply be run again. Details: [What installation does](reference.md#what-installation-does). Exit statuses: `0` installed, `1` failed, `2` a usage error. @@ -87,12 +90,12 @@ Exit statuses: `0` installed, `1` failed, `2` a usage error. | Service | For | What it does | | --- | --- | --- | -| `--with activitypub` | Production | Runs the site's own ActivityPub service and database, routed through Caddy. | +| `--with activitypub` | Production, with Caddy | Runs the site's own ActivityPub service and database, routed through Caddy. | | `--with mailpit` | Local | Sends Ghost's mail (invites, password resets, sign-in links) to a [Mailpit](https://mailpit.axllent.org) inbox at `http://127.0.0.1:MAILPIT_PORT` (`./ghost-docker info` shows it). Newsletters go through Mailgun's API, so Mailpit never sees them. | | `--with supervisor` | Either | Lets Ghost Admin run Ghost updates within the site's major version, each with a checked backup first. Needs Ghost 6.72.0 or later; refused under rootless Docker. See [upgrade-supervisor.md](upgrade-supervisor.md). | -ActivityPub and analytics need Caddy's routes, so a local site cannot select -them; Mailpit would catch a production site's real mail, so a production site +ActivityPub and analytics need Caddy's routes, so a local site, or one +installed `--no-caddy`, cannot select them; Mailpit would catch a production site's real mail, so a production site cannot select it. **Analytics** is added after installation, because its Tinybird login is @@ -167,7 +170,8 @@ A production site's bundle is installed as a production site, as sign-in code to confirm the new device, so mail has to work. - **Nothing is stopped.** If nginx or Apache still holds ports 80 and 443, Caddy cannot start and the import fails, naming the port. Stopping it is - part of the move below. + part of the move below, unless you [keep nginx](#keeping-nginx) and import + with `--no-caddy`. ### Moving a site to Docker @@ -221,7 +225,7 @@ curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --import ~/m ``` - **Stop nginx yourself.** If it serves other sites too, move those first, or - keep the source (see [Ports](#ports-and-your-existing-proxy)). + [keep nginx](#keeping-nginx). - DNS already points here; Caddy gets its own certificate when it starts. - **If the import fails:** `sudo systemctl start nginx`, then `ghost start` in the source. The bundle is unchanged, so you can retry. @@ -229,6 +233,30 @@ curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --import ~/m nginx`, and disable the source's `ghost_...` service (`systemctl list-unit-files 'ghost_*'` names it). +#### Keeping nginx + +To keep Ghost-CLI's nginx, and its certificate, serving the site, import +without Caddy. nginx keeps ports 80 and 443, and only the source stops: + +```bash +cd /var/www/ghost +ghost stop +ghost migrate-export --output ~/my-site-bundle +mkdir ~/my-site && cd ~/my-site +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --import ~/my-site-bundle --no-caddy +``` + +- **Check nginx points at the new site.** Ghost-CLI's server block sends + requests to the source's port, usually 2368, which the stopped source no + longer holds, so the new site is usually given the same one. If the summary + names another, change `proxy_pass` to it, then `sudo nginx -t && sudo + systemctl reload nginx`; until then nginx answers with a 502 error. Ghost-CLI's + block already sends `X-Forwarded-Proto` ([Your own proxy](#your-own-proxy)). +- **If the import fails:** `ghost start` in the source. nginx was never changed. +- **Afterwards**, disable the source's `ghost_...` service at boot + (`systemctl list-unit-files 'ghost_*'` names it). Leave nginx enabled: it + serves the site now. + #### To another host ```bash @@ -281,19 +309,33 @@ directory, with `sudo` because MySQL owns `data/mysql`. For the real move, expor - A port `install` chooses skips ports other containers publish, and on macOS ports other programs hold too. A busy port you ask for with `--port` is an error. -- A production site needs 80 and 443. If anything holds them, installation - fails, names the port, and leaves the directory as it was. +- A production site needs 80 and 443 for Caddy. If anything holds them, + installation fails, names the port, and leaves the directory as it was. A + site installed `--no-caddy` does not use them. **On Linux, use Docker Engine 28 or later.** Ghost (and Mailpit) are published on `127.0.0.1` only, but older engines let other machines on the local network -reach those ports, and so Ghost around Caddy. `doctor` and `check` warn about +reach those ports, and so Ghost around Caddy or your own proxy. `doctor` and `check` warn about such an engine. Docker Desktop, OrbStack and rootless Docker are not affected. -To run Ghost behind your own nginx or Apache instead, point it at -`127.0.0.1:${GHOST_PORT}` and drop the `caddy` service from `compose.yml` or -move it off 80/443. That is an unsupported customization, and stack updates -may touch `compose.yml`; see -[configuration.md](configuration.md#site-modes-and-profiles). +### Your own proxy + +If nginx or Apache already serves this host, install without Caddy, as +Ghost-CLI's `ghost install --no-setup-nginx --no-setup-ssl` did: + +```bash +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --domain example.com --no-caddy +``` + +Ghost is published on `127.0.0.1:PORT`, which the summary names, and your +proxy serves the domain over HTTPS and passes requests there with `Host`, +`X-Forwarded-For` and **`X-Forwarded-Proto: https`**. Without that last +header Ghost redirects every request to HTTPS, in a loop, and treats the +connection as insecure, which breaks its secure cookies. The nginx server block, the Apache directives, and what is +refused (ActivityPub and analytics) are in +[configuration.md](configuration.md#your-own-proxy). The manager does not +configure or check your proxy; `check` verifies Ghost and reports the ingress +as yours. How ports are detected on each platform: [Ports](reference.md#ports). diff --git a/docs/reference.md b/docs/reference.md index d8d2ba7f..b7c613c5 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -15,7 +15,8 @@ happens underneath them. ownership, and that a sibling container sees the directory at the same path), and disk and memory, which warn rather than refuse. 3. **Ports Docker knows about.** The default port skips any that a container - publishes. An explicit `--port`, or 80 and 443 for a production site, that + publishes. An explicit `--port`, or 80 and 443 for a production site with + Caddy, that a container publishes is an error naming the container. Nothing is stopped. Ports held by anything else are found when the services start; see [Ports](#ports). @@ -38,13 +39,15 @@ happens underneath them. copy of the example, whose SMTP block is a placeholder. 7. **Routing**, in production: `caddy/sites/site.caddy`, written once with the site's domains, its network aliases and every snippet argument. It is - yours from then on; see [caddy.md](caddy.md). + yours from then on; see [caddy.md](caddy.md). With `--no-caddy`, nothing: + the routing is your proxy's ([configuration.md](configuration.md#your-own-proxy)). 8. **Metadata**: `.ghost-docker.json`, described in [architecture.md](architecture.md#installation-metadata). 9. **Start and verify**, unless `--no-start`: `docker compose up --wait`, so MySQL and Ghost must pass their own health checks, then the site is reached - through its own ingress (next section). A running container is not - readiness. + through Caddy (next section). With `--no-caddy` that last step is a note, + not a check: the manager cannot reach your proxy from its container. A + running container is not readiness. **A failed installation removes what it created** — containers, network, volumes, the data directories, `.env`, `ghost.env`, the metadata and the @@ -67,6 +70,7 @@ Each answer is reported for what it is: | caddy | Its health check: its admin API answers, with its configuration loaded. That says Caddy is up, not that it serves each name; **https** shows that once there is a certificate. | `ok` or `ERROR` | | https | An HTTPS request to Caddy's container for Ghost's `/ghost/api/admin/site/`, with the domain as its server name and Host, as a browser asks. **serving** means this site's Ghost answered through Caddy: Ghost reports its site's URL, and that must be the site's `URL` (by either name, the canonical one, not the admin domain). It names the certificate's issuer and expiry; a certificate from a CA browsers do not trust (staging, or Caddy's internal CA) is a `warning`. **pending** means Caddy has no certificate for the name yet, so Ghost could not be asked through it: Caddy obtains one once the domain's DNS reaches this host, `./ghost-docker check` reports the change, and `docker compose logs caddy` shows each attempt. Caddy answering with something other than Ghost (a broken route, a 502), another site's Ghost (a route to the wrong upstream), or an out-of-date certificate, is an `ERROR`. | `ok`, `warning`, `note` or `ERROR` | | admin https | With an admin domain of its own: the same, for that name. Ghost reached by the admin domain still reports the site's `URL`, which is what is checked. On the site's domain, Ghost answering the Admin API path with a redirect to the admin domain counts as Ghost answering; the admin domain's own answer then names the site. | `ok`, `warning`, `note` or `ERROR` | +| ingress | With `--no-caddy` (the `no-caddy` profile), in place of **caddy** and **https**: the site is served by your own proxy, which the manager cannot reach from its container, so it is not checked. The note names the URL and the loopback port the proxy must pass it to with `X-Forwarded-Proto: https`. | `note` | | mailpit | With `--with mailpit`: its health check. The check names `mailpit-${COMPOSE_PROJECT_NAME}:1025`, where Ghost sends mail. | `ok` or `ERROR` | | published ports | The ports Docker says it published. A container cannot reach the host's own loopback interface, so they are not checked from there (the **https** request goes to Caddy's container, not to the host's ports): opening the URL is that check. | `note` | @@ -94,7 +98,8 @@ offered; for a private name, put `tls internal` in a `caddy/custom/` file. records its port, and a new site may be given the same one. - A port you *asked for* does not: `--port` on a busy port is an error, because a site at an address nothing else expects is worse than a refusal. -- A production site needs 80 and 443. If a container holds them, installation +- A production site needs 80 and 443 for Caddy; one installed `--no-caddy` + does not. If a container holds them, installation stops before writing anything and names it. If another program holds them, Docker refuses to start Caddy; the error names the port, says nothing that was running was stopped, and the directory is as it was. @@ -204,8 +209,8 @@ so set those up again. Export without `--sqlite-format portable` to get a - `--import` with `--with`: import the site first, then enable optional services. A local site may take `--with mailpit`. -- `--domain`, `--admin-domain` or `--email` with a local site's bundle, and - `--local` with a production site's. +- `--domain`, `--admin-domain`, `--email` or `--no-caddy` with a local site's + bundle, and `--local` with a production site's. - A `portable` bundle of a production site. The exporter makes portable bundles of local SQLite sites only; a site that must move through Ghost Admin is installed new, then its content and members are imported there. diff --git a/manager/src/backup.ts b/manager/src/backup.ts index 1263cf1b..844840a5 100644 --- a/manager/src/backup.ts +++ b/manager/src/backup.ts @@ -174,7 +174,7 @@ export function siteOverrides(resolved: ResolvedSite): string[] { function notIncluded(site: SiteFacts): string[] { const profiles = site.settings.get('COMPOSE_PROFILES') ?? ''; const lines: string[] = []; - if (site.mode === 'production') { + if (site.layout === 'production') { lines.push( "Caddy's certificates and state, which Caddy obtains again when the site starts", ); diff --git a/manager/src/commands/doctor.ts b/manager/src/commands/doctor.ts index cc2e0e9e..5d69127a 100644 --- a/manager/src/commands/doctor.ts +++ b/manager/src/commands/doctor.ts @@ -160,7 +160,7 @@ function dockerEngine({ daemon, context }: Facts): Check | null { label, detail: `${version}: before ${LOOPBACK_ISOLATED}, machines on this host's local network can reach ports ` + - "published on 127.0.0.1, Ghost's among them, bypassing Caddy. Upgrade Docker Engine to " + + "published on 127.0.0.1, Ghost's among them, bypassing its proxy. Upgrade Docker Engine to " + `${LOOPBACK_ISOLATED} or later`, }; } diff --git a/manager/src/commands/install.ts b/manager/src/commands/install.ts index 42e16cfb..d0a15acd 100644 --- a/manager/src/commands/install.ts +++ b/manager/src/commands/install.ts @@ -1,4 +1,5 @@ // `install`: a local or production site, configured, started and verified. +// A production site has Caddy, or with --no-caddy, the operator's own proxy. // `run` takes the parts in order, each a function of its own: refusals that // need nothing; with --import, the bundle (import.ts); preflight, ports, the // exact Ghost image and a free project name, still changing nothing; then @@ -47,6 +48,8 @@ import { MAILPIT_DATA_DIR, META_FILE, profileConflict, + NO_CADDY_PROFILE, + type Layout, type SiteMode, } from '../site.ts'; import { takenPorts } from '../ports.ts'; @@ -128,6 +131,9 @@ const options = z adminDomain: hostname .optional() .describe('Serve Ghost Admin on a separate domain. Production only.'), + noCaddy: flag( + 'A production site behind your own proxy (nginx, Apache) on this host: Ghost on 127.0.0.1:PORT, no Caddy, and ports 80 and 443 left to your proxy. See docs/install.md#your-own-proxy.', + ), email: z .string() .regex(ACME_EMAIL, refused('must be an email address')) @@ -208,6 +214,12 @@ const options = z (flags.local && flags.domain !== undefined ? 'choose one site mode: --local, or --domain example.com, not both' : null) ?? + (flags.local && flags.noCaddy + ? '--no-caddy applies to production sites: a local site has no Caddy' + : null) ?? + (flags.noCaddy && flags.email !== undefined + ? "--email is Caddy's ACME account; with --no-caddy, your proxy obtains the certificate" + : null) ?? (flags.channel !== undefined && flags.release !== undefined ? 'choose --channel or --release, not both' : null) ?? @@ -232,6 +244,8 @@ type Flags = z.output; interface Plan { readonly mode: SiteMode; + /** Its mode, or for a production site behind the operator's proxy, `no-caddy`. */ + readonly layout: Layout; readonly domain: string; readonly adminDomain: string; readonly email: string; @@ -269,6 +283,7 @@ async function plan(flags: Flags, prompt: Prompter | null): Promise { } return checked({ mode, + layout: layoutFor(mode, flags), domain, adminDomain: flags.adminDomain ?? '', email: flags.email ?? '', @@ -277,13 +292,30 @@ async function plan(flags: Flags, prompt: Prompter | null): Promise { } /** An import's plan: the bundle says what kind of site it is, and options may name its domains. */ -const imported = (importing: Importing, flags: Flags): Plan => - checked({ ...importing.address(flags), email: flags.email ?? '', services: flags.with }); +function imported(importing: Importing, flags: Flags): Plan { + const address = importing.address(flags); + if (address.mode === 'local' && flags.noCaddy) { + throw new UsageError( + '--no-caddy applies to production sites, and this bundle is of a local site,\n' + + ' which is imported as one.', + ); + } + return checked({ + ...address, + layout: layoutFor(address.mode, flags), + email: flags.email ?? '', + services: flags.with, + }); +} + +/** A production site's ingress is Caddy unless --no-caddy says it is the operator's proxy. */ +const layoutFor = (mode: SiteMode, flags: Flags): Layout => + mode === 'production' && flags.noCaddy ? NO_CADDY_PROFILE : mode; /** What a site of its mode cannot be, however its domains were given. */ function checked(intent: Plan): Plan { for (const service of intent.services) { - const conflict = profileConflict(intent.mode, service); + const conflict = profileConflict(intent.layout, service); if (conflict !== null) { throw new UsageError(`--with ${service} ${conflict}`); } @@ -434,7 +466,7 @@ async function prepare( } const { port, mailpitPort } = await sitePorts( io, - intent.mode, + intent.layout, flags.port, intent.services.includes('mailpit'), ); @@ -460,7 +492,7 @@ async function prepare( const production = intent.mode === 'production'; return { ...target, - files: clone ? [] : payloadFiles(target.stack, intent.mode), + files: clone ? [] : payloadFiles(target.stack, intent.layout), flags, intent, port, @@ -468,7 +500,7 @@ async function prepare( ghost, pin, project, - profiles: [intent.mode, ...intent.services].join(','), + profiles: [intent.layout, ...intent.services].join(','), production, url: production ? `https://${intent.domain}` : `http://localhost:${port}`, release, @@ -489,7 +521,8 @@ async function preflight(io: Io, context: Context): Promise { /** * The ports Ghost, and with --with mailpit Mailpit's inbox, are published on. - * Any port the site needs that a running container publishes is refused, + * Any port the site needs, Caddy's 80 and 443 among them when it has Caddy, + * that a running container publishes is refused, * naming the container; one only a stopped site publishes is warned about. Where Docker would publish over a port a host process * holds (io.hostListens), Ghost's port must also be free on the host: a * chosen one skips it, a requested one is refused. Mailpit's is always @@ -497,7 +530,7 @@ async function preflight(io: Io, context: Context): Promise { */ async function sitePorts( io: Io, - mode: SiteMode, + layout: Layout, requested: number | undefined, mailpit: boolean, ): Promise<{ port: number; mailpitPort: number | null }> { @@ -509,7 +542,7 @@ async function sitePorts( : null; const wanted = [ port, - ...(mode === 'production' ? [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https] : []), + ...(layout === 'production' ? [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https] : []), ]; const holders = taken.holders(wanted); if (holders.size > 0) { @@ -595,7 +628,7 @@ function writeStack(site: Site, created: Created) { ok( io, 'stack files', - `compose.yml, ${site.production ? 'caddy/, mysql-init/, tinybird/' : 'mysql-init/'} from the manager image`, + `compose.yml, ${site.intent.layout === 'production' ? 'caddy/, mysql-init/, tinybird/' : 'mysql-init/'} from the manager image`, ); writeLauncher(dir, io.env, { image: pin!, channel: site.release.channel }, created); created.save(); @@ -689,8 +722,8 @@ async function validateConfiguration({ io, dir, intent }: Site) { } /** A production site's Caddy routes. Written once; from here on the file is the operator's. */ -function writeSiteRoutes({ io, dir, production, project, intent }: Site, created: Created) { - if (!production) { +function writeSiteRoutes({ io, dir, project, intent }: Site, created: Created) { + if (intent.layout !== 'production') { return; } const { domain, adminDomain, email, services } = intent; @@ -734,15 +767,18 @@ function writeSiteMetadata(site: Site, created: Created) { ok(io, META_FILE, 'installation metadata'); } -async function startAndVerify({ io, dir }: Site, created: Created) { +async function startAndVerify({ io, dir, intent }: Site, created: Created) { heading(io, 'Starting the services'); created.project = true; await upAndWait( io, dir, 'Pulling images, starting the services and waiting for them to be healthy', - ' If a port is already in use, choose another for Ghost with --port; a production\n' + - ' site needs 80 and 443 free for Caddy. Nothing that was already running was stopped.', + (intent.layout === 'production' + ? ' If a port is already in use, choose another for Ghost with --port; a production\n' + + ' site needs 80 and 443 free for Caddy.' + : ' If a port is already in use, choose another for Ghost with --port.') + + ' Nothing that was already running was stopped.', ); ok(io, 'services', 'healthy, by their own health checks'); @@ -800,24 +836,42 @@ async function undoInstall( function printSummary(site: Site, importing: Importing | null) { const { io, flags, intent, url, production, ghost } = site; const admin = intent.adminDomain ? `https://${intent.adminDomain}` : url; + // Started or not, the operator's proxy is theirs to set up. + const proxy = + intent.layout === NO_CADDY_PROFILE + ? [ + `Point your proxy at 127.0.0.1:${site.port} for ${[intent.domain, intent.adminDomain].filter(Boolean).join(' and ')},`, + 'over HTTPS, with X-Forwarded-Proto: https (docs/install.md#your-own-proxy).', + ] + : []; const next = flags.noStart ? [ 'Nothing is running. Start the site with: docker compose up -d', + ...proxy, ...(importing?.manifest.kind === 'portable' ? importing.nextSteps : []), ] - : production + : intent.layout === NO_CADDY_PROFILE ? [ - "Point the domain's DNS at this host; Caddy then obtains a certificate, and", - './ghost-docker check reports it.', + ...proxy, ...(importing === null ? [ 'Configure mail (see ghost.env), then open Ghost Admin and create the owner account.', ] : importing.nextSteps), ] - : importing !== null - ? importing.nextSteps - : ['Open Ghost Admin and create the owner account.']; + : production + ? [ + "Point the domain's DNS at this host; Caddy then obtains a certificate, and", + './ghost-docker check reports it.', + ...(importing === null + ? [ + 'Configure mail (see ghost.env), then open Ghost Admin and create the owner account.', + ] + : importing.nextSteps), + ] + : importing !== null + ? importing.nextSteps + : ['Open Ghost Admin and create the owner account.']; io.stdout( [ '', @@ -832,7 +886,7 @@ function printSummary(site: Site, importing: Importing | null) { ` Channel nightly: a build of Ghost's main branch, for testing, ${production ? 'which this production site should not run' : 'never for production'}`, ] : []), - ` Loopback 127.0.0.1:${site.port}`, + ` Loopback 127.0.0.1:${site.port}${intent.layout === NO_CADDY_PROFILE ? ', for your proxy' : ''}`, ...(site.mailpitPort === null ? [] : [` Mailpit http://127.0.0.1:${site.mailpitPort}, the mail Ghost sends`]), diff --git a/manager/src/commands/self-update.ts b/manager/src/commands/self-update.ts index 7bfb4836..a7717a4d 100644 --- a/manager/src/commands/self-update.ts +++ b/manager/src/commands/self-update.ts @@ -42,7 +42,7 @@ import { compareReleases, isRelease } from '../release.ts'; import { resolveSite } from '../resolved.ts'; import { heading, note, ok } from '../report.ts'; import * as env from '../env.ts'; -import { COMPOSE_FILE, ENV_FILE, META_FILE, type SiteFacts, type SiteMode } from '../site.ts'; +import { COMPOSE_FILE, ENV_FILE, META_FILE, type Layout, type SiteFacts } from '../site.ts'; import { reportNeedsOperator, reportRestored, @@ -131,12 +131,12 @@ const checksumOf = (path: string): string | null => function planPayload( dir: string, stack: string, - mode: SiteMode, + layout: Layout, recorded: Record, ): Payload { const changes: FileChange[] = []; const checksums: Record = {}; - const files = payloadFiles(stack, mode); + const files = payloadFiles(stack, layout); for (const file of files) { const wanted = sha256(readFileSync(join(stack, file))); const present = checksumOf(join(dir, file)); @@ -339,7 +339,7 @@ export const selfUpdateCommand = defineCommand({ } const stack = stackDir(io.env); - const payload = planPayload(dir, stack, metadata.mode, metadata.payload); + const payload = planPayload(dir, stack, site.layout, metadata.payload); const update: Update = { io, site, metadata, from, to, release, stack, payload }; if (flags.check) { diff --git a/manager/src/config.ts b/manager/src/config.ts index d54bc50c..81e2bfa4 100644 --- a/manager/src/config.ts +++ b/manager/src/config.ts @@ -16,9 +16,10 @@ import { ENV_FILE, GHOST_ENV_FILE, hostOf, + layoutOf, + MODE_PROFILE_NAMES, OPTIONAL_PROFILES, profileConflict, - SITE_MODES, siteMode, splitProfiles, unknownProfiles, @@ -92,7 +93,7 @@ export async function validateEnv(io: Io, dir: string): Promise { return [ error( file, - `COMPOSE_PROFILES is not set; it must name exactly one site mode (${SITE_MODES.join(', ')})`, + `COMPOSE_PROFILES is not set; it must name exactly one site mode (${MODE_PROFILE_NAMES.join(', ')})`, ), ]; } @@ -101,7 +102,7 @@ export async function validateEnv(io: Io, dir: string): Promise { findings.push( error( file, - `COMPOSE_PROFILES=${profiles} must name exactly one site mode (${SITE_MODES.join(', ')})`, + `COMPOSE_PROFILES=${profiles} must name exactly one site mode (${MODE_PROFILE_NAMES.join(', ')})`, ), ); } @@ -115,7 +116,7 @@ export async function validateEnv(io: Io, dir: string): Promise { ); } for (const profile of splitProfiles(profiles)) { - const conflict = mode === null ? null : profileConflict(mode, profile); + const conflict = mode === null ? null : profileConflict(layoutOf(profiles), profile); if (conflict !== null) { findings.push(error(file, `COMPOSE_PROFILES selects ${profile}, which ${conflict}`)); } @@ -142,8 +143,8 @@ export async function validateEnv(io: Io, dir: string): Promise { } } - // A production site is served by Caddy, over HTTPS, on the host its URL - // names; that host is the site's domain. + // A production site is served over HTTPS, by Caddy or the operator's own + // proxy, on the host its URL names; that host is the site's domain. if (mode === 'production') { for (const key of ['URL', 'ADMIN_URL']) { const url = values[key]; diff --git a/manager/src/payload.ts b/manager/src/payload.ts index a7854310..d6af9a1f 100644 --- a/manager/src/payload.ts +++ b/manager/src/payload.ts @@ -2,7 +2,7 @@ // manager image carries and `install` writes into an image-mode site, with a // checksum of each recorded in the metadata so `self-update` can tell an // untouched file from an edited one, and a launcher pinned to the image. A -// local site gets only the files its mode uses. A checkout's files are used +// directory gets only the files its layout uses. A checkout's files are used // in place (docs/architecture.md#installation-and-import). import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'; @@ -12,7 +12,7 @@ import { inspectImage, splitReference } from './docker/client.ts'; import { CliError } from './errors.ts'; import { atomicWrite, filesUnder } from './fs.ts'; import type { Io } from './io.ts'; -import type { SiteMode } from './site.ts'; +import type { Layout } from './site.ts'; export const stackDir = (env: NodeJS.ProcessEnv): string => env.GD_STACK_DIR ?? '/opt/ghost-docker/stack'; @@ -29,18 +29,24 @@ export const sha256 = (content: string | Buffer): string => export const isCheckout = (context: Context, dir: string): boolean => context.source === 'checkout' && existsSync(join(dir, 'manager', 'Dockerfile')); -/** Top-level payload directories only production sites use: Caddy, and analytics's Tinybird jobs. */ -const PRODUCTION_ONLY = ['caddy', 'tinybird']; +/** + * The top-level payload entries a directory of each layout does without: a + * site with no Caddy has no routes, and cannot select analytics, whose + * Tinybird jobs are built from tinybird/. + */ +const UNUSED: Record = { + local: ['caddy', 'tinybird'], + production: [], + 'no-caddy': ['caddy', 'tinybird'], +}; /** * Every file of the payload, relative to the stack directory, in a stable - * order; with a mode, only those a site of that mode uses. + * order; with a layout, only those a directory of that layout uses. */ -export function payloadFiles(stack: string, mode?: SiteMode): string[] { - const files = filesUnder(stack); - return mode === 'local' - ? files.filter((file) => !PRODUCTION_ONLY.includes(file.split('/')[0]!)) - : files; +export function payloadFiles(stack: string, layout?: Layout): string[] { + const unused = layout === undefined ? [] : UNUSED[layout]; + return filesUnder(stack).filter((file) => !unused.includes(file.split('/')[0]!)); } /** Paths, files and directories, the payload and launcher would write over. */ diff --git a/manager/src/site.ts b/manager/src/site.ts index c877ae90..fb3a6be5 100644 --- a/manager/src/site.ts +++ b/manager/src/site.ts @@ -51,6 +51,38 @@ export type ConfigFile = (typeof CONFIG_FILES)[number]; export const SITE_MODES = ['local', 'production'] as const; export type SiteMode = (typeof SITE_MODES)[number]; +/** + * A production site behind the operator's own proxy (nginx, Apache) on the + * host: Ghost and MySQL, no Caddy. Its mode is production. + */ +export const NO_CADDY_PROFILE = 'no-caddy'; + +/** The profiles that select a site's mode, and the mode each selects. */ +const MODE_PROFILES: Readonly> = { + local: 'local', + production: 'production', + [NO_CADDY_PROFILE]: 'production', +}; +export const MODE_PROFILE_NAMES = Object.keys(MODE_PROFILES); + +/** + * What a directory's files are for: a site of either mode, or a production + * site behind the operator's own proxy. The stack files each one needs differ + * (payload.ts), and only a production layout has Caddy. + */ +export type Layout = SiteMode | typeof NO_CADDY_PROFILE; + +/** The layout COMPOSE_PROFILES selects; a production one unless it says otherwise. */ +export function layoutOf(profiles: string): Layout { + const selected = splitProfiles(profiles); + for (const layout of [NO_CADDY_PROFILE, 'local'] as const) { + if (selected.includes(layout)) { + return layout; + } + } + return 'production'; +} + /** Additive, per-site. `supervisor` runs the upgrade supervisor (docs/upgrade-supervisor.md). */ export const OPTIONAL_PROFILES = ['analytics', 'activitypub', 'mailpit', 'supervisor'] as const; @@ -66,14 +98,23 @@ export const LOCAL_ONLY_PROFILES = ['mailpit'] as const; */ export const PRODUCTION_ONLY_PROFILES = ['analytics', 'activitypub'] as const; -/** Why a site of `mode` must not select `profile`, or null when it may. */ -export function profileConflict(mode: SiteMode, profile: string): string | null { - if (mode === 'production' && (LOCAL_ONLY_PROFILES as readonly string[]).includes(profile)) { +/** Why a site of `layout` must not select `profile`, or null when it may. */ +export function profileConflict(layout: Layout, profile: string): string | null { + if (layout !== 'local' && (LOCAL_ONLY_PROFILES as readonly string[]).includes(profile)) { return "is for local sites only: it would catch a production site's real mail"; } - if (mode === 'local' && (PRODUCTION_ONLY_PROFILES as readonly string[]).includes(profile)) { + if (layout === 'local' && (PRODUCTION_ONLY_PROFILES as readonly string[]).includes(profile)) { return 'is for production sites only: a local site has no Caddy to route to it'; } + if ( + layout === NO_CADDY_PROFILE && + (PRODUCTION_ONLY_PROFILES as readonly string[]).includes(profile) + ) { + return ( + "needs Caddy's routes, and this site is behind your own proxy, which the manager\n" + + ' does not configure; see docs/configuration.md#your-own-proxy' + ); + } return null; } @@ -89,17 +130,17 @@ export const splitProfiles = (profiles: string): string[] => * none or more than one. Optional profiles never select a mode. */ export function siteMode(profiles: string): SiteMode | null { - const modes = splitProfiles(profiles).filter((profile): profile is SiteMode => - (SITE_MODES as readonly string[]).includes(profile), + const modes = splitProfiles(profiles).filter((profile) => + Object.hasOwn(MODE_PROFILES, profile), ); - return modes.length === 1 ? modes[0]! : null; + return modes.length === 1 ? MODE_PROFILES[modes[0]!]! : null; } /** Profiles that are neither a site mode nor a known optional profile. */ export const unknownProfiles = (profiles: string): string[] => splitProfiles(profiles).filter( (profile) => - !(SITE_MODES as readonly string[]).includes(profile) && + !Object.hasOwn(MODE_PROFILES, profile) && !(OPTIONAL_PROFILES as readonly string[]).includes(profile), ); @@ -135,7 +176,7 @@ export function generatedSettings(input: { >; readonly port: number; readonly mailpitPort: number | null; - /** Caddy's, written for a production site. */ + /** Caddy's, written for a production site with Caddy. */ readonly ports: { readonly http: string; readonly https: string }; readonly database: { readonly user: string; @@ -145,6 +186,7 @@ export function generatedSettings(input: { }): [string, string][] { const { ghost, database } = input; const production = input.mode === 'production'; + const caddy = layoutOf(input.profiles.join(',')) === 'production'; return Object.entries({ COMPOSE_PROFILES: input.profiles.join(','), SITE_MODE: input.mode, @@ -161,7 +203,7 @@ export function generatedSettings(input: { GHOST_PORT: String(input.port), ...(input.mailpitPort === null ? {} : { MAILPIT_PORT: String(input.mailpitPort) }), RESTART_POLICY: production ? 'unless-stopped' : 'no', - ...(production ? { HTTP_PORT: input.ports.http, HTTPS_PORT: input.ports.https } : {}), + ...(caddy ? { HTTP_PORT: input.ports.http, HTTPS_PORT: input.ports.https } : {}), DATABASE_HOST: 'db', DATABASE_PORT: '3306', DATABASE_NAME: 'ghost', @@ -184,6 +226,8 @@ export const hostOf = (url: string): string => { export interface SiteFacts { readonly dir: string; readonly mode: SiteMode | null; + /** Whether Caddy serves it ('production'), or the operator's own proxy ('no-caddy'). */ + readonly layout: Layout; /** The hosts of URL and ADMIN_URL: what Caddy should serve, in production. */ readonly domain: string; readonly adminDomain: string; @@ -196,6 +240,7 @@ export function siteFacts(dir: string, settings: SiteSettings): SiteFacts { dir, settings, mode: siteMode(value('COMPOSE_PROFILES')), + layout: layoutOf(value('COMPOSE_PROFILES')), domain: hostOf(value('URL')), adminDomain: hostOf(value('ADMIN_URL')), }; diff --git a/manager/src/verify.ts b/manager/src/verify.ts index 573d0d9e..d28faa0b 100644 --- a/manager/src/verify.ts +++ b/manager/src/verify.ts @@ -1,5 +1,7 @@ // Health checks establish readiness; an HTTPS request through Caddy must also -// identify this Ghost site by its canonical URL. Probe the site network, since +// identify this Ghost site by its canonical URL. Behind the operator's own +// proxy there is no Caddy to ask, and the host's proxy cannot be reached from +// here, so only Ghost's health is verified. Probe the site network, since // manager loopback is not host loopback. See docs/architecture.md#verification-and-service-access. import { ServiceUnreachable, type HttpsAnswer } from './clients.ts'; import { composePs, type ServiceState } from './compose.ts'; @@ -7,7 +9,7 @@ import type { Io } from './io.ts'; import { NetworkUnavailable, type SiteNetwork } from './network.ts'; import { CliError } from './errors.ts'; import { failed, heading, printChecks, type Check } from './report.ts'; -import { hasProfile, readSettings, siteFacts, type SiteFacts } from './site.ts'; +import { hasProfile, NO_CADDY_PROFILE, readSettings, siteFacts, type SiteFacts } from './site.ts'; const describeState = (state: ServiceState | undefined): string => state ? [state.State, state.Health].filter(Boolean).join(', ') : 'no container'; @@ -190,7 +192,7 @@ export async function verifyIngress( site: SiteFacts, known?: readonly ServiceState[] | null, ): Promise { - const production = site.mode === 'production'; + const production = site.layout === 'production'; const withMailpit = hasProfile(site.settings.get('COMPOSE_PROFILES') ?? '', 'mailpit'); // `check` has the service states already. const services = known ?? (await composePs(io, site.dir)); @@ -250,6 +252,16 @@ export async function verifyIngress( } } } + if (site.layout === NO_CADDY_PROFILE) { + checks.push({ + status: 'note', + label: 'ingress', + detail: + `your own proxy, which the manager does not configure or check. It must serve\n` + + `${site.settings.get('URL') || 'URL'} over HTTPS and pass it to 127.0.0.1:${site.settings.get('GHOST_PORT') || '2368'} with\n` + + 'X-Forwarded-Proto: https (docs/configuration.md#your-own-proxy)', + }); + } if (withMailpit) { const alias = `mailpit-${site.settings.get('COMPOSE_PROJECT_NAME') || 'ghost'}`; checks.push(healthy('mailpit', state('mailpit'), `Ghost sends mail to ${alias}:1025`)); diff --git a/manager/test/config.test.ts b/manager/test/config.test.ts index 79c39280..fb61bf2d 100644 --- a/manager/test/config.test.ts +++ b/manager/test/config.test.ts @@ -67,6 +67,26 @@ describe('.env', () => { assert.match(result.errors, /selects activitypub, which is for production sites only/); }); + test('a site behind your own proxy is a production one, without what needs Caddy', async () => { + makeSite(h, { ...PRODUCTION, COMPOSE_PROFILES: 'no-caddy,supervisor' }); + const result = await validate(); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /valid for a production site/); + makeSite(h, { ...PRODUCTION, COMPOSE_PROFILES: 'no-caddy,production' }); + assert.match( + (await validate()).errors, + /exactly one site mode \(local, production, no-caddy\)/, + ); + makeSite(h, { ...PRODUCTION, URL: 'http://example.com', COMPOSE_PROFILES: 'no-caddy' }); + assert.match((await validate()).errors, /URL must be https:\/\//); + makeSite(h, { ...PRODUCTION, COMPOSE_PROFILES: 'no-caddy,analytics,activitypub,mailpit' }); + const refused = await validate(); + assert.equal(refused.code, 1); + assert.match(refused.errors, /selects analytics, which needs Caddy's routes/); + assert.match(refused.errors, /selects activitypub, which needs Caddy's routes/); + assert.match(refused.errors, /selects mailpit, which is for local sites only/); + }); + test('SITE_MODE must match COMPOSE_PROFILES', async () => { makeSite(h, { ...LOCAL, SITE_MODE: 'production' }); assert.match((await validate()).errors, /SITE_MODE=production does not match .* \(local\)/); diff --git a/manager/test/import.test.ts b/manager/test/import.test.ts index 8a45213b..7487be61 100644 --- a/manager/test/import.test.ts +++ b/manager/test/import.test.ts @@ -619,6 +619,21 @@ describe('importing a production site', () => { assert.match(result.stdout, /every count matches the bundle/); }); + test("behind your own proxy, it keeps the source's domains and writes no Caddy", async () => { + const result = await install( + '--import', + bundle(fixture('mysql-dump')), + '--no-caddy', + '--no-start', + ); + assert.equal(result.code, 0, result.stderr); + assert.equal(setting('COMPOSE_PROFILES'), 'no-caddy'); + assert.equal(setting('SITE_MODE'), 'production'); + assert.equal(setting('URL'), 'https://example.com'); + assert.equal(setting('ADMIN_URL'), 'https://admin.example.com'); + assert.ok(!existsSync(join(h.dir, 'caddy'))); + }); + test('a failure removes what it created, leaving the directory as it was', async () => { load = () => failed(1, 'ERROR 1064 (42000) at line 1'); const result = await install('--import', bundle(fixture('mysql-dump'))); @@ -667,6 +682,11 @@ describe('refusals that change nothing', () => { 2, /--email applies to production sites, and this bundle is of a local site/, ); + await refusedWith( + ['--import', path, '--no-caddy'], + 2, + /--no-caddy applies to production sites, and this bundle is of a local site/, + ); await refusedWith( ['--import', path, '--with', 'mailpit,activitypub'], 2, diff --git a/manager/test/install.test.ts b/manager/test/install.test.ts index 925d34aa..1093e000 100644 --- a/manager/test/install.test.ts +++ b/manager/test/install.test.ts @@ -61,6 +61,15 @@ describe('refusals that change nothing', () => { [['--local', '--with', 'redis'], /unknown optional service: redis/], [['--domain', 'example.com', '--with', 'mailpit'], /mailpit is for local sites only/], [['--local', '--with', 'activitypub'], /activitypub is for production sites only/], + [['--local', '--no-caddy'], /--no-caddy applies to production sites/], + [ + ['--domain', 'example.com', '--no-caddy', '--email', 'ops@example.com'], + /--email is Caddy's ACME account/, + ], + [ + ['--domain', 'example.com', '--no-caddy', '--with', 'activitypub'], + /--with activitypub needs Caddy's routes, and this site is behind your own proxy[\s\S]*docs\/configuration\.md#your-own-proxy/, + ], [['--local', '--with', 'production'], /--with selects optional services/], [['--local', '--port', '70000'], /port number/], [['--local', '--frobnicate'], /frobnicate/], @@ -587,6 +596,94 @@ describe('a production site, not started', () => { }); }); +describe('a production site behind your own proxy', () => { + test('ports 80 and 443 are left to the proxy, even when a container publishes them', async () => { + h.daemon.containers = [ + { + Id: 'p', + Names: ['/operators-proxy'], + Ports: [ + { PrivatePort: 80, PublicPort: 80, Type: 'tcp' }, + { PrivatePort: 443, PublicPort: 443, Type: 'tcp' }, + ], + }, + ]; + const result = await install('--domain', 'example.com', '--no-caddy', '--no-start'); + assert.equal(result.code, 0, result.stderr); + }); + + test('it is a production site with no Caddy: no routes, no Caddy ports, and the proxy is told where Ghost is', async () => { + const result = await install( + '--domain', + 'example.com', + '--admin-domain', + 'admin.example.com', + '--no-caddy', + '--with', + 'supervisor', + '--no-start', + ); + assert.equal(result.code, 0, result.stderr); + const values = env.toRecord(readFileSync(join(h.dir, '.env'), 'utf8')); + assert.equal(values.COMPOSE_PROFILES, 'no-caddy,supervisor'); + assert.equal(values.SITE_MODE, 'production'); + assert.equal(values.NODE_ENV, 'production'); + assert.equal(values.RESTART_POLICY, 'unless-stopped'); + assert.equal(values.URL, 'https://example.com'); + assert.equal(values.ADMIN_URL, 'https://admin.example.com'); + assert.equal(values.COMPOSE_PROJECT_NAME, 'ghost-example-com'); + assert.equal(values.HTTP_PORT, undefined); + assert.equal(values.HTTPS_PORT, undefined); + assert.ok(!existsSync(join(h.dir, 'caddy'))); + assert.ok(!existsSync(join(h.dir, 'tinybird'))); + const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); + assert.equal(metadata.mode, 'production'); + assert.deepEqual(metadata.profiles, ['no-caddy', 'supervisor']); + assert.deepEqual( + Object.keys(metadata.payload).filter((file) => /^(caddy|tinybird)\//.test(file)), + [], + ); + assert.match(result.stdout, /Loopback {5}127\.0\.0\.1:2368, for your proxy/); + // Not started, the proxy is still the operator's to set up first. + assert.match( + result.stdout, + /Nothing is running\.[^\n]*\nPoint your proxy at 127\.0\.0\.1:2368 for example\.com and admin\.example\.com,\nover HTTPS, with X-Forwarded-Proto: https/, + ); + assert.match(result.stdout, /\.env and ghost\.env are valid for a production site/); + assert.ok(!compose.some((args) => args[0] === 'up' || args[0] === 'run')); + }); + + test('started, it is verified by Ghost alone, and the proxy is left to the operator', async () => { + h.daemon.composeRun = (args) => { + compose.push(args); + switch (args[0]) { + case 'config': + return ok(JSON.stringify({ services: { ghost: { environment: {} } } })); + case 'ps': + return ok( + JSON.stringify({ + Service: 'ghost', + State: 'running', + Health: 'healthy', + Publishers: [{ URL: '127.0.0.1', PublishedPort: 2368 }], + }), + ); + default: + return ok(''); + } + }; + const result = await install('--domain', 'example.com', '--no-caddy'); + assert.equal(result.code, 0, result.stderr); + assert.match( + result.stdout, + /ingress {12}your own proxy, which the manager does not configure/, + ); + assert.match(result.stdout, /Point your proxy at 127\.0\.0\.1:2368 for example\.com/); + assert.doesNotMatch(result.stdout, /caddy\/|ok +caddy|Caddy obtains/); + assert.deepEqual(h.network.probes, []); + }); +}); + describe('the project name', () => { /** A container of `project`, made in `dir`, as Compose labels it. */ const containerOf = (project: string, dir: string) => ({ diff --git a/manager/test/integration/compose.test.ts b/manager/test/integration/compose.test.ts index 2161690e..181ca898 100644 --- a/manager/test/integration/compose.test.ts +++ b/manager/test/integration/compose.test.ts @@ -134,6 +134,25 @@ test('every profile is `*` to Compose, so undo finds whatever a failed install s } }); +test("a site behind the operator's own proxy is Ghost and MySQL, Ghost on loopback, and no Caddy", async () => { + const site = makeSite(io, 'no-caddy', { + profiles: 'no-caddy,supervisor', + url: 'https://example.com', + override: '', + }); + const listed = await compose(io, { dir: site.dir })`config --services`; + assert.equal(listed.exitCode, 0, listed.stderr); + assert.deepEqual(listed.stdout.trim().split('\n').sort(), ['db', 'ghost', 'supervisor']); + const config = await compose(io, { dir: site.dir })`config --format json`; + assert.equal(config.exitCode, 0, config.stderr); + const ghost = JSON.parse(config.stdout).services.ghost; + assert.deepEqual( + ghost.ports.map((port: Record) => [port.host_ip, port.published]), + [['127.0.0.1', '2368']], + ); + assert.equal(ghost.environment.url, 'https://example.com'); +}); + for (const rootOverride of [false, true]) { for (const absolute of [false, true]) { test(`a nested compose.override.yml COMPOSE_FILE names is effective and inventoried (root ${rootOverride}, absolute ${absolute})`, async () => { diff --git a/manager/test/integration/site.ts b/manager/test/integration/site.ts index 2ff74349..a312256c 100644 --- a/manager/test/integration/site.ts +++ b/manager/test/integration/site.ts @@ -10,7 +10,7 @@ import { inspectContainer } from '../../src/docker/client.ts'; import * as env from '../../src/env.ts'; import { processIo, type Io } from '../../src/io.ts'; import { onSiteNetwork } from '../../src/network.ts'; -import { readSettings, siteFacts, type SiteFacts } from '../../src/site.ts'; +import { readSettings, siteFacts, siteMode, type SiteFacts } from '../../src/site.ts'; const REPO = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..'); @@ -84,7 +84,7 @@ export function makeSite(io: Io, name: string, options: SiteOptions): TestSite { env.serializeAll([ ['COMPOSE_PROJECT_NAME', project], ['COMPOSE_PROFILES', options.profiles], - ['SITE_MODE', options.profiles.includes('production') ? 'production' : 'local'], + ['SITE_MODE', siteMode(options.profiles) ?? 'local'], ['URL', options.url ?? 'http://localhost:2368'], ['DATABASE_PASSWORD', secret()], ['DATABASE_ROOT_PASSWORD', secret()], diff --git a/manager/test/verify.test.ts b/manager/test/verify.test.ts index 5df5e3b8..3535c0ef 100644 --- a/manager/test/verify.test.ts +++ b/manager/test/verify.test.ts @@ -291,6 +291,22 @@ test('a local site has no Caddy, and nothing to ask on its network', async () => assert.deepEqual(h.network.probes, []); }); +describe('a production site behind your own proxy', () => { + test("Ghost's health is all that is verified: the proxy is the operator's, and nothing is asked through it", async () => { + site.caddy = 'unhealthy'; + const checks = await verify({ ...PRODUCTION, COMPOSE_PROFILES: 'no-caddy' }); + assert.deepEqual(Object.keys(checks), ['ghost', 'ingress', 'published ports']); + assert.equal(checks.ghost!.status, 'ok'); + assert.equal(checks.ingress!.status, 'note'); + assert.match( + checks.ingress!.detail, + /your own proxy[\s\S]*https:\/\/example\.com over HTTPS and pass it to 127\.0\.0\.1:2368 with\nX-Forwarded-Proto: https/, + ); + assert.doesNotMatch(checks['published ports']!.detail, /Caddy/); + assert.deepEqual(h.network.probes, []); + }); +}); + describe('a local site with Mailpit', () => { const MAILPIT = { ...LOCAL, COMPOSE_PROFILES: 'local,mailpit' }; diff --git a/tests/e2e/install.sh b/tests/e2e/install.sh index adeac28d..240adf9a 100755 --- a/tests/e2e/install.sh +++ b/tests/e2e/install.sh @@ -214,7 +214,7 @@ fi # --- An existing proxy on 80 and 443 ------------------------------------------ -step "A proxy already serving 80 and 443" +step "A proxy already serving 80 and 443, and a site behind it" new_site e2e-existing-proxy X=$SITE if port_free 80 && port_free 443; then @@ -228,6 +228,36 @@ if port_free 80 && port_free 443; then [[ $(docker inspect -f '{{.State.Running}}' "$PROXY") == true ]] || fail "the proxy was stopped" [[ -z $(ls -A "$X") ]] || fail "files were written" "$(ls -A "$X")" ok "refused before anything was written, naming the container, which still runs" + + # Behind that proxy instead: no Caddy, and 80 and 443 left alone. + run install_alone "$X" --domain "$DOMAIN" --no-caddy + expect_status 0 + expect_output 'ok +ghost +healthy' + expect_output 'note +ingress +your own proxy, which the manager does not configure or check' + [[ $(docker inspect -f '{{.State.Running}}' "$PROXY") == true ]] || fail "the proxy was stopped" + [[ ! -e $X/caddy && -z $(compose_in "$X" ps --quiet caddy 2>/dev/null || true) ]] || fail "Caddy was installed" + [[ $(setting "$X" COMPOSE_PROFILES) == no-caddy && $(setting "$X" SITE_MODE) == production ]] || + fail "not configured as a production site behind a proxy" "$(cat "$X/.env")" + ok "installed beside the proxy, with no Caddy" + + # What the operator's proxy sends, from the host's loopback port. + port=$(setting "$X" GHOST_PORT) + body=$(curl --silent --noproxy '*' --max-time 20 --header "Host: $DOMAIN" \ + --header 'X-Forwarded-Proto: https' --header 'X-Forwarded-For: 203.0.113.7' \ + "http://127.0.0.1:$port/ghost/api/admin/site/" || true) + [[ $(jq -r .site.url <<<"$body" 2>/dev/null) == "https://$DOMAIN/" ]] || + fail "Ghost did not answer on 127.0.0.1:$port with X-Forwarded-Proto: https" "$body" + # Without the header, Ghost sends the proxy back to HTTPS: the loop the docs warn about. + location=$(curl --silent --noproxy '*' --max-time 20 --output /dev/null --write-out '%{redirect_url}' \ + --header "Host: $DOMAIN" "http://127.0.0.1:$port/" || true) + [[ $location == "https://$DOMAIN/"* ]] || fail "Ghost did not redirect a request without X-Forwarded-Proto (got '$location')" + ok "Ghost answers on loopback with X-Forwarded-Proto: https, and redirects without it" + + run "$X/ghost-docker" --dir "$X" check + expect_status 0 + expect_output 'note +ingress +your own proxy' + ok "check passes, and leaves the ingress to the proxy" + compose_in "$X" down --volumes >/dev/null 2>&1 docker rm -f "$PROXY" >/dev/null else skip "something on this host already holds 80 or 443"