diff --git a/CLAUDE.md b/CLAUDE.md index 8614adf..4841f4b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,9 +34,9 @@ Releases are cut with `scripts/release.sh [notes]`, which patches `int - *Project containers* (`internal/project/manager.go`): one `ingot_php_` container per project directory, created directly via `docker.Client.RunContainer` (not compose) — or, for a project with `image_type=custom` and a build-from-Dockerfile choice, via `docker.Client.BuildImage` first. Changing PHP version, image choice, or server root means destroying and recreating the container, not reconfiguring it in place. - *Global services* (`internal/services/manager.go`): `ingot_dns`, `ingot_proxy`, `ingot_mail`, plus any configured databases, all managed as one Docker Compose project (`name: ingot`) whose YAML is generated inline in Go (`generateComposeConfig`) rather than read from a file. Adding/removing a database rewrites and re-applies the whole compose config, which restarts the group. -**Images come from a private GHCR registry** (`ghcr.io/aliasproject/{php,dns,caddy,openssl}`), so most flows depend on GitHub auth being set up first (`internal/github/client.go` — supports PAT, OAuth device flow, or delegating to `gh auth token`, then does the `docker login ghcr.io` for image pulls). The `php` image comes in several variant tags per PHP version (`-frankenphp-dev`, `-frankenphp-wordpress-dev`, ...), selected in `project.Manager.createContainer` based on the project's detected/chosen `framework` and `image_type` labels. +**Images come from a private GHCR registry** (`ghcr.io/aliasproject/{php,dns,caddy,ingot-openssl}`), so most flows depend on GitHub auth being set up first (`internal/github/client.go` — supports PAT, OAuth device flow, or delegating to `gh auth token`, then does the `docker login ghcr.io` for image pulls). The `php` image comes in several variant tags per PHP version (`-frankenphp-dev`, `-frankenphp-wordpress-dev`, ...), selected in `project.Manager.createContainer` based on the project's detected/chosen `framework` and `image_type` labels. -**SSL** (`internal/ssl/manager.go`): a CA cert and per-domain certs are generated by running the `ghcr.io/aliasproject/openssl` image against the `ingot_certs` volume (not via a Go TLS library) — self-signed, not Let's Encrypt, since `.test` domains are IANA-reserved and never publicly resolvable so ACME has no path to succeed. Per-project Caddy vhost files (`.caddyfile`) are written directly into the `ingot_vhosts` volume, which is mounted at `/etc/caddy` in the `ingot_proxy` container alongside a base `Caddyfile` (written by `services.Manager.Start`) that does `import /etc/caddy/*.caddyfile` — adding or removing a project is just adding/removing one file plus `caddy reload`, no full-file rewrite. There's no templating engine, just Go `fmt.Sprintf` strings. The base Caddyfile also has host-less `https://`/`http://` catch-all sites that serve a branded "No project here" 404 page (`internal/services/default_page.html`, embedded in the binary and written to `ingot_vhosts/default/`) for any `*.test` host without a vhost. Its HTTPS side can't use a static cert (browsers reject a wildcard directly under a TLD like `*.test`), so it uses Caddy's on-demand internal issuer with the ingot CA as its root (the `pki` global block; `ssl.Manager.PrepareCAForCaddy` makes the CA key readable to Caddy before start), minting an exact cert per requested host that chains to the already-trusted CA. +**SSL** (`internal/ssl/manager.go`): a CA cert ("Ingot Local CA", `IngotLocalCA.pem`) and per-domain certs are generated by running the `ghcr.io/aliasproject/ingot-openssl:` image (`Dockerfile.openssl` + `openssl/entrypoint.sh`, pushed by `scripts/release.sh` alongside `ingot-idle`) against the `ingot_certs` volume (not via a Go TLS library) — self-signed, not Let's Encrypt, since `.test` domains are IANA-reserved and never publicly resolvable so ACME has no path to succeed. Per-project Caddy vhost files (`.caddyfile`) are written directly into the `ingot_vhosts` volume, which is mounted at `/etc/caddy` in the `ingot_proxy` container alongside a base `Caddyfile` (written by `services.Manager.Start`) that does `import /etc/caddy/*.caddyfile` — adding or removing a project is just adding/removing one file plus `caddy reload`, no full-file rewrite. There's no templating engine, just Go `fmt.Sprintf` strings. The base Caddyfile also has host-less `https://`/`http://` catch-all sites that serve a branded "No project here" 404 page (`internal/services/default_page.html`, embedded in the binary and written to `ingot_vhosts/default/`) for any `*.test` host without a vhost. Its HTTPS side can't use a static cert (browsers reject a wildcard directly under a TLD like `*.test`), so it uses Caddy's on-demand internal issuer with the ingot CA as its root (the `pki` global block; `ssl.Manager.PrepareCAForCaddy` makes the CA key readable to Caddy before start), minting an exact cert per requested host that chains to the already-trusted CA. **Sharing** (`internal/share/manager.go`, `ingot share`): exposes a project publicly through a Cloudflare Tunnel. A `cloudflared` container on `ingot_internal` sends traffic to Caddy over plain HTTP, and a `.share.caddyfile` vhost matching the exact public host proxies it on to the project. That vhost file is the only record of a share's URL, mode and auth. The tunnel containers carry `ingot.share.*` labels only so leftovers can be found and removed, and they're deliberately not global services, so `global restart` doesn't bounce them. Quick mode (default) runs one `ingot_share_` container per share with a random trycloudflare.com URL. Named mode (`INGOT_SHARE_TUNNEL_TOKEN` + `INGOT_SHARE_DOMAIN`) runs one shared `ingot_share` container whose `*.` ingress is configured in the Cloudflare dashboard. See `docs/SHARING.md`. diff --git a/Dockerfile.openssl b/Dockerfile.openssl new file mode 100644 index 0000000..d37e4e4 --- /dev/null +++ b/Dockerfile.openssl @@ -0,0 +1,30 @@ +# Generates the Ingot Local CA and per-domain certificates +# (openssl/entrypoint.sh). Published as ghcr.io/aliasproject/ingot-openssl: +# by scripts/release.sh, tagged with the CLI version so a CLI always gets the +# file names and certificate layout it was built against. +# +# Like Dockerfile.idle, this builds an arm64 image without emulation (QEMU) +# on an amd64 machine: rather than RUN apk add on the target platform, the +# fetch stage runs on the build platform, downloads the target +# architecture's openssl packages and unpacks them onto the stock alpine +# image. +ARG ALPINE_VERSION=3.22 + +FROM --platform=$BUILDPLATFORM alpine:${ALPINE_VERSION} AS fetch +ARG TARGETARCH +RUN case "$TARGETARCH" in \ + amd64) arch=x86_64 ;; \ + arm64) arch=aarch64 ;; \ + *) echo "unsupported architecture: $TARGETARCH" >&2; exit 1 ;; \ + esac \ + && apk add --no-cache tar \ + && mkdir /pkgs /rootfs && cd /pkgs \ + && apk fetch --no-cache --keys-dir "/usr/share/apk/keys/$arch" --arch "$arch" openssl libcrypto3 libssl3 \ + && for p in *.apk; do tar -xzf "$p" -C /rootfs --exclude='.*' 2>/dev/null; done \ + && test -x /rootfs/usr/bin/openssl + +FROM alpine:${ALPINE_VERSION} +LABEL org.opencontainers.image.source=https://github.com/aliasproject/ingot +COPY --from=fetch /rootfs/ / +COPY openssl/entrypoint.sh /entrypoint.sh +ENTRYPOINT ["sh", "/entrypoint.sh"] diff --git a/internal/config/config.go b/internal/config/config.go index 8fd564f..885b9a0 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -22,6 +22,11 @@ const ( // IdleImage is the ingot_idle service's image, tagged with the CLI // version so each CLI runs the service built from the same source. IdleImage = "ghcr.io/aliasproject/ingot-idle:" + Version + + // OpensslImage generates the CA and per-domain certificates + // (Dockerfile.openssl), tagged with the CLI version for the same reason: + // the CLI relies on the file names and certificate layout it writes. + OpensslImage = "ghcr.io/aliasproject/ingot-openssl:" + Version ) // Config holds the application configuration diff --git a/internal/services/manager.go b/internal/services/manager.go index 3f0487c..37296a5 100644 --- a/internal/services/manager.go +++ b/internal/services/manager.go @@ -71,7 +71,7 @@ const baseCaddyfile = `{ skip_install_trust pki { ca ingot { - name "Ingot Local CA" + name "` + ssl.CAName + `" root { cert /etc/caddy/ssl/` + ssl.CACertFile + ` key /etc/caddy/ssl/` + ssl.CAKeyFile + ` diff --git a/internal/ssl/manager.go b/internal/ssl/manager.go index fbe37b6..041af69 100644 --- a/internal/ssl/manager.go +++ b/internal/ssl/manager.go @@ -52,12 +52,21 @@ func (m *Manager) SetupSSL() error { } // CACertFile and CAKeyFile are the CA's filenames inside the ingot_certs -// volume, as written by the openssl image's entrypoint. +// volume, and CAName is its common name, which is how the OS trust stores +// and NSS databases find it. All three are set by openssl/entrypoint.sh. const ( - CACertFile = "AliasProjectCASelfSigned.pem" - CAKeyFile = "AliasProjectCASelfSigned.key" + CACertFile = "IngotLocalCA.pem" + CAKeyFile = "IngotLocalCA.key" + CAName = "Ingot Local CA" ) +// linuxCAFile is where the CA is installed on distros without p11-kit's +// `trust` (Debian/Ubuntu). IsCertificateInstalled can only check that the +// file exists, so the name is tied to the CA's: the "Alias Project" CA was +// installed as ingot-ca.crt, and finding that file must not count as +// trusting this one. +const linuxCAFile = "/usr/local/share/ca-certificates/ingot-local-ca.crt" + // PrepareCAForCaddy makes sure the CA exists and that Caddy's non-root user // can read its private key. The reverse proxy's catch-all site issues // on-demand certs signed by this CA (see services.baseCaddyfile), and Caddy @@ -87,7 +96,7 @@ func (m *Manager) SetupProjectSSL(projectName string) error { // Check if CA certificate exists first if !m.caExistsInVolume() { - return fmt.Errorf("CA certificate not found. Run 'ingot cert install' first") + return fmt.Errorf("CA certificate not found. Run 'ingot global start' first") } // Check if Caddy is running @@ -140,7 +149,7 @@ func (m *Manager) SetupProjectSSL(projectName string) error { // successfully; per-project failures are collected but do not stop the rest. func (m *Manager) RepairVhosts(projectNames []string) (int, error) { if !m.caExistsInVolume() { - return 0, fmt.Errorf("CA certificate not found. Run 'ingot cert install' first") + return 0, fmt.Errorf("CA certificate not found. Run 'ingot global start' first") } // Keep projects stopped with `ingot stop` stopped: a repair only fixes @@ -201,11 +210,8 @@ func (m *Manager) ReloadCaddy() error { func (m *Manager) RemoveProjectSSL(projectName string) error { domain := projectName + ".test" - // Remove certificate files directly from ingot_certs volume. Includes - // .csr alongside .crt/.key: the openssl image only (re)generates each of - // key/csr/crt when that specific file is missing, so leaving a stale - // .csr behind means a future generation reuses it as-is - signing it - // produces a .crt that doesn't match the freshly generated .key. + // Remove certificate files directly from ingot_certs volume, .csr + // included so nothing of the old certificate is left behind. // This works regardless of Caddy container state if err := m.docker.Run("run", "--rm", "-v", "ingot_certs:/certs", "alpine:latest", "sh", "-c", fmt.Sprintf("rm -f /certs/%s.crt /certs/%s.key /certs/%s.csr", domain, domain, domain)); err != nil { @@ -284,7 +290,7 @@ func (m *Manager) GenerateCertificate(domain string) error { cmd := exec.Command("docker", "run", "--rm", "-e", "DOMAIN="+domain, "-v", "ingot_certs:/certificates", - "ghcr.io/aliasproject/openssl:latest") + config.OpensslImage) output, err := cmd.CombinedOutput() if err != nil { @@ -454,7 +460,7 @@ func (m *Manager) caExistsInVolume() bool { err := m.docker.Run("run", "--rm", "-v", "ingot_certs:/certificates", "alpine:latest", - "test", "-f", "/certificates/AliasProjectCASelfSigned.pem", + "test", "-f", "/certificates/"+CACertFile, ) return err == nil } @@ -479,9 +485,8 @@ func (m *Manager) certificateExists(domain string) bool { func (m *Manager) generateCA() error { return m.docker.Run("run", "--rm", - "-e", "DOMAIN=init", "-v", "ingot_certs:/certificates", - "ghcr.io/aliasproject/openssl:latest", + config.OpensslImage, ) } @@ -492,7 +497,7 @@ func (m *Manager) copyCAToTempFile(tmpPath string) error { "-v", "ingot_certs:/source", "-v", filepath.Dir(tmpPath)+":/dest", "alpine:latest", - "cp", "/source/AliasProjectCASelfSigned.pem", "/dest/"+filepath.Base(tmpPath), + "cp", "/source/"+CACertFile, "/dest/"+filepath.Base(tmpPath), ) } @@ -610,13 +615,16 @@ func (m *Manager) StoppedProjects() (map[string]bool, error) { return stopped, nil } +// reloadCaddy uses --force because Caddy skips a reload whose config text +// is unchanged, and a reissued certificate keeps the same file paths: without +// it Caddy would go on serving the old certificate from memory. func (m *Manager) reloadCaddy() error { - return m.docker.Run("exec", "ingot_proxy", "caddy", "reload", "--config", "/etc/caddy/Caddyfile") + return m.docker.Run("exec", "ingot_proxy", "caddy", "reload", "--force", "--config", "/etc/caddy/Caddyfile") } func (m *Manager) installCertMacOS(caPath string) error { // Remove old certificate if exists - exec.Command("sudo", "security", "delete-certificate", "-c", "AliasProjectCASelfSigned", "/Library/Keychains/System.keychain").Run() + exec.Command("sudo", "security", "delete-certificate", "-c", CAName, "/Library/Keychains/System.keychain").Run() // Add new certificate cmd := exec.Command("sudo", "security", "add-trusted-cert", @@ -662,7 +670,7 @@ func (m *Manager) installCertLinux(caPath string) error { } } else { // Copy to system certificate store - destPath := "/usr/local/share/ca-certificates/ingot-ca.crt" + destPath := linuxCAFile cmd := exec.Command("sudo", "cp", caPath, destPath) if err := cmd.Run(); err != nil { @@ -718,7 +726,7 @@ func (m *Manager) installCertIntoNSSDatabases(caPath string) { cmd := exec.Command(certutilPath, "-d", "sql:"+dir, "-A", "-t", "C,,", - "-n", "Alias Project CA Self Signed CN", + "-n", CAName, "-i", caPath) if output, err := cmd.CombinedOutput(); err != nil { fmt.Printf(utils.Colorize("[WARNING]", utils.ColorYellow)+" Warning: failed to trust certificate in %s: %v\n%s\n", dir, err, output) @@ -773,7 +781,7 @@ func (m *Manager) installCertWindows(caPath string) error { func (m *Manager) IsCertificateInstalled() bool { switch runtime.GOOS { case "darwin": - cmd := exec.Command("security", "find-certificate", "-c", "AliasProjectCASelfSigned", "/Library/Keychains/System.keychain") + cmd := exec.Command("security", "find-certificate", "-c", CAName, "/Library/Keychains/System.keychain") return cmd.Run() == nil case "linux": // installCertLinux uses `trust anchor` when available (Arch, Fedora, @@ -784,10 +792,12 @@ func (m *Manager) IsCertificateInstalled() bool { if _, err := exec.LookPath("trust"); err == nil { return m.isCertificateInstalledViaTrust() } - return fileExists("/usr/local/share/ca-certificates/ingot-ca.crt") + return fileExists(linuxCAFile) case "windows": - cmd := exec.Command("powershell", "-Command", - "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*AliasProjectCASelfSigned*' }") + // A pipeline that matches nothing still exits 0, so set the exit + // code from whether anything matched. + cmd := exec.Command("powershell", "-NoProfile", "-Command", + "if (Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*CN="+CAName+"*' }) { exit 0 } else { exit 1 }") return cmd.Run() == nil default: return false @@ -805,7 +815,7 @@ func (m *Manager) isCertificateInstalledViaTrust() bool { return false } normalized := strings.ToLower(strings.Join(strings.Fields(string(output)), "")) - return strings.Contains(normalized, "aliasprojectcaselfsigned") + return strings.Contains(normalized, strings.ToLower(strings.ReplaceAll(CAName, " ", ""))) } // isCertificateInstalledInChromeNSSDB checks Chrome/Chromium's default NSS @@ -854,14 +864,14 @@ func (m *Manager) isCertificateInstalledInChromeNSSDB() bool { return false } dir := filepath.Join(home, ".pki", "nssdb") - cmd := exec.Command(certutilPath, "-L", "-d", "sql:"+dir, "-n", "Alias Project CA Self Signed CN") + cmd := exec.Command(certutilPath, "-L", "-d", "sql:"+dir, "-n", CAName) return cmd.Run() == nil } func (m *Manager) showSystemCertificateInfo() { switch runtime.GOOS { case "darwin": - cmd := exec.Command("security", "find-certificate", "-c", "AliasProjectCASelfSigned", "-p", "/Library/Keychains/System.keychain") + cmd := exec.Command("security", "find-certificate", "-c", CAName, "-p", "/Library/Keychains/System.keychain") if output, err := cmd.Output(); err == nil && len(output) > 0 { fmt.Println(" Location: System Keychain") fmt.Println(" Trust: SSL, Basic X.509") @@ -869,7 +879,7 @@ func (m *Manager) showSystemCertificateInfo() { case "linux": if _, err := exec.LookPath("trust"); err == nil && m.isCertificateInstalledViaTrust() { fmt.Println(" Location: p11-kit trust store (trust anchor)") - } else if fileExists("/usr/local/share/ca-certificates/ingot-ca.crt") { + } else if fileExists(linuxCAFile) { fmt.Println(" Location: /usr/local/share/ca-certificates/") } case "windows": diff --git a/openssl/entrypoint.sh b/openssl/entrypoint.sh new file mode 100644 index 0000000..5d4aa62 --- /dev/null +++ b/openssl/entrypoint.sh @@ -0,0 +1,71 @@ +#!/bin/sh +# Generates the Ingot Local CA and per-domain certificates into +# /certificates (the ingot_certs volume). See internal/ssl/manager.go. +# +# Files are generated when missing, so re-running is safe and the CA is +# never replaced. A domain's csr and crt are also regenerated with a new key, +# and its crt is reissued when it no longer verifies against the CA (the CA +# was regenerated) or expires within 30 days. Ingot runs this on every +# `ingot start` (ssl.SetupProjectSSL). With DOMAIN unset only the CA is +# generated. +# +# No path length limit on the CA: Caddy's on-demand issuer for unknown +# hosts (services.baseCaddyfile) signs through an intermediate it creates. + +set -e + +CERTS=/certificates +CA_CERT="$CERTS/IngotLocalCA.pem" +CA_KEY="$CERTS/IngotLocalCA.key" +# These names and the CN below must match the constants in +# internal/ssl/manager.go (CACertFile, CAKeyFile, CAName). + +# The CA browsers and the OS are asked to trust. Valid for ten years, like +# mkcert's, so users don't have to re-trust it every two. +if [ ! -f "$CA_CERT" ]; then + openssl req -x509 -new -nodes -sha256 -days 3650 \ + -newkey rsa:3072 -keyout "$CA_KEY" -out "$CA_CERT" \ + -subj "/O=Alias Project/OU=Ingot/CN=Ingot Local CA" \ + -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" \ + -addext "subjectKeyIdentifier=hash" +fi + +[ -n "$DOMAIN" ] || exit 0 + +# A new key invalidates any csr and crt left over from the old one: signing +# the stale csr would give a crt that doesn't match the key. +if [ ! -f "$CERTS/$DOMAIN.key" ]; then + rm -f "$CERTS/$DOMAIN.csr" "$CERTS/$DOMAIN.crt" + openssl genrsa -out "$CERTS/$DOMAIN.key" 2048 +fi + +# A reissue rebuilds the csr too, so it picks up this script's subject +# (certs from the old image's csr had an @aliasproject.ssl email address). +crt="$CERTS/$DOMAIN.crt" +if [ -f "$crt" ] && ! { openssl verify -CAfile "$CA_CERT" "$crt" >/dev/null 2>&1 && + openssl x509 -in "$crt" -noout -checkend 2592000 >/dev/null; }; then + rm -f "$crt" "$CERTS/$DOMAIN.csr" +fi + +if [ ! -f "$CERTS/$DOMAIN.csr" ]; then + openssl req -new -key "$CERTS/$DOMAIN.key" -out "$CERTS/$DOMAIN.csr" \ + -subj "/CN=$DOMAIN" +fi + +# 825 days is the longest validity Apple platforms accept for a TLS server +# certificate, and they also require the serverAuth extended key usage. +if [ ! -f "$CERTS/$DOMAIN.crt" ]; then + ext=$(mktemp) + cat > "$ext" <