diff --git a/docs/API.md b/docs/API.md index b0179a706..33ecddae9 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2157,6 +2157,12 @@ and SERVICE_START rejects a `duration` outside it: Environments on the same engine may therefore report different values for both. +`features` (`{ computeJobs, services, secureTls? }`) tells what an environment accepts. +`secureTls: true` means service ports can be served over HTTPS (`secureTls` in `serviceStart` / +`serviceRestart`): the environment is the node's first local Docker environment, its `nodeHost` +is a public IP or a domain, and the node's Caddy accepted the last update. An older +node omits it; treat a missing value as `false`. + Both fields are additive, and an older node omits them. Their fallbacks differ, so treat each separately: @@ -2730,6 +2736,7 @@ Operator-published blueprint. Secret `envVars` values are never returned — onl | image | string | base image | | tag / checksum / dockerfile | string | image spec — exactly one | | exposedPorts | number[] | container ports to forward | +| secureTls | number[] | HTTP ports to request over HTTPS (subset of exposedPorts) | | envVarKeys | string[] | keys of operator-set env vars (values never returned) | | userConfigurableEnvVars | object[] | `{ key, validation?, sensitive? }` passed via `userData` | | command / entrypoint | string[] | Docker CMD / ENTRYPOINT overrides | @@ -2768,14 +2775,15 @@ The encrypted `userData` is never returned. Key fields: | environment | string | envId the service runs on | | owner | string | consumerAddress | | status | number | `10` Starting, `20` Locking, `11` PullImage, `13` BuildImage, `30` Claiming, `40` Running, `12` PullImageFailed, `14` BuildImageFailed, `15` VulnerableImage, `50` Stopping, `70` Stopped, `75` Expired, `76` DiskQuotaExceeded (restartable/editable like Stopped until expiresAt), `99` Error | -| statusText | string | human-readable status | -| dateCreated | string | ISO timestamp | -| expiresAt | number | Unix ms timestamp when the paid window ends | -| duration | number | requested seconds | -| endpoints | object[] | `{ containerPort, hostPort, url }` per exposed port | -| resources | object[] | `{ id, amount, price }` | -| payment | object | initial start payment record | -| extendPayments | object[] | one entry per successful extend | +| statusText | string | human-readable status | +| dateCreated | string | ISO timestamp | +| expiresAt | number | Unix ms timestamp when the paid window ends | +| duration | number | requested seconds | +| endpoints | object[] | `{ containerPort, hostPort, url, tls }` per exposed port. `tls: true` → `url` is `https://:` (served by the node's Caddy); otherwise `http://` | +| secureTls | number[] | container ports served over HTTPS; absent when none | +| resources | object[] | `{ id, amount, price }` | +| payment | object | initial start payment record | +| extendPayments | object[] | one entry per successful extend | --- @@ -2869,7 +2877,8 @@ should keep watching `serviceStatus`, not just stop once they first see `Running | duration | number | v | seconds; capped by `serviceOnDemand.maxDurationSeconds` | | userData | string | | ECIES-encrypted (to the node pubkey) JSON of env vars | | metadata | object | | arbitrary user labels (`string`/`number`/`boolean` values, ≤1 KB JSON); node-opaque. Returned on both `serviceStatus` and `serviceList` | -| payment | object | v | `{ chainId, token }` | +| secureTls | number[] | | exposed HTTP container ports to serve over HTTPS (unique). Needs `features.secureTls` on the environment (else 400). TLS only: authentication is the image's own job. See [services.md](services.md#https-endpoints-securetls) | +| payment | object | v | `{ chainId, token }` | #### Response (200) @@ -3065,6 +3074,7 @@ RESPEC mode (restart on a new image spec — `image` required, plus at most one | dockerCmd | string[] | | exact container command (Docker exec-form CMD override) | | dockerEntrypoint | string[] | | container ENTRYPOINT override | | metadata | object | | user labels (≤1 KB JSON). **Not** a container param — independent of REUSE/RESPEC. When present it **replaces** the stored metadata; when omitted the original metadata is kept | +| secureTls | number[] | | container ports, like `serviceStart`. **Not** a container param. When present it **replaces** the stored list (`[]` turns TLS off); when omitted the stored list is kept. A non-empty list needs `features.secureTls` (else 400). An omitted list drops TLS only when the node's config no longer allows it (e.g. `nodeHost` is now private); while TLS is only temporarily unavailable, the stored list is kept | | ports | object[] | | `{ containerPort, hostPort? }[]` — change the ports, optionally **pinning** host ports (`hostPort` omitted = auto-allocate). Independent of REUSE/RESPEC (no `image` required). Validated/reserved up front: an unavailable requested host port is rejected and the running service is **left untouched**; on success the old host ports are freed after teardown and the `endpoints`/URLs change. Omitted ⇒ keep current ports. (The legacy `exposedPorts` field is **not** read on restart — use `ports`.) | #### Response (200) diff --git a/docs/networking.md b/docs/networking.md index b0cf6e9af..1aba98631 100644 --- a/docs/networking.md +++ b/docs/networking.md @@ -110,6 +110,49 @@ When a TLS certificate is provisioned successfully, you will see logs like: ----- End of TLS addresses ----- ``` +## Service TLS: the Caddy proxy + +Services can serve their ports over HTTPS (see [services.md](services.md#https-endpoints-securetls)). +TLS is done by the official [Caddy](https://caddyserver.com/) image. The node starts and manages +it; you do not add it to your compose file. + +- The node runs one container, `ocean-node-caddy` (`caddy:2.11.9-alpine`, host network, + restart `always`, certificates in the `ocean-node-caddy-data` volume). It sends Caddy the + config with `docker exec`, to Caddy's admin API on the host's `127.0.0.1:2019`. +- Only the first local (`socketPath`) Docker environment does this, with its + `serviceOnDemand.nodeHost` as the certificate name: a public IP or a domain. With + `localhost` or a private IP, service TLS is off and the node logs one line asking you to set + it. +- The node sends the config when the services change, and again every minute (so a restarted + Caddy gets it back). An environment shows `features.secureTls: true` only after Caddy + accepted the last config. Caddy's log: `docker logs ocean-node-caddy`. +- Open the service `hostPortRange` (TCP), as for plain services: Caddy listens on the secure + host ports. +- One ocean-node with service TLS per Docker host: Caddy binds the host's port 80 and admin port 2019. A second node finds `ocean-node-caddy` owned by the first and keeps TLS off. + +### Certificate from Let's Encrypt (default) + +Caddy gets and renews a Let's Encrypt certificate for `nodeHost` on its own, with the +`shortlived` profile (needed for IP certificates). **Port 80 must be free**: Let's Encrypt +checks the name with an HTTP request on port 80, and Caddy (host network) answers it. + +### Nodes where a proxy already holds ports 80 and 443 + +If another proxy (for example Traefik) holds ports 80 and 443, it answers every certificate +check there. Caddy cannot get a certificate, and IP certificates are not possible. Caddy then +uses the Let's Encrypt certificate that the proxy already has for your domain. The proxy does +not change, and it keeps renewing the certificate. + +1. Set `serviceOnDemand.nodeHost` to a domain that the proxy has a certificate for (for example + `cp1.oncompute.ai`). +2. Set `serviceOnDemand.letsEncryptAcmePath` to the **host** path of the proxy's `acme.json` (for + example `/home/ubuntu/ocean/letsencrypt/acme.json`). The file must be in Traefik's + `acme.json` format. The node mounts it read-only into Caddy; the node cannot read it itself, + because the file is owned by root with mode 600. + +The node copies the certificate for `nodeHost` into Caddy, and copies it again after a renewal. +In this mode Caddy does not bind port 80. + ## Verifying Connectivity ### Check how your node sees itself diff --git a/docs/services.md b/docs/services.md index ec2b2536f..d08c60a94 100644 --- a/docs/services.md +++ b/docs/services.md @@ -82,12 +82,12 @@ longer use (the bucket was deleted, or it belongs to someone else and bucket sha disabled or the owner was removed from its access list) is refused with `403` before anything is torn down, so the running container is left as it was. -**Restart can change the image — atomically.** A restart is either *all-old* or *all-new*; +**Restart can change the image — atomically.** A restart is either _all-old_ or _all-new_; it never mixes new request params over the stored job: - **REUSE mode** — send no container params and the service restarts on exactly its stored spec (image, `userData`, `dockerCmd`, `dockerEntrypoint`). -- **RESPEC mode** — send *any* container param and the container is rebuilt entirely from the +- **RESPEC mode** — send _any_ container param and the container is rebuilt entirely from the request. `image` is then **required** and exactly one of `tag`/`checksum`/`dockerfile` applies (validated like `serviceStart`); `userData`/`dockerCmd`/`dockerEntrypoint` are taken as-sent, so anything omitted is empty — never inherited from the old job. @@ -221,6 +221,38 @@ instances on other hosts) cannot run conflicting operations on the same service. every 30 s while the operation runs; a lease not refreshed for 2 minutes belongs to a crashed process and is stolen automatically, so no manual cleanup is ever needed. +## HTTPS endpoints (`secureTls`) + +`serviceStart` and `serviceRestart` take an optional `secureTls` list of container ports to +serve over HTTPS: + +```json +"secureTls": [8188, 8189] +``` + +- **HTTP ports only.** The node ends TLS and proxies plain HTTP (websockets and streaming + included) to the container. Leave non-HTTP ports (SSH, Redis, …) out of the list: they are + published plain, and the image must secure them itself. +- **Endpoints.** Each endpoint has `tls: true|false`. A secure port's `url` is + `https://:`; the other ports keep `http://:`. +- **Caddy.** TLS is done by a Caddy container that the node starts and manages (see + [networking.md](networking.md#service-tls-the-caddy-proxy)). The node sends Caddy one server + per secure port over Caddy's admin API: it listens on the host port, serves the certificate + for `nodeHost` and proxies to the container IP on the service network. The service container + publishes only the other ports. The node's service loop sends a changed set at once and an + unchanged one every minute. +- **TLS only, no auth.** The node does not check who calls the port; all headers, including + `Authorization`, go to the container unchanged. Authentication is the image's own job: the + templates gate their ports with their `SERVICE_PASSWORD`. +- **Restart.** Host ports never change. How a restart keeps, replaces or drops the list: + see `serviceRestart` in [API.md](API.md). +- **When it is available.** An environment advertises `features.secureTls: true` in + GET_COMPUTE_ENVIRONMENTS only when it is the node's first local Docker environment + (`socketPath`), its `nodeHost` is a public IP or a domain, and Caddy accepted the node's + last update. Otherwise a request with a non-empty `secureTls` is rejected before any payment. +- **The certificate.** Caddy gets and renews it; see + [networking.md](networking.md#service-tls-the-caddy-proxy). + ## Readiness and startup progress `Running` only means the container started. For workloads it recognizes, the node also reports @@ -335,15 +367,16 @@ first, which keeps them available after the session ends: Service-on-demand is configured per Docker connection under `serviceOnDemand`: -| Field | Meaning | -| --- | --- | -| `enabled` | Master switch for the feature on this connection. | -| `nodeHost` | Externally reachable host used to build endpoint URLs. | -| `hostPortRange` | `[start, end]` range the node allocates published host ports from. | -| `minDurationSeconds` | Hard floor under a service's duration for this daemon (default 0 — no floor). An environment may raise it with its own `minServiceDuration`; a smaller per-env value is clamped up to this one at startup, with a warning. | -| `maxDurationSeconds` | Hard ceiling on a service's lifetime for this daemon (default 86400). An environment may lower it with its own `maxServiceDuration`; a larger per-env value is clamped to this one at startup, with a warning. | -| `allowImageBuild` | If true, consumers may submit an inline `dockerfile` to build. | -| `buildTimeoutSeconds` | Max wall-clock seconds an inline-`dockerfile` build may run before it is aborted. Separate from the service duration and capped at it. Optional; defaults to `300`. An environment may override it per-env with its own `buildTimeoutSeconds`. | +| Field | Meaning | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `enabled` | Master switch for the feature on this connection. | +| `nodeHost` | Externally reachable host used to build endpoint URLs. A public IP or domain is also the name of the node's TLS certificate (see [HTTPS endpoints](#https-endpoints-securetls)). | +| `letsEncryptAcmePath` | Optional. Host path of an `acme.json` (Traefik's format), on nodes where another proxy holds ports 80 and 443: service TLS then uses its certificate for `nodeHost` (see [networking.md](networking.md#nodes-where-a-proxy-already-holds-ports-80-and-443)). | +| `hostPortRange` | `[start, end]` range the node allocates published host ports from. | +| `minDurationSeconds` | Hard floor under a service's duration for this daemon (default 0 — no floor). An environment may raise it with its own `minServiceDuration`; a smaller per-env value is clamped up to this one at startup, with a warning. | +| `maxDurationSeconds` | Hard ceiling on a service's lifetime for this daemon (default 86400). An environment may lower it with its own `maxServiceDuration`; a larger per-env value is clamped to this one at startup, with a warning. | +| `allowImageBuild` | If true, consumers may submit an inline `dockerfile` to build. | +| `buildTimeoutSeconds` | Max wall-clock seconds an inline-`dockerfile` build may run before it is aborted. Separate from the service duration and capped at it. Optional; defaults to `300`. An environment may override it per-env with its own `buildTimeoutSeconds`. | Whether a given environment accepts services is gated by its `features.services` flag, and access can be restricted with the environment's `access` allow-list @@ -459,10 +492,10 @@ huggingface.co on every start, because a service container starts with an empty A node can point every service at a local caching mirror instead, so the second and later starts of the same model are served from the host's disk. Off by default; two env vars: -| Env var | Config field | Meaning | -| --- | --- | --- | -| `SERVICE_HF_MIRROR_URL` | `serviceHfMirrorUrl` | Mirror URL as **service containers** reach it, e.g. `http://172.17.0.1:8092`. When set, every service gets `HF_ENDPOINT=` and `HF_HUB_DISABLE_XET=1`. Must be `http://` or `https://`; anything else is logged and the feature stays off (the node still starts). | -| `SERVICE_HF_CLIENT_PATCH` | `serviceHfClientPatch` | Ship the node's download-client patch into services (see below). Defaults to `true` when a mirror is set, `false` otherwise; `false` turns it off, `true` without a mirror applies the patch alone. | +| Env var | Config field | Meaning | +| ------------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `SERVICE_HF_MIRROR_URL` | `serviceHfMirrorUrl` | Mirror URL as **service containers** reach it, e.g. `http://172.17.0.1:8092`. When set, every service gets `HF_ENDPOINT=` and `HF_HUB_DISABLE_XET=1`. Must be `http://` or `https://`; anything else is logged and the feature stays off (the node still starts). | +| `SERVICE_HF_CLIENT_PATCH` | `serviceHfClientPatch` | Ship the node's download-client patch into services (see below). Defaults to `true` when a mirror is set, `false` otherwise; `false` turns it off, `true` without a mirror applies the patch alone. | Only **service** containers get any of this; compute jobs are unchanged. @@ -645,7 +678,7 @@ then `docker network rm t`. - **⚠️ Low ports won't bind inside the container.** Because `CapDrop: ['ALL']` removes `NET_BIND_SERVICE`, a process **inside** the container cannot bind to a container port below 1024. Have your service listen on a **high port** (the externally published - *host* port is allocated by the node from `hostPortRange` regardless). If a specific + _host_ port is allocated by the node from `hostPortRange` regardless). If a specific image genuinely needs a low in-container port, that requires explicitly adding `CapAdd: ['NET_BIND_SERVICE']` in the engine — it is intentionally not enabled by default. @@ -685,9 +718,9 @@ then `docker network rm t`. that address; results are restricted to services owned by it, so one consumer cannot read another's job records or endpoint URLs. That said, a published service endpoint is still reachable by anyone who learns or guesses its URL — the node only port-forwards - and does not authenticate traffic to the container, so put your own authentication in - front of any sensitive service and do not rely on endpoint-URL secrecy as access - control. + (or, with `secureTls`, adds TLS) and does not authenticate traffic to the container, so + put your own authentication in front of any sensitive service and do not rely on + endpoint-URL secrecy as access control. - **`serviceStreamableLogs` is authenticated and owner-scoped, like `serviceStatus`.** Container stdout/stderr can leak secrets or sensitive request data, so the same diff --git a/src/@types/C2D/C2D.ts b/src/@types/C2D/C2D.ts index b9d3f4fa0..f1a57b754 100644 --- a/src/@types/C2D/C2D.ts +++ b/src/@types/C2D/C2D.ts @@ -8,6 +8,7 @@ import type { ServiceOnDemandConfig } from './ServiceOnDemand.js' export interface ComputeEnvFeatures { computeJobs: boolean // false → COMPUTE_START + FREE_COMPUTE_START rejected services: boolean // false → SERVICE_START rejected; env hidden from service matching + secureTls?: boolean // HTTPS service ports: the node's Caddy holds a cert for nodeHost } export enum C2DClusterType { // eslint-disable-next-line no-unused-vars diff --git a/src/@types/C2D/ServiceOnDemand.ts b/src/@types/C2D/ServiceOnDemand.ts index 66704ca91..c94d0e0d9 100644 --- a/src/@types/C2D/ServiceOnDemand.ts +++ b/src/@types/C2D/ServiceOnDemand.ts @@ -93,6 +93,7 @@ export interface ServiceTemplate { dockerfile?: string // inline Dockerfile content — triggers build; mutually exclusive with tag/checksum additionalDockerFiles?: Record // filename → content; only valid with dockerfile exposedPorts: number[] + secureTls?: number[] // HTTP ports clients should request over HTTPS; a subset of exposedPorts envVars?: Record // fixed env vars — operator-set, never returned to callers userConfigurableEnvVars?: UserConfigurableEnvVar[] command?: string[] // Docker CMD override; ${KEY} expanded from userData @@ -136,6 +137,7 @@ export const DEFAULT_BUILD_TIMEOUT_SECONDS = 300 // 5 min export interface ServiceOnDemandConfig { enabled: boolean nodeHost: string // host (or IP) clients use to reach forwarded service ports; e.g. 'localhost' + letsEncryptAcmePath?: string // host path of an acme.json (Traefik format) with a cert for nodeHost hostPortRange?: [number, number] // e.g. [30000, 32767]; specific to this daemon's host minDurationSeconds?: number // default: DEFAULT_SERVICE_MIN_DURATION_SECONDS (no daemon floor) maxDurationSeconds?: number // default: DEFAULT_SERVICE_MAX_DURATION_SECONDS (24 h) @@ -220,7 +222,8 @@ export interface ServiceLogArchive { export interface ServiceEndpoint { containerPort: number hostPort: number - url: string // e.g. "http://:31042" + url: string // e.g. "http://:31042"; "https://…" when `tls` + tls?: boolean } /* eslint-disable no-unused-vars */ @@ -314,6 +317,7 @@ export interface ServiceJob { // auto (pre-feature shape). Drives host-port reservation at start/restart. requestedHostPorts?: Record endpoints: ServiceEndpoint[] + secureTls?: number[] // container ports served over HTTPS userData?: string // ECIES(node key) string sent by the client; stored as-is, decrypted only at start/restart; never returned // Arbitrary, node-opaque user labels (≤1 KB when JSON-stringified). Set at SERVICE_START, // optionally replaced at SERVICE_RESTART. Returned only to the owner via toPublicServiceJob diff --git a/src/@types/commands.ts b/src/@types/commands.ts index 62f686b08..dbe803d26 100644 --- a/src/@types/commands.ts +++ b/src/@types/commands.ts @@ -485,6 +485,7 @@ export interface ServiceStartCommand extends Command { // Preferred port spec: container→host pairs with optional pinned host port. When present it // supersedes `exposedPorts` (a warning is logged if both are sent). ports?: ServicePortRequest[] + secureTls?: number[] // container ports served over HTTPS resources?: ComputeResourceRequest[] duration: number // seconds; capped by serviceOnDemand.maxDurationSeconds userData?: string // ECIES-encrypted (to the node's public key) JSON object → the container's env-var map @@ -587,6 +588,7 @@ export interface ServiceRestartCommand extends Command { userData?: string // ECIES-encrypted (to the node's public key) JSON → container env-var map dockerCmd?: string[] // exact container command (Docker exec-form CMD override; no shell) dockerEntrypoint?: string[] // container ENTRYPOINT override + secureTls?: number[] // not a container param; replaces the stored list when present // NOT a container param — independent of the REUSE/RESPEC discriminator above and never // triggers RESPEC mode. When present it REPLACES the stored metadata; when omitted the // original metadata is kept untouched. diff --git a/src/components/c2d/caddyProxy.ts b/src/components/c2d/caddyProxy.ts new file mode 100644 index 000000000..6f8389a3f --- /dev/null +++ b/src/components/c2d/caddyProxy.ts @@ -0,0 +1,361 @@ +import type Dockerode from 'dockerode' +import { X509Certificate } from 'crypto' +import net from 'net' +import { PassThrough } from 'stream' +import { setTimeout as sleep } from 'timers/promises' +import { + DEFAULT_SERVICE_MAX_DURATION_SECONDS, + ServiceStatusNumber, + type ServiceEndpoint, + type ServiceJob, + type ServiceOnDemandConfig +} from '../../@types/C2D/ServiceOnDemand.js' +import { create256Hash } from '../../utils/crypt.js' +import { CORE_LOGGER } from '../../utils/logging/common.js' +import { urlHost } from './serviceTls.js' + +export const CADDY_IMAGE = 'caddy:2.11.9-alpine' +// One per Docker host: Caddy binds the host's port 80 and admin port 2019 +export const CADDY_CONTAINER = 'ocean-node-caddy' +export const CADDY_ACME_JSON = '/letsencrypt/acme.json' +const CADDY_DATA_VOLUME = 'ocean-node-caddy-data' +const CADDY_CERT_DIR = '/data/ocean' +const CADDY_CERT_STORAGE = '/data/caddy/certificates' +// Docker can rewrite bind paths in inspect output, so the mounted file is compared by label +const ACME_LABEL = 'ocean-node.letsencrypt-acme-path' +const OWNER_LABEL = 'ocean-node.owner' +const ENSURE_TIMEOUT_MS = 120_000 // includes the image pull +const EXEC_TIMEOUT_MS = 10_000 +const EXEC_EXIT_POLL_MS = 100 +const EXEC_EXIT_POLLS = 20 +const RESEND_MS = 60_000 // a restarted Caddy has no config until the next load +const CERT_WAIT_RESEND_MS = 5_000 +const LOG_KEY = 'service-tls-sync' +const LOG_INTERVAL_MS = 600_000 +const CERT_FILE_HASH_CHARS = 16 +// Admin API on the host's loopback (Caddy's default): service containers cannot reach it +export const CADDY_LOAD_CMD = [ + 'wget', + '-qO-', + '--header', + 'Content-Type: application/json', + '--post-file=/dev/stdin', + 'http://127.0.0.1:2019/load' +] + +function withTimeout(promise: Promise, ms: number, what: string): Promise { + let timer: NodeJS.Timeout + const timeout = new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error(`${what}: timed out`)), ms) + }) + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)) +} + +async function inspectOrNull(target: { inspect(): Promise }): Promise { + try { + return await target.inspect() + } catch (e) { + if (e?.statusCode === 404) return null + throw e + } +} + +async function ownCaddy(docker: Dockerode, owner: string) { + const container = docker.getContainer(CADDY_CONTAINER) + const info = await inspectOrNull(container) + const current = info?.Config?.Labels?.[OWNER_LABEL] + if (info && current !== owner) + throw new Error( + `${CADDY_CONTAINER} belongs to another node (${current ?? 'unknown'})` + ) + return { container, info } +} + +async function createCaddy( + docker: Dockerode, + owner: string, + acmePath?: string +): Promise { + if (!(await inspectOrNull(docker.getImage(CADDY_IMAGE)))) { + const stream = await docker.pull(CADDY_IMAGE) + await new Promise((resolve, reject) => + docker.modem.followProgress(stream, (err: Error) => + err ? reject(err) : resolve(null) + ) + ) + } + const binds = [`${CADDY_DATA_VOLUME}:/data`] + if (acmePath) binds.push(`${acmePath}:${CADDY_ACME_JSON}:ro`) + const container = await docker.createContainer({ + name: CADDY_CONTAINER, + Image: CADDY_IMAGE, + Cmd: ['caddy', 'run'], + Labels: { [ACME_LABEL]: acmePath ?? '', [OWNER_LABEL]: owner }, + // host network: Caddy listens on the services' random host ports + HostConfig: { NetworkMode: 'host', RestartPolicy: { Name: 'always' }, Binds: binds } + }) + await container.start() + return container +} + +export function ensureCaddy( + docker: Dockerode, + owner: string, + acmePath?: string +): Promise { + const ensure = async () => { + const { container, info } = await ownCaddy(docker, owner) + if ( + info?.Config?.Image === CADDY_IMAGE && + info.Config.Labels?.[ACME_LABEL] === (acmePath ?? '') + ) { + if (!info.State?.Running) await container.start() + return container + } + if (info) await container.remove({ force: true }) + return createCaddy(docker, owner, acmePath) + } + return withTimeout(ensure(), ENSURE_TIMEOUT_MS, `start ${CADDY_CONTAINER}`) +} + +export async function removeCaddy(docker: Dockerode, owner: string): Promise { + const { container, info } = await ownCaddy(docker, owner) + if (info) await container.remove({ force: true }) +} + +// `input` goes on stdin and never into an error: it can hold a private key +export async function caddyExec( + container: Dockerode.Container, + Cmd: string[], + input = '' +): Promise { + const exec = await container.exec({ + Cmd, + AttachStdin: true, + AttachStdout: true, + AttachStderr: true + }) + const stream = await exec.start({ hijack: true, stdin: true }) + const out = new PassThrough() + const chunks: Buffer[] = [] + out.on('data', (c: Buffer) => chunks.push(c)) + container.modem.demuxStream(stream, out, out) + const ended = new Promise((resolve, reject) => { + stream.on('end', resolve) + stream.on('close', resolve) + stream.on('error', reject) + }) + stream.end(input) + await withTimeout(ended, EXEC_TIMEOUT_MS, `caddy exec ${Cmd[0]}`).finally(() => + stream.destroy() + ) + // Docker can report the exec as running for a moment after its stream ends + let info = await exec.inspect() + for (let i = 0; info.Running && i < EXEC_EXIT_POLLS; i++) { + await sleep(EXEC_EXIT_POLL_MS) + info = await exec.inspect() + } + const output = Buffer.concat(chunks).toString() + if (info.ExitCode !== 0) + throw new Error( + `caddy exec ${Cmd[0]} exited ${info.ExitCode}: ${output.trim().slice(0, 200)}` + ) + return output +} + +export interface CaddyTlsService { + serviceId: string + upstreamIp: string + endpoints: ServiceEndpoint[] +} + +// The host matcher makes Caddy get the cert; default_sni serves it to IP clients (no SNI). +// storeCert: another proxy holds port 80, so no redirect server there. +export function buildCaddyServers( + nodeHost: string, + services: CaddyTlsService[], + { storeCert = false, maxDurationSeconds = DEFAULT_SERVICE_MAX_DURATION_SECONDS } = {} +): Record { + const servers: Record = {} + for (const svc of services) { + for (const { containerPort, hostPort } of svc.endpoints.filter((e) => e.tls)) { + const proxy = { + handler: 'reverse_proxy', + upstreams: [{ dial: `${urlHost(svc.upstreamIp)}:${containerPort}` }], + flush_interval: -1, + // without it, a config reload closes open websockets + stream_close_delay: `${maxDurationSeconds}s` + } + servers[`ocean_${svc.serviceId}_${containerPort}`] = { + listen: [`:${hostPort}`], + tls_connection_policies: [{ default_sni: nodeHost }], + routes: [{ match: [{ host: [nodeHost] }], handle: [proxy] }], + ...(storeCert && { automatic_https: { disable_redirects: true } }) + } + } + } + return servers +} + +// Without certFile Caddy gets the cert itself, before any service needs it (automate); +// the shortlived profile is required for IP certificates. +export function buildCaddyConfig( + servers: Record, + nodeHost: string, + certFile?: string +) { + const tls = certFile + ? { certificates: { load_files: [{ certificate: certFile, key: certFile }] } } + : { + certificates: { automate: [nodeHost] }, + automation: { + policies: [{ issuers: [{ module: 'acme', profile: 'shortlived' }] }] + } + } + return { apps: { tls, http: { servers } } } +} + +interface AcmeJsonCert { + certificate: string // base64 PEM chain, leaf first + key: string // base64 PEM +} + +function covers(chainPem: string, name: string): boolean { + const leaf = new X509Certificate(chainPem) + return !!(net.isIP(name) ? leaf.checkIP(name) : leaf.checkHost(name)) +} + +// Traefik's acme.json: { : { Certificates: AcmeJsonCert[] } }. Returns chain + key +// of a cert valid for `name` (wildcards included). +export function findStoreCert(acmeJson: string, name: string): string | null { + const store = JSON.parse(acmeJson) as Record + for (const resolver of Object.values(store)) { + for (const cert of resolver?.Certificates ?? []) { + const [chain, key] = [cert.certificate, cert.key].map((b64) => + Buffer.from(b64, 'base64').toString().trim() + ) + if (covers(chain, name)) return `${chain}\n${key}` + } + } + return null +} + +const defaultIo = { ensure: ensureCaddy, exec: caddyExec, remove: removeCaddy } + +// Keeps the node's Caddy container in line with the running TLS services +export class CaddyProxy { + certReady = false // Caddy holds a cert for nodeHost: features.secureTls + private lastLoad: { json: string; at: number } | null = null + private removed = false + private upstreamIps = new Map() // containerId -> IP on ocean-svc- + + constructor( + private readonly docker: Dockerode, + private readonly owner: string, + private readonly io = defaultIo + ) {} + + // nodeHost null: TLS is off, so Caddy goes. Resolves true when Caddy holds no stale ports. + async sync( + nodeHost: string | null, + runningJobs: () => Promise, + sod?: ServiceOnDemandConfig + ): Promise { + try { + if (nodeHost) await this.load(nodeHost, await runningJobs(), sod) + else await this.remove() + CORE_LOGGER.resetThrottle(LOG_KEY) + return true + } catch (e: any) { + this.certReady = false + CORE_LOGGER.throttled( + LOG_KEY, + 'error', + `Service TLS: Caddy sync failed: ${e.message}`, + LOG_INTERVAL_MS + ) + return false + } + } + + private async remove() { + if (this.removed) return + await this.io.remove(this.docker, this.owner) + this.removed = true + this.lastLoad = null + this.certReady = false + } + + private async load(nodeHost: string, jobs: ServiceJob[], sod?: ServiceOnDemandConfig) { + const acmePath = sod?.letsEncryptAcmePath + const servers = buildCaddyServers(nodeHost, await this.tlsServices(jobs), { + storeCert: !!acmePath, + maxDurationSeconds: sod?.maxDurationSeconds + }) + const json = JSON.stringify(servers) + const resendMs = this.certReady ? RESEND_MS : CERT_WAIT_RESEND_MS + if (this.lastLoad?.json === json && Date.now() - this.lastLoad.at < resendMs) return + const caddy = await this.io.ensure(this.docker, this.owner, acmePath) + const certFile = acmePath ? await this.copyStoreCert(caddy, nodeHost) : undefined + const config = buildCaddyConfig(servers, nodeHost, certFile) + await this.io.exec(caddy, CADDY_LOAD_CMD, JSON.stringify(config)) + this.lastLoad = { json, at: Date.now() } + this.removed = false + this.certReady = !!certFile || (await this.hasCert(caddy, nodeHost)) + } + + // The file name follows the cert, so a renewal changes the config and Caddy reloads it + private async copyStoreCert(caddy: Dockerode.Container, nodeHost: string) { + const pem = findStoreCert( + await this.io.exec(caddy, ['cat', CADDY_ACME_JSON]), + nodeHost + ) + if (!pem) throw new Error(`letsEncryptAcmePath has no certificate for ${nodeHost}`) + const file = `${CADDY_CERT_DIR}/${create256Hash(pem).slice(2, 2 + CERT_FILE_HASH_CHARS)}.pem` + const write = `umask 077 && mkdir -p ${CADDY_CERT_DIR} && rm -f ${CADDY_CERT_DIR}/*.pem && cat > ${file}` + await this.io.exec(caddy, ['sh', '-c', write], pem) + return file + } + + // Caddy stores certificates///.crt, with ':' as '-' + private hasCert(caddy: Dockerode.Container, nodeHost: string): Promise { + const name = nodeHost.toLowerCase().replaceAll(':', '-') + const ls = `ls ${CADDY_CERT_STORAGE}/*/"$1"/"$1".crt` + return this.io.exec(caddy, ['sh', '-c', ls, '--', name]).then( + () => true, + () => false + ) + } + + private async tlsServices(jobs: ServiceJob[]): Promise { + const secure = jobs.filter( + (j) => j.status === ServiceStatusNumber.Running && j.secureTls?.length + ) + const live = new Set(secure.map((j) => j.containerId)) + for (const id of this.upstreamIps.keys()) + if (!live.has(id)) this.upstreamIps.delete(id) + const services = await Promise.all(secure.map((j) => this.tlsService(j))) + return services.filter((s) => s) + } + + private async tlsService(job: ServiceJob): Promise { + let upstreamIp = this.upstreamIps.get(job.containerId) + if (!upstreamIp) { + try { + const info = await this.docker.getContainer(job.containerId).inspect() + upstreamIp = + info.NetworkSettings?.Networks?.[`ocean-svc-${job.serviceId}`]?.IPAddress + if (!upstreamIp) throw new Error('container has no IP on its service network') + this.upstreamIps.set(job.containerId, upstreamIp) + } catch (e: any) { + CORE_LOGGER.throttled( + `service-tls-skip-${job.serviceId}`, + 'warn', + `Service TLS: skipping service ${job.serviceId}: ${e.message}` + ) + return null + } + } + return { serviceId: job.serviceId, upstreamIp, endpoints: job.endpoints } + } +} diff --git a/src/components/c2d/compute_engine_base.ts b/src/components/c2d/compute_engine_base.ts index 893a2a45c..607c320e4 100644 --- a/src/components/c2d/compute_engine_base.ts +++ b/src/components/c2d/compute_engine_base.ts @@ -154,7 +154,8 @@ export abstract class C2DEngine { userData?: string, // ECIES-encrypted; the engine decrypts it transiently into the container env metadata?: DBComputeJobMetadata, outputBucketId?: string, - requestedHostPorts?: Record // pinned host ports keyed by containerPort + requestedHostPorts?: Record, // pinned host ports keyed by containerPort + secureTls?: number[] ): Promise { return null } @@ -183,6 +184,11 @@ export abstract class C2DEngine { return await fn() } + // Whether this engine's config allows TLS service ports (C2DEngineDocker overrides) + public serviceTlsConfigured(): boolean { + return false + } + // Restart is atomic: when an image spec is supplied (RESPEC mode) the whole container is // rebuilt from these params; when it is absent (REUSE mode) the stored spec is reused. // eslint-disable-next-line require-await @@ -199,7 +205,8 @@ export abstract class C2DEngine { newDockerEntrypoint?: string[], newMetadata?: DBComputeJobMetadata, newExposedPorts?: number[], // present ⇒ change ports; undefined ⇒ keep current - newRequestedHostPorts?: Record // pinned host ports keyed by containerPort + newRequestedHostPorts?: Record, // pinned host ports keyed by containerPort + newSecureTls?: number[] ): Promise { return null } diff --git a/src/components/c2d/compute_engine_docker.ts b/src/components/c2d/compute_engine_docker.ts index e249c3f94..808c59b7a 100755 --- a/src/components/c2d/compute_engine_docker.ts +++ b/src/components/c2d/compute_engine_docker.ts @@ -2,6 +2,7 @@ import { Readable, PassThrough } from 'stream' import path from 'path' import { + C2DClusterType, C2DStatusNumber, C2DStatusText, DBComputeJobMetadata @@ -93,8 +94,8 @@ import { DEFAULT_BUILD_TIMEOUT_SECONDS } from '../../@types/C2D/ServiceOnDemand.js' import type { - ServiceJob, ServiceEndpoint, + ServiceJob, ServiceImagePullProgress, ServiceModelDownload, ServiceReadiness @@ -108,6 +109,8 @@ import { READY_PROBE_PERIOD_SECONDS, READINESS_WARN_AFTER_SECONDS } from './serviceReadiness.js' +import { buildServiceEndpoints, tlsNameFor } from './serviceTls.js' +import { CaddyProxy } from './caddyProxy.js' import { resolveServiceEngine, type ServiceEngineProfile } from './serviceEngines.js' import { buildModelDownload, @@ -224,6 +227,18 @@ const logDockerCleanupError = (e: any, msg: string) => // which a multi-process (one-worker-per-GPU) model server needs. const SERVICE_DEFAULT_PIDS_LIMIT = 512 +// A TLS port's host port belongs to Caddy, so the container does not publish it +function servicePortBindings(endpoints: ServiceEndpoint[]) { + const PortBindings: Record> = {} + const ExposedPorts: Record> = {} + for (const ep of endpoints) { + ExposedPorts[`${ep.containerPort}/tcp`] = {} + if (!ep.tls) + PortBindings[`${ep.containerPort}/tcp`] = [{ HostPort: String(ep.hostPort) }] + } + return { PortBindings, ExposedPorts } +} + export class C2DEngineDocker extends C2DEngine { private envs: ComputeEnvironment[] = [] @@ -305,6 +320,9 @@ export class C2DEngineDocker extends C2DEngine { // calls — so stop() can drain them before returning. Otherwise an op could outlive // stop() and race a restarted engine on the same shared DB. private serviceOpPromises: Set> = new Set() + private caddy: CaddyProxy | null = null // only on the TLS engine + private tlsSync: Promise = Promise.resolve(true) + private tlsSyncQueued = false private imageCleanupTimer: NodeJS.Timeout | null = null private paymentClaimTimer: NodeJS.Timeout | null = null private scanDBUpdateTimer: NodeJS.Timeout | null = null @@ -330,7 +348,6 @@ export class C2DEngineDocker extends C2DEngine { config: OceanNodeConfig ) { super(clusterConfig, db, escrow, keyManager, config) - this.docker = null if (clusterConfig.connection.socketPath) { try { @@ -341,6 +358,13 @@ export class C2DEngineDocker extends C2DEngine { ) } } + if (this.docker && this.isTlsEngine()) { + this.caddy = new CaddyProxy(this.docker, keyManager.getEthAddress()) + if (clusterConfig.connection.serviceOnDemand && !this.tlsNodeHost()) + CORE_LOGGER.info( + "Service TLS off: set serviceOnDemand.nodeHost to the node's public IP or domain" + ) + } this.retentionDays = clusterConfig.connection.imageRetentionDays || 7 this.cleanupInterval = clusterConfig.connection.imageCleanupInterval this.paymentClaimInterval = clusterConfig.connection.paymentClaimInterval || 3600 // 1 hour @@ -963,6 +987,8 @@ export class C2DEngineDocker extends C2DEngine { await Promise.allSettled([...this.serviceProbesInFlight.values()]) this.serviceProbesInFlight.clear() } + // A late Caddy load must not overwrite the next engine's config + await this.tlsSync this.isInternalLoopRunning = false // Release any GPU metrics backends (e.g. nvmlShutdown). Best-effort, never throws; the // optional chain also covers engines built without the constructor (e.g. test doubles). @@ -1416,10 +1442,12 @@ export class C2DEngineDocker extends C2DEngine { // rather than overwriting it with a partial sum. let queuedTotal = 0 let queuedFreeTotal = 0 + const secureTls = !!this.caddy?.certReady // const systemInfo = this.docker ? await this.docker.info() : null for (const env of this.envs) { if (!chainId || (env.fees && Object.hasOwn(env.fees, String(chainId)))) { const computeEnv = JSON.parse(JSON.stringify(env)) + computeEnv.features = { ...computeEnv.features, secureTls } // TO DO - At some point in time we need to handle multiple runtimes // console.log('********************************') @@ -2394,6 +2422,11 @@ export class C2DEngineDocker extends C2DEngine { ) ) } + // Not awaited: a first sync can pull the Caddy image; at most one loop sync in flight + if (!this.tlsSyncQueued) { + this.tlsSyncQueued = true + this.syncServiceTls().finally(() => (this.tlsSyncQueued = false)) + } CORE_LOGGER.resetThrottle(`c2d-internal-loop-${this.getC2DConfig().hash}`) } catch (e) { // runs every tick: log the first failure, then at most once per interval @@ -4850,7 +4883,8 @@ export class C2DEngineDocker extends C2DEngine { userData?: string, metadata?: DBComputeJobMetadata, outputBucketId?: string, - requestedHostPorts?: Record + requestedHostPorts?: Record, + secureTls?: number[] ): Promise { validateJobMetadataSize(metadata) const containerImage = resolveServiceImage( @@ -4883,6 +4917,7 @@ export class C2DEngineDocker extends C2DEngine { exposedPorts, ...(requestedHostPorts ? { requestedHostPorts } : {}), endpoints: [], + secureTls, userData, // stored as received (ECIES-encrypted); decrypted transiently at container start metadata, outputBucketId, @@ -5187,12 +5222,12 @@ export class C2DEngineDocker extends C2DEngine { throw e } - const nodeHost = sod?.nodeHost ?? 'localhost' - job.endpoints = job.exposedPorts.map((cp, i) => ({ - containerPort: cp, - hostPort: hostPorts[i], - url: `http://${nodeHost}:${hostPorts[i]}` - })) + job.endpoints = buildServiceEndpoints( + job.exposedPorts, + hostPorts, + sod?.nodeHost ?? 'localhost', + job.secureTls + ) // Ports are now tracked via job.endpoints; the pre-lock pinned reservations are subsumed // (a later failure follows the claimTx-based keep/release logic in the catch below). reservedPinned.length = 0 @@ -5210,12 +5245,7 @@ export class C2DEngineDocker extends C2DEngine { const cmd = job.dockerCmd?.length ? job.dockerCmd : undefined const entrypoint = job.dockerEntrypoint?.length ? job.dockerEntrypoint : undefined - const PortBindings: Record> = {} - const ExposedPorts: Record> = {} - job.exposedPorts.forEach((cp, i) => { - PortBindings[`${cp}/tcp`] = [{ HostPort: String(hostPorts[i]) }] - ExposedPorts[`${cp}/tcp`] = {} - }) + const { PortBindings, ExposedPorts } = servicePortBindings(job.endpoints) const { Memory, @@ -5380,6 +5410,57 @@ export class C2DEngineDocker extends C2DEngine { await this.removeServiceNetwork(serviceId, network?.id).catch(() => {}) } + private isTlsEngine(): boolean { + const cluster = this.getC2DConfig() + if (!cluster?.connection?.socketPath) return false + const first = this.getConfig()?.c2dClusters?.find( + (c) => c.type === C2DClusterType.DOCKER && c.connection?.socketPath + ) + return first?.hash === cluster.hash + } + + // Only the first local engine: Caddy runs on its host and dials container IPs + private tlsNodeHost(): string | null { + if (!this.caddy) return null + return tlsNameFor(this.getC2DConfig().connection.serviceOnDemand?.nodeHost) + } + + // Config, not Caddy's state: a short Caddy failure must not drop a stored list + public override serviceTlsConfigured(): boolean { + return !!this.tlsNodeHost() + } + + // Chained: a restart's sync must run after a loop sync that read older state. Reads the DB, + // not the loop's list, which skips services with an op in flight (an extend keeps TLS). + private syncServiceTls(): Promise { + const { caddy } = this + if (!caddy) return Promise.resolve(true) + const cluster = this.getC2DConfig() + this.tlsSync = this.tlsSync + .then(() => + caddy.sync( + this.tlsNodeHost(), + () => this.db.getRunningServiceJobs(cluster.hash), + cluster.connection.serviceOnDemand + ) + ) + .catch((e) => { + CORE_LOGGER.throttled( + `service-tls-sync-${cluster.hash}`, + 'error', + `Service TLS: sync failed: ${e.message}` + ) + return false + }) + return this.tlsSync + } + + // Caddy must let go of TLS host ports (except `stillTls`) before anything else publishes them + private freeTlsPorts(endpoints: ServiceEndpoint[], stillTls: number[] = []) { + const leaving = endpoints.some((ep) => ep.tls && !stillTls.includes(ep.containerPort)) + return leaving ? this.syncServiceTls() : Promise.resolve(true) + } + // Removes a service's Docker network by BOTH the persisted id (when set) and the // deterministic name `ocean-svc-`: job.networkId is only persisted after the // container starts, so a node crash mid-start leaves networkId='' in the DB while the @@ -6394,6 +6475,8 @@ export class C2DEngineDocker extends C2DEngine { // Only expiry ends the reservation; disk-stopped services remain reserved until now. const [stoppedJob] = await this.db.getServiceJob(svc.serviceId, svc.owner) if (stoppedJob) { + // Not Expired until Caddy frees the TLS ports: the next tick retries + if (!(await this.freeTlsPorts(stoppedJob.endpoints ?? []))) return delete stoppedJob.terminationReason stoppedJob.status = finalStatus stoppedJob.statusText = ServiceStatusText[finalStatus] @@ -6559,7 +6642,8 @@ export class C2DEngineDocker extends C2DEngine { newDockerEntrypoint?: string[], newMetadata?: DBComputeJobMetadata, newExposedPorts?: number[], - newRequestedHostPorts?: Record + newRequestedHostPorts?: Record, + newSecureTls?: number[] ): Promise { // Metadata is independent of the container-param REUSE/RESPEC grouping: validate it up // front so a bad request is rejected before any teardown. Applied to the job below. @@ -6705,10 +6789,12 @@ export class C2DEngineDocker extends C2DEngine { assignedHost.add(hp) resolvedHost.set(cp, hp) } - const newEndpoints: ServiceEndpoint[] = newExposedPorts.map((cp) => { - const hp = resolvedHost.get(cp) as number - return { containerPort: cp, hostPort: hp, url: `http://${nodeHost}:${hp}` } - }) + const newEndpoints = buildServiceEndpoints( + newExposedPorts, + newExposedPorts.map((cp) => resolvedHost.get(cp) as number), + nodeHost, + newSecureTls ?? job.secureTls + ) portChangeOldEndpoints = job.endpoints job.exposedPorts = newExposedPorts if (newRequestedHostPorts && Object.keys(newRequestedHostPorts).length) @@ -6726,6 +6812,7 @@ export class C2DEngineDocker extends C2DEngine { // Replace the stored metadata only when the request carries a new bag; otherwise the // original labels are kept untouched (independent of the container-param REUSE/RESPEC). if (newMetadata !== undefined) job.metadata = newMetadata + if (newSecureTls !== undefined) job.secureTls = newSecureTls await this.db.updateServiceJob(job) } catch (e) { // Release any host ports newly reserved for a port change that was never handed to the @@ -6894,12 +6981,16 @@ export class C2DEngineDocker extends C2DEngine { // field initializers, which is how the unit tests construct one.) this.serviceProbeUrls?.delete(serviceId) await this.db.updateServiceJob(job) - // Live Docker handles for the newly-created container/network, tracked so the // catch block can tear them down on failure (otherwise the network leaks). let network: Dockerode.Network | null = null let container: Dockerode.Container | null = null try { + const tlsFreed = oldEndpoints + ? await this.freeTlsPorts(oldEndpoints) + : await this.freeTlsPorts(job.endpoints, job.secureTls) + if (!tlsFreed) + throw new Error('Caddy did not release the TLS ports; try again later') const sod = this.getC2DConfig().connection?.serviceOnDemand // Atomic restart. An image spec on the request (RESPEC mode) rebuilds the whole @@ -6970,13 +7061,14 @@ export class C2DEngineDocker extends C2DEngine { const cmd = effDockerCmd?.length ? effDockerCmd : undefined const entrypoint = effDockerEntrypoint?.length ? effDockerEntrypoint : undefined - // 5. Rebuild port bindings — reuse already-allocated host ports - const PortBindings: Record> = {} - const ExposedPorts: Record> = {} - job.endpoints.forEach((ep) => { - PortBindings[`${ep.containerPort}/tcp`] = [{ HostPort: String(ep.hostPort) }] - ExposedPorts[`${ep.containerPort}/tcp`] = {} - }) + // 5. Rebuild endpoints + port bindings — same host ports + job.endpoints = buildServiceEndpoints( + job.endpoints.map((ep) => ep.containerPort), + job.endpoints.map((ep) => ep.hostPort), + sod?.nodeHost ?? 'localhost', + job.secureTls + ) + const { PortBindings, ExposedPorts } = servicePortBindings(job.endpoints) // 6. New per-service network network = await this.createServiceNetwork(serviceId) diff --git a/src/components/c2d/serviceReadiness.ts b/src/components/c2d/serviceReadiness.ts index 304fcc448..2f476c84b 100644 --- a/src/components/c2d/serviceReadiness.ts +++ b/src/components/c2d/serviceReadiness.ts @@ -2,6 +2,7 @@ import type { ServiceImagePullProgress, ServiceJob } from '../../@types/C2D/ServiceOnDemand.js' +import { urlHost } from './serviceTls.js' // How often the aggregated byte counts are pushed to the caller const PULL_PROGRESS_EMIT_INTERVAL_MS = 1000 @@ -122,12 +123,13 @@ export function probeCandidates( const urls: string[] = [] for (const ip of containerIps) { if (ip) { - // Docker reports IPv4 here today; an IPv6 literal would need brackets to form a URL. - const host = ip.includes(':') ? `[${ip}]` : ip - urls.push(`http://${host}:${containerPort}${path}`) + urls.push(`http://${urlHost(ip)}:${containerPort}${path}`) } } - if (hostPort) { + // Caddy speaks only https, with a cert for nodeHost: only the public URL can work + if (endpoint?.tls) { + urls.push(`${endpoint.url}${path}`) + } else if (hostPort) { urls.push(`http://127.0.0.1:${hostPort}${path}`) // Docker Desktop always, and Linux compose when the node declares `host-gateway`. urls.push(`http://host.docker.internal:${hostPort}${path}`) diff --git a/src/components/c2d/serviceTls.ts b/src/components/c2d/serviceTls.ts new file mode 100644 index 000000000..a8f5d0b7b --- /dev/null +++ b/src/components/c2d/serviceTls.ts @@ -0,0 +1,60 @@ +import net from 'net' +import type { ServiceEndpoint } from '../../@types/C2D/ServiceOnDemand.js' +import { isBlockedAddress, isLocalHostname } from '../../utils/safeUrl.js' + +export const SECURE_TLS_UNAVAILABLE_MESSAGE = + 'TLS is not available on this environment: no public nodeHost, no certificate yet, ' + + 'or a remote Docker daemon' + +// null when valid; [] is valid (turns TLS off on restart) +export function validateSecureTls(value: unknown, exposedPorts: number[]): string | null { + if (value === undefined) return null + if (!Array.isArray(exposedPorts) || !exposedPorts.every(Number.isInteger)) + return 'exposed ports must be an array of integers' + if (!Array.isArray(value)) return '"secureTls" must be an array of container ports' + if (new Set(value).size !== value.length) + return '"secureTls" lists a port more than once' + const bad = value.findIndex((port) => !exposedPorts.includes(port)) + if (bad !== -1) + return `"secureTls" port ${String(value[bad])} is not one of the exposed ports` + return null +} + +export function urlHost(host: string): string { + return net.isIP(host) === 6 ? `[${host}]` : host +} + +export function buildServiceEndpoints( + exposedPorts: number[], + hostPorts: number[], + nodeHost: string, + secureTls?: number[] +): ServiceEndpoint[] { + return exposedPorts.map((containerPort, i) => { + const tls = !!secureTls?.includes(containerPort) + return { + containerPort, + hostPort: hostPorts[i], + url: `${tls ? 'https' : 'http'}://${urlHost(nodeHost)}:${hostPorts[i]}`, + tls + } + }) +} + +// Names that only resolve on a private network: a public CA does not issue for them +const PRIVATE_NAME_SUFFIXES = [ + '.local', + '.internal', + '.lan', + '.home.arpa', + '.localdomain' +] + +// A public IP or a dotted, non-local domain: the names a public CA issues for +export function tlsNameFor(nodeHost?: string): string | null { + if (!nodeHost) return null + if (net.isIP(nodeHost)) return isBlockedAddress(nodeHost) ? null : nodeHost + const name = nodeHost.toLowerCase() + if (!name.includes('.') || isLocalHostname(name)) return null + return PRIVATE_NAME_SUFFIXES.some((s) => name.endsWith(s)) ? null : nodeHost +} diff --git a/src/components/core/service/restartService.ts b/src/components/core/service/restartService.ts index c21bc8de8..275279972 100644 --- a/src/components/core/service/restartService.ts +++ b/src/components/core/service/restartService.ts @@ -21,6 +21,10 @@ import { normalizePortSpec, HostPortUnavailableError } from './utils.js' +import { + validateSecureTls, + SECURE_TLS_UNAVAILABLE_MESSAGE +} from '../../c2d/serviceTls.js' import { PersistentStorageAccessDeniedError } from '../../persistentStorage/PersistentStorageFactory.js' import { restartSubsidyDropped, @@ -151,6 +155,27 @@ export class ServiceRestartHandler extends CommandHandler { if (!accessGranted) return { stream: null, status: { httpStatus: 403, error: 'Access denied' } } + // Port change is independent of REUSE/RESPEC: `ports` present ⇒ change ports, omitted ⇒ + // keep the current ones. Only `ports` is honoured (not the legacy `exposedPorts`), so a + // client echoing a start body into a restart does not accidentally change ports. + const normalizedPorts = + task.ports !== undefined ? normalizePortSpec(task.ports, undefined) : undefined + const tlsError = validateSecureTls( + task.secureTls, + normalizedPorts?.exposedPorts ?? job.exposedPorts + ) + if (tlsError) + return buildInvalidParametersResponse(buildInvalidRequestMessage(tlsError)) + if (task.secureTls?.length && !runEnv.features?.secureTls) + return buildInvalidParametersResponse( + buildInvalidRequestMessage(SECURE_TLS_UNAVAILABLE_MESSAGE) + ) + // A node whose config no longer allows TLS restarts an omitted list plain (no 400 loop) + const dropTls = + task.secureTls === undefined && + !!job.secureTls?.length && + !engine.serviceTlsConfigured() + // State check — cannot restart an expired service if (job.status === ServiceStatusNumber.Expired) return buildInvalidParametersResponse( @@ -223,17 +248,16 @@ export class ServiceRestartHandler extends CommandHandler { } } + if (dropTls) + CORE_LOGGER.info( + `service ${task.serviceId}: TLS no longer available, restarting without it` + ) try { // Asynchronous, like SERVICE_START: engine.restartService validates, persists the // job as Restarting and returns immediately — the teardown + image pull/build + // new container run in the background (an image pull can take minutes and must // not block the HTTP/P2P response). Clients poll SERVICE_GET_STATUS and watch // Restarting → … → Running (or an Error status with the failure reason). - // Port change is independent of REUSE/RESPEC: `ports` present ⇒ change ports, omitted ⇒ - // keep the current ones. Only `ports` is honoured (not the legacy `exposedPorts`), so a - // client echoing a start body into a restart does not accidentally change ports. - const normalizedPorts = - task.ports !== undefined ? normalizePortSpec(task.ports, undefined) : undefined const restarted = await engine.restartService( task.serviceId, task.consumerAddress, @@ -247,7 +271,8 @@ export class ServiceRestartHandler extends CommandHandler { task.dockerEntrypoint, task.metadata, normalizedPorts?.exposedPorts, - normalizedPorts?.requestedHostPorts + normalizedPorts?.requestedHostPorts, + dropTls ? [] : task.secureTls ) CORE_LOGGER.info(`Service ${task.serviceId} restarted by ${task.consumerAddress}`) return { diff --git a/src/components/core/service/startService.ts b/src/components/core/service/startService.ts index b24552942..0a95ba1f6 100644 --- a/src/components/core/service/startService.ts +++ b/src/components/core/service/startService.ts @@ -33,6 +33,10 @@ import { resolveUserSubsidyProviders } from '../utils/subsidyProviders.js' import { maintenanceGuard } from '../utils/maintenance.js' +import { + validateSecureTls, + SECURE_TLS_UNAVAILABLE_MESSAGE +} from '../../c2d/serviceTls.js' export class ServiceStartHandler extends CommandHandler { validate(command: ServiceStartCommand): ValidateParams { @@ -130,6 +134,11 @@ export class ServiceStartHandler extends CommandHandler { } } + if (task.secureTls?.length && !env.features?.secureTls) + return buildInvalidParametersResponse( + buildInvalidRequestMessage(SECURE_TLS_UNAVAILABLE_MESSAGE) + ) + // 1b. Access-list gate (mirrors paid compute → 403). The signature only proves // control of consumerAddress, not allowlist membership, so this must be // enforced here before any escrow/charge logic. @@ -228,6 +237,9 @@ export class ServiceStartHandler extends CommandHandler { task.ports, task.exposedPorts ) + const tlsError = validateSecureTls(task.secureTls, normExposedPorts) + if (tlsError) + return buildInvalidParametersResponse(buildInvalidRequestMessage(tlsError)) if (requestedHostPorts) { const range = engine.getC2DConfig().connection?.serviceOnDemand ?.hostPortRange ?? [30000, 32767] @@ -381,7 +393,8 @@ export class ServiceStartHandler extends CommandHandler { task.userData, task.metadata, task.outputBucketId, - requestedHostPorts + requestedHostPorts, + task.secureTls ) CORE_LOGGER.info( diff --git a/src/components/httpRoutes/compute.ts b/src/components/httpRoutes/compute.ts index c763878ed..089e2f4b6 100644 --- a/src/components/httpRoutes/compute.ts +++ b/src/components/httpRoutes/compute.ts @@ -457,6 +457,7 @@ computeRoutes.post(`${SERVICES_API_BASE_PATH}/serviceStart`, async (req, res) => // arrays, non-scalar objects) still reach validation and produce a 400 rather // than being silently swallowed by `|| undefined`. metadata: req.body.metadata ?? undefined, + secureTls: req.body.secureTls ?? undefined, outputBucketId: (req.body.outputBucketId as string) || undefined, payment: req.body.payment, // Tri-state preserved: undefined = use node config, [] = no providers, array = use these. @@ -522,6 +523,7 @@ computeRoutes.post(`${SERVICES_API_BASE_PATH}/serviceRestart`, async (req, res) metadata: req.body.metadata ?? undefined, // Restart accepts ONLY `ports` (not the legacy `exposedPorts`) — see ServiceRestartCommand. ports: (req.body.ports as ServicePortRequest[]) || undefined, + secureTls: req.body.secureTls ?? undefined, authorization: req.headers?.authorization, caller: req.caller } diff --git a/src/test/unit/service/serviceHandlers.test.ts b/src/test/unit/service/serviceHandlers.test.ts index 338b98fb4..51040e097 100644 --- a/src/test/unit/service/serviceHandlers.test.ts +++ b/src/test/unit/service/serviceHandlers.test.ts @@ -15,6 +15,7 @@ import { ServiceRestartHandler } from '../../../components/core/service/restartS import { ServiceGetStreamableLogsHandler } from '../../../components/core/service/getStreamableLogs.js' import { SubsidyGateError } from '../../../components/core/utils/subsidyProviders.js' import { PersistentStorageAccessDeniedError } from '../../../components/persistentStorage/PersistentStorageFactory.js' +import { SECURE_TLS_UNAVAILABLE_MESSAGE } from '../../../components/c2d/serviceTls.js' import { HostPortUnavailableError } from '../../../components/core/service/utils.js' // Checksummed (EIP-55): commands are canonicalized on ingress, so this is the form handlers @@ -60,6 +61,13 @@ const TEMPLATE = { exposedPorts: [8888] } +// createServiceJob(..., metadata, outputBucketId, requestedHostPorts, secureTls) +const START_METADATA_ARG = 15 +const START_BUCKET_ARG = 16 +const START_SECURE_TLS_ARG = 18 +// restartService(..., metadata, newExposedPorts, newRequestedHostPorts, secureTls) +const RESTART_SECURE_TLS_ARG = 13 + interface FakeOpts { serviceEnabled?: boolean // per-env service cap; omitted → the env inherits the daemon's 86400 @@ -67,6 +75,8 @@ interface FakeOpts { // per-env service floor; omitted → the env has none (no minJobDuration on the fake env) minServiceDuration?: number serviceJobInDb?: ServiceJob | null + secureTls?: boolean // env.features.secureTls; off by default + tlsConfigured?: boolean // engine.serviceTlsConfigured(); defaults to secureTls cost?: number | null envId?: string streamableLogs?: Readable | null @@ -77,7 +87,8 @@ function buildFakes(opts: FakeOpts = {}) { id: opts.envId ?? 'env-1', features: { computeJobs: true, - services: opts.serviceEnabled !== false + services: opts.serviceEnabled !== false, + ...(opts.secureTls ? { secureTls: true } : {}) }, resources: [{ id: 'cpu', kind: 'fungible', total: 8, min: 1, max: 8 }], ...(opts.maxServiceDuration === undefined @@ -118,6 +129,7 @@ function buildFakes(opts: FakeOpts = {}) { }, escrow, getComputeEnvironments: sinon.stub().resolves([env]), + serviceTlsConfigured: sinon.stub().returns(opts.tlsConfigured ?? !!opts.secureTls), // hash must match makeJob's clusterHash: handlers resolve the owning engine by it getC2DConfig: sinon.stub().returns({ hash: 'hash-1', @@ -667,6 +679,74 @@ describe('Service handlers', () => { expect(engine.restartService.calledOnce).to.equal(true) }) + describe('secureTls', () => { + it('400 when the env has no TLS', async () => { + const { node, engine } = buildFakes({ serviceJobInDb: makeJob() }) + const res = await new ServiceRestartHandler(node).handle({ + ...baseTask, + secureTls: [8888] + } as any) + expect(res.status.httpStatus).to.equal(400) + expect(String(res.status.error)).to.contain('TLS is not available') + expect(engine.restartService.called).to.equal(false) + }) + + it('omitted list on a node whose config lost TLS: restarts plain ([])', async () => { + const { node, engine } = buildFakes({ + serviceJobInDb: makeJob({ secureTls: [8888] }) + }) + const res = await new ServiceRestartHandler(node).handle({ ...baseTask } as any) + expect(res.status.httpStatus).to.equal(200) + expect( + engine.restartService.firstCall.args.at(RESTART_SECURE_TLS_ARG) + ).to.deep.equal([]) + }) + + it('omitted list while Caddy is not synced yet keeps the stored list', async () => { + const { node, engine } = buildFakes({ + serviceJobInDb: makeJob({ secureTls: [8888] }), + tlsConfigured: true + }) + const res = await new ServiceRestartHandler(node).handle({ ...baseTask } as any) + expect(res.status.httpStatus).to.equal(200) + expect(engine.restartService.firstCall.args.at(RESTART_SECURE_TLS_ARG)).to.equal( + undefined + ) + }) + + it('forwards a valid list', async () => { + const { node, engine } = buildFakes({ + serviceJobInDb: makeJob(), + secureTls: true + }) + const list = [8888] + const res = await new ServiceRestartHandler(node).handle({ + ...baseTask, + secureTls: list + } as any) + expect(res.status.httpStatus).to.equal(200) + expect( + engine.restartService.firstCall.args.at(RESTART_SECURE_TLS_ARG) + ).to.deep.equal(list) + }) + + it('checks the list against the new "ports"', async () => { + const { node, engine } = buildFakes({ + serviceJobInDb: makeJob(), + secureTls: true + }) + const res = await new ServiceRestartHandler(node).handle({ + ...baseTask, + ports: [{ containerPort: 9000 }], + secureTls: [9000] + } as any) + expect(res.status.httpStatus).to.equal(200) + expect( + engine.restartService.firstCall.args.at(RESTART_SECURE_TLS_ARG) + ).to.deep.equal([9000]) + }) + }) + it('maps the engine backstop SubsidyGateError to 403 (not 500)', async () => { // The engine re-runs the subsidy gate on the fresh row under the lock and throws // SubsidyGateError on a disallowed RESPEC (the concurrent-extend race). The handler must @@ -1287,10 +1367,52 @@ describe('Service handlers', () => { expect(res.status.httpStatus).to.equal(403) }) + describe('secureTls', () => { + const tlsTask = { ...baseTask, exposedPorts: [8188] } + + it('400 with the rejection message when the env has no TLS', async () => { + const { node, engine } = buildFakes() + const res = await new ServiceStartHandler(node).handle({ + ...tlsTask, + secureTls: [8188] + } as any) + expect(res.status.httpStatus).to.equal(400) + expect(String(res.status.error)).to.contain(SECURE_TLS_UNAVAILABLE_MESSAGE) + expect(engine.createServiceJob.called).to.equal(false) + }) + + it('passes the list to createServiceJob', async () => { + const { node, engine } = buildFakes({ secureTls: true }) + const list = [8188] + const res = await new ServiceStartHandler(node).handle({ + ...tlsTask, + secureTls: list + } as any) + expect(res.status.httpStatus).to.equal(200) + expect( + engine.createServiceJob.firstCall.args.at(START_SECURE_TLS_ARG) + ).to.deep.equal(list) + }) + + it('accepts a port given only in "ports"', async () => { + const { node, engine } = buildFakes({ secureTls: true }) + const res = await new ServiceStartHandler(node).handle({ + ...baseTask, + exposedPorts: undefined, + ports: [{ containerPort: 8188 }], + secureTls: [8188] + } as any) + expect(res.status.httpStatus).to.equal(200) + expect( + engine.createServiceJob.firstCall.args.at(START_SECURE_TLS_ARG) + ).to.deep.equal([8188]) + }) + }) + // createServiceJob arg order (see compute_engine_docker.createServiceJob): // (env, image, tag, checksum, dockerfile, addFiles, cmd, entrypoint, exposedPorts[8], // resources, duration, owner, payment, serviceId, userData, metadata, outputBucketId, - // requestedHostPorts[17]) + // requestedHostPorts[17], secureTls[18]) it('400 when "ports" has a duplicate containerPort, without creating a job', async () => { const { node, engine } = buildFakes() const res = await new ServiceStartHandler(node).handle({ @@ -1523,9 +1645,9 @@ describe('Service handlers', () => { outputBucketId: 'bucket-42' } as any) expect(res.status.httpStatus).to.equal(200) - // signature tail: (..., metadata[15], outputBucketId[16], requestedHostPorts[17]). - // Explicit index, not .at(-1): requestedHostPorts is now the trailing arg. - expect(engine.createServiceJob.lastCall.args[16]).to.equal('bucket-42') + expect(engine.createServiceJob.lastCall.args.at(START_BUCKET_ARG)).to.equal( + 'bucket-42' + ) }) it('forwards user metadata to createServiceJob (before outputBucketId)', async () => { @@ -1536,9 +1658,9 @@ describe('Service handlers', () => { metadata } as any) expect(res.status.httpStatus).to.equal(200) - // signature tail: (..., serviceId[13], userData[14], metadata[15], outputBucketId[16], - // requestedHostPorts[17]). Explicit index, not .at(-2), for the same reason. - expect(engine.createServiceJob.firstCall.args[15]).to.deep.equal(metadata) + expect(engine.createServiceJob.firstCall.args.at(START_METADATA_ARG)).to.deep.equal( + metadata + ) }) it('400 fail-fast when metadata exceeds 1 KB, before any job is created', async () => { diff --git a/src/test/unit/service/serviceReadiness.test.ts b/src/test/unit/service/serviceReadiness.test.ts index efb7076e2..c8fb29969 100644 --- a/src/test/unit/service/serviceReadiness.test.ts +++ b/src/test/unit/service/serviceReadiness.test.ts @@ -248,6 +248,23 @@ describe('probeCandidates', () => { expect(urls).to.include('http://127.0.0.1:31001/health') expect(urls).to.not.include('http://127.0.0.1:31000/health') }) + + it('for a TLS port, keeps only the container IP and the public https URL', () => { + const tlsJob = { + endpoints: [ + { + containerPort: 8000, + hostPort: 31042, + url: 'https://157.66.255.31:31042', + tls: true + } + ] + } as ServiceJob + expect(probeCandidates(tlsJob, ['172.20.0.2'], 8000, '/health')).to.deep.equal([ + 'http://172.20.0.2:8000/health', + 'https://157.66.255.31:31042/health' + ]) + }) }) describe('runReadinessProbe', () => { diff --git a/src/test/unit/service/serviceTls.test.ts b/src/test/unit/service/serviceTls.test.ts new file mode 100644 index 000000000..6271cf84b --- /dev/null +++ b/src/test/unit/service/serviceTls.test.ts @@ -0,0 +1,68 @@ +import { expect } from 'chai' +import { + validateSecureTls, + buildServiceEndpoints, + tlsNameFor +} from '../../../components/c2d/serviceTls.js' +import { buildCaddyServers } from '../../../components/c2d/caddyProxy.js' + +describe('service TLS helpers', () => { + it('validateSecureTls: accepts exposed ports, rejects the rest', () => { + for (const ok of [undefined, [], [8188, 8189]]) + expect(validateSecureTls(ok, [8188, 8189])).to.equal(null) + for (const bad of ['x', ['8188'], [8188, 8188]]) + expect(validateSecureTls(bad, [8188])).to.be.a('string') + expect(validateSecureTls([9999], [8188])).to.contain('9999') + }) + + it('buildServiceEndpoints: https for secure ports, IPv6 in brackets', () => { + expect( + buildServiceEndpoints([8188, 8189], [31042, 31043], 'fd00::1', [8188]) + ).to.deep.equal([ + { containerPort: 8188, hostPort: 31042, url: 'https://[fd00::1]:31042', tls: true }, + { containerPort: 8189, hostPort: 31043, url: 'http://[fd00::1]:31043', tls: false } + ]) + }) + + it('buildCaddyServers: one host-matched proxy server per TLS endpoint', () => { + const HOST = '157.66.255.31' + const endpoints = buildServiceEndpoints([8188, 8189], [31042, 31043], HOST, [8188]) + expect( + buildCaddyServers(HOST, [{ serviceId: 'abc', upstreamIp: '172.20.0.2', endpoints }]) + ).to.deep.equal({ + ocean_abc_8188: { + listen: [':31042'], + tls_connection_policies: [{ default_sni: HOST }], + routes: [ + { + match: [{ host: [HOST] }], + handle: [ + { + handler: 'reverse_proxy', + upstreams: [{ dial: '172.20.0.2:8188' }], + flush_interval: -1, + stream_close_delay: '86400s' + } + ] + } + ] + } + }) + }) + + it('tlsNameFor: a public IP or a domain, else null', () => { + expect(tlsNameFor('157.66.255.31')).to.equal('157.66.255.31') + expect(tlsNameFor('cp1.oncompute.ai')).to.equal('cp1.oncompute.ai') + for (const bad of [ + 'localhost', + 'node1', + '10.0.0.1', + '192.168.1.1', + 'fd00::1', + 'node.local', + 'host.docker.internal', + undefined + ]) + expect(tlsNameFor(bad)).to.equal(null) + }) +}) diff --git a/src/test/unit/service/serviceTlsSync.test.ts b/src/test/unit/service/serviceTlsSync.test.ts new file mode 100644 index 000000000..e0882c0e3 --- /dev/null +++ b/src/test/unit/service/serviceTlsSync.test.ts @@ -0,0 +1,542 @@ +import { expect } from 'chai' +import sinon from 'sinon' +import { C2DEngineDocker } from '../../../components/c2d/compute_engine_docker.js' +import { ServiceStatusNumber } from '../../../@types/C2D/ServiceOnDemand.js' +import { + CaddyProxy, + CADDY_ACME_JSON, + CADDY_CONTAINER, + CADDY_IMAGE, + CADDY_LOAD_CMD, + buildCaddyConfig, + buildCaddyServers, + ensureCaddy, + findStoreCert +} from '../../../components/c2d/caddyProxy.js' +import { releaseHostPort } from '../../../components/core/service/utils.js' + +const NODE_HOST = '157.66.255.31' +const ACME_FILE = '/srv/letsencrypt/acme.json' + +interface FakeCaddy { + loads: any[] // configs Caddy accepted + execs: { cmd: string[]; input: string }[] + fail: boolean + acmeJson: string + hasCert: boolean // Caddy's storage holds a cert for nodeHost +} + +// Stands in for the node's Caddy container (ensureCaddy + docker exec) +function fakeCaddyIo(fake: FakeCaddy) { + const container = { id: 'caddy' } + return { + ensure: sinon.stub().resolves(container), + remove: sinon.stub().resolves(), + exec: sinon.stub().callsFake((_c: unknown, cmd: string[], input = '') => { + fake.execs.push({ cmd, input }) + if (cmd === CADDY_LOAD_CMD) { + if (fake.fail) return Promise.reject(new Error('caddy exec wget exited 1')) + fake.loads.push(JSON.parse(input)) + } + if (cmd[2]?.startsWith('ls ') && !fake.hasCert) + return Promise.reject(new Error('caddy exec sh exited 1')) + return Promise.resolve(cmd[0] === 'cat' ? fake.acmeJson : '') + }) + } +} + +// Self-signed test certs: SANs 1.c2d.nodes.oceanprotocol.com + cp2.oncompute.ai, and *.example.com +const SAN_CERT = `-----BEGIN CERTIFICATE----- +MIIB5TCCAYugAwIBAgIUcNXwP5RVCh4u3h68tgnxr7NH0T0wCgYIKoZIzj0EAwIw +KDEmMCQGA1UEAwwdMS5jMmQubm9kZXMub2NlYW5wcm90b2NvbC5jb20wIBcNMjYx +MTI0MTM0MTIzWhgPMjEyNjEwMzExMzQxMjNaMCgxJjAkBgNVBAMMHTEuYzJkLm5v +ZGVzLm9jZWFucHJvdG9jb2wuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE +u/6yoPj6yD0EM0AlDFh5HCyLiSC30vp/ZqJt8YJtftnRps5pl8X1U/g8OZt7xuDF +wUQj0de4Lw7xPh+SWAcfM6OBkDCBjTAdBgNVHQ4EFgQU0IPNbEBXAoB3tKhQYJID +8Ck8yjEwHwYDVR0jBBgwFoAU0IPNbEBXAoB3tKhQYJID8Ck8yjEwDwYDVR0TAQH/ +BAUwAwEB/zA6BgNVHREEMzAxgh0xLmMyZC5ub2Rlcy5vY2VhbnByb3RvY29sLmNv +bYIQY3AyLm9uY29tcHV0ZS5haTAKBggqhkjOPQQDAgNIADBFAiEAg5A4DvqQqCgx +xJimK/u8KwBGkWUchBpRk5lCTKO5LtQCICJ+kEkVp3B+U28hJ3OSTwYfjEP8hopJ +7bQP3o62tx4S +-----END CERTIFICATE----- +` +const WILDCARD_CERT = `-----BEGIN CERTIFICATE----- +MIIBnDCCAUOgAwIBAgIUCbjj4FdbcTiWxC6mYcJROxMUXcswCgYIKoZIzj0EAwIw +FjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wIBcNMjYxMTI0MTM0MTIzWhgPMjEyNjEw +MzExMzQxMjNaMBYxFDASBgNVBAMMC2V4YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYI +KoZIzj0DAQcDQgAEXdjyzMS77ewjVHWC5cvFx5DKU4/xCEULM2fLz4Djl9p8g6gc +K5anF+cp6dvat8JPbNMWOijlEw/jb8t0NX0As6NtMGswHQYDVR0OBBYEFJcfii3C +NgaBznf3oqYWExSE+cBrMB8GA1UdIwQYMBaAFJcfii3CNgaBznf3oqYWExSE+cBr +MA8GA1UdEwEB/wQFMAMBAf8wGAYDVR0RBBEwD4INKi5leGFtcGxlLmNvbTAKBggq +hkjOPQQDAgNHADBEAiBswN4kQ9SbLTbV3GD5ibblAAV0nJ/gOt+f2Jg2yaXLsAIg +Twks4csGCs14fFZW7mMcxTDhqMsKHesV9eqRrxqXsf8= +-----END CERTIFICATE----- +` +const KEY_PEM = '-----BEGIN PRIVATE KEY-----\nK\n-----END PRIVATE KEY-----\n' + +function acmeJsonFor(...certs: string[]): string { + const b64 = (text: string) => Buffer.from(text).toString('base64') + return JSON.stringify({ + myresolver: { + Certificates: certs.map((cert) => ({ certificate: b64(cert), key: b64(KEY_PEM) })) + } + }) +} + +describe('ensureCaddy', () => { + const BINDS = ['ocean-node-caddy-data:/data'] + function fakeDocker(info: any) { + const existing = { + inspect: info + ? sinon.stub().resolves(info) + : sinon.stub().rejects(Object.assign(new Error('gone'), { statusCode: 404 })), + start: sinon.stub().resolves(), + remove: sinon.stub().resolves() + } + const created = { start: sinon.stub().resolves() } + return { + existing, + created, + getContainer: sinon.stub().returns(existing), + getImage: sinon.stub().returns({ inspect: sinon.stub().resolves({}) }), + createContainer: sinon.stub().resolves(created) + } + } + const LABEL = 'ocean-node.letsencrypt-acme-path' + const OWNER = 'ocean-node.owner' + const running = (acme = '', Image = CADDY_IMAGE, owner = '0xnode') => ({ + Config: { Image, Labels: { [LABEL]: acme, [OWNER]: owner } }, + State: { Running: true } + }) + + it('creates and starts Caddy on the host network when it is missing', async () => { + const docker = fakeDocker(null) + expect(await ensureCaddy(docker as any, '0xnode')).to.equal(docker.created) + expect(docker.createContainer.firstCall.args[0]).to.deep.equal({ + name: CADDY_CONTAINER, + Image: CADDY_IMAGE, + Cmd: ['caddy', 'run'], + Labels: { [LABEL]: '', [OWNER]: '0xnode' }, + HostConfig: { NetworkMode: 'host', RestartPolicy: { Name: 'always' }, Binds: BINDS } + }) + expect(docker.created.start.calledOnce).to.equal(true) + }) + + it('keeps a running Caddy with the same image and files', async () => { + const docker = fakeDocker(running()) + expect(await ensureCaddy(docker as any, '0xnode')).to.equal(docker.existing) + expect(docker.existing.start.called).to.equal(false) + expect(docker.createContainer.called).to.equal(false) + }) + + it("leaves another node's Caddy alone", async () => { + const docker = fakeDocker(running('', CADDY_IMAGE, '0xother')) + let error: Error + await ensureCaddy(docker as any, '0xnode').catch((e) => (error = e)) + expect(error.message).to.contain('belongs to another node (0xother)') + expect(docker.existing.remove.called).to.equal(false) + }) + + it('recreates Caddy when the image or the letsEncryptAcmePath changes', async () => { + for (const [info, acme] of [ + [running('', 'caddy:2.10.0-alpine'), undefined], + [running(), '/srv/letsencrypt/acme.json'] + ] as const) { + const docker = fakeDocker(info) + await ensureCaddy(docker as any, '0xnode', acme) + expect(docker.existing.remove.calledOnce).to.equal(true) + expect(docker.createContainer.calledOnce).to.equal(true) + } + const docker = fakeDocker(null) + await ensureCaddy(docker as any, '0xnode', '/srv/letsencrypt/acme.json') + expect(docker.createContainer.firstCall.args[0].HostConfig.Binds).to.deep.equal([ + ...BINDS, + `/srv/letsencrypt/acme.json:${CADDY_ACME_JSON}:ro` + ]) + }) +}) + +describe('findStoreCert', () => { + it('finds the cert that covers the name, wildcards for one label only', () => { + const store = acmeJsonFor(SAN_CERT, WILDCARD_CERT) + expect(findStoreCert(store, 'cp2.oncompute.ai')).to.contain(SAN_CERT.trim()) + expect(findStoreCert(store, 'api.example.com')).to.contain(WILDCARD_CERT.trim()) + for (const name of ['cp1.oncompute.ai', 'a.b.example.com', 'example.com']) + expect(findStoreCert(store, name)).to.equal(null) + }) +}) + +describe('service TLS sync (Caddy admin API)', () => { + let engine: any + let network: any + let caddy: FakeCaddy + let io: ReturnType + let containers: Record + + function setTlsEngine(opts: { nodeHost?: string; letsEncryptAcmePath?: string }) { + engine.getC2DConfig = sinon.stub().returns({ + hash: 'cluster-hash', + connection: { + socketPath: '/var/run/docker.sock', + serviceOnDemand: { + hostPortRange: [31042, 31141], + nodeHost: opts.nodeHost ?? NODE_HOST, + letsEncryptAcmePath: opts.letsEncryptAcmePath + } + } + }) + } + + function inspectWithIp(serviceId: string, ip: string) { + return sinon.stub().resolves({ + NetworkSettings: { Networks: { [`ocean-svc-${serviceId}`]: { IPAddress: ip } } } + }) + } + + beforeEach(() => { + caddy = { loads: [], execs: [], fail: false, acmeJson: '{}', hasCert: true } + engine = Object.create(C2DEngineDocker.prototype) + engine.tlsSync = Promise.resolve(true) + engine.cpuAllocations = new Map() + engine.envCpuCoresMap = new Map() + engine.serviceOpsInFlight = new Set() + engine.serviceOpPromises = new Set() + network = { + id: 'net-1', + inspect: sinon.stub().resolves({ Containers: {} }), + remove: sinon.stub().resolves() + } + containers = {} + const service = { + id: 'svc-container', + start: sinon.stub().resolves(), + stop: sinon.stub().resolves(), + remove: sinon.stub().resolves(), + infoArchive: sinon.stub().resolves({}), + inspect: inspectWithIp('x', '172.20.0.2') + } + containers['svc-container'] = service + engine.docker = { + createNetwork: sinon.stub().resolves(network), + createContainer: sinon.stub().resolves(service), + getNetwork: sinon.stub().returns(network), + getContainer: sinon.stub().callsFake((id: string) => containers[id]) + } + engine.db = { + updateServiceJob: sinon.stub().resolves(), + acquireServiceLock: sinon.stub().resolves(true), + releaseServiceLock: sinon.stub().resolves(undefined), + getRunningServiceJobs: sinon.stub().resolves([]) + } + setTlsEngine({}) + engine.pullImageRef = sinon.stub().resolves() + engine.buildServiceResourceConstraints = sinon + .stub() + .returns({ Memory: 0, NanoCpus: 0, DeviceRequests: [] }) + engine.escrow = { + createLock: sinon.stub().resolves('0xlock'), + waitForTransaction: sinon.stub().resolves(), + claimLock: sinon.stub().resolves('0xclaim'), + cancelExpiredLock: sinon.stub().resolves('0xcancel'), + getMinLockTime: sinon.stub().returns(3600) + } + engine.keyManager = { decrypt: sinon.stub().resolves(Buffer.from('{}')) } + io = fakeCaddyIo(caddy) + engine.caddy = new CaddyProxy(engine.docker, '0xnode', io as any) + }) + + afterEach(() => { + sinon.restore() + // claimed services keep their host ports reserved: free them for the next test + for (let p = 31042; p <= 31141; p++) releaseHostPort(p) + }) + + function makeStartingJob(overrides: any = {}) { + return { + serviceId: 'x', + clusterHash: 'cluster-hash', + environment: 'env-1', + owner: '0xowner', + image: 'nginx', + tag: 'latest', + containerImage: 'nginx:latest', + containerId: '', + networkId: '', + status: ServiceStatusNumber.Starting, + statusText: 'Starting', + dateCreated: new Date().toISOString(), + expiresAt: Date.now() + 60000, + duration: 60, + exposedPorts: [8188, 8189], + endpoints: [] as any[], + secureTls: [8188], + resources: [{ id: 'cpu', amount: 1 }], + payment: { + chainId: 1, + token: '0xtoken', + cost: 10, + lockTx: '', + claimTx: '', + cancelTx: '' + }, + ...overrides + } + } + + function makeRunningJob(overrides: any = {}) { + return { + ...makeStartingJob(), + status: ServiceStatusNumber.Running, + statusText: 'Running', + containerId: 'svc-container', + endpoints: [ + { + containerPort: 8188, + hostPort: 31042, + url: `https://${NODE_HOST}:31042`, + tls: true + }, + { + containerPort: 8189, + hostPort: 31043, + url: `http://${NODE_HOST}:31043`, + tls: false + } + ], + payment: { chainId: 1, token: '0xtoken', claimTx: '0xclaim' }, + ...overrides + } + } + + const posts = () => caddy.loads.map((config) => ({ body: config.apps.http.servers })) + + describe('syncServiceTls', () => { + it('loads one server map built from the running secure services', async () => { + const a = makeRunningJob({ serviceId: 'a', containerId: 'ca' }) + containers.ca = { inspect: inspectWithIp('a', '172.20.0.5') } + engine.db.getRunningServiceJobs.resolves([ + a, + makeRunningJob({ serviceId: 'b', containerId: 'cb', secureTls: undefined }), + makeStartingJob({ serviceId: 'c' }) + ]) + + await engine.syncServiceTls() + + expect(caddy.loads).to.deep.equal([ + buildCaddyConfig( + buildCaddyServers(NODE_HOST, [ + { + serviceId: 'a', + upstreamIp: '172.20.0.5', + endpoints: a.endpoints + } + ]), + NODE_HOST + ) + ]) + expect(io.ensure.firstCall.args.slice(1)).to.deep.equal(['0xnode', undefined]) + }) + + it('a failed load does not throw, and is retried on the next sync', async () => { + caddy.fail = true + engine.db.getRunningServiceJobs.resolves([makeRunningJob()]) + await engine.syncServiceTls() + caddy.fail = false + await engine.syncServiceTls() + expect(posts()).to.have.length(1) + }) + + it('letsEncryptAcmePath: loads its cert for nodeHost, no ACME, no port 80', async () => { + setTlsEngine({ nodeHost: 'cp2.oncompute.ai', letsEncryptAcmePath: ACME_FILE }) + caddy.acmeJson = acmeJsonFor(WILDCARD_CERT, SAN_CERT) + engine.db.getRunningServiceJobs.resolves([makeRunningJob()]) + + await engine.syncServiceTls() + + expect(io.ensure.firstCall.args[2]).to.equal(ACME_FILE) + const [read, write] = caddy.execs + expect(read.cmd).to.deep.equal(['cat', CADDY_ACME_JSON]) + expect(write.input).to.equal(`${SAN_CERT.trim()}\n${KEY_PEM.trim()}`) + const [config] = caddy.loads + const file = config.apps.tls.certificates.load_files[0].certificate + expect(write.cmd[2]).to.match(new RegExp(`cat > ${file}$`)) + expect(config.apps.tls).to.not.have.property('automation') + expect(config.apps.http.servers.ocean_x_8188.automatic_https).to.deep.equal({ + disable_redirects: true + }) + expect(engine.caddy.certReady).to.equal(true) + }) + + it('TLS off on the TLS engine: removes Caddy once, so it frees the ports', async () => { + setTlsEngine({ nodeHost: 'localhost' }) + expect(await engine.syncServiceTls()).to.equal(true) + await engine.syncServiceTls() + expect(io.remove.calledOnceWith(engine.docker, '0xnode')).to.equal(true) + expect(io.ensure.called).to.equal(false) + }) + + it('a throw while it builds a sync resolves false, and the next sync still runs', async () => { + engine.tlsNodeHost = () => { + throw new Error('bad config') + } + expect(await engine.syncServiceTls()).to.equal(false) + delete engine.tlsNodeHost + expect(await engine.syncServiceTls()).to.equal(true) + expect(posts()).to.have.length(1) + }) + + it('skips identical servers within a minute, re-sends them after', async () => { + engine.db.getRunningServiceJobs.resolves([makeRunningJob()]) + await engine.syncServiceTls() + await engine.syncServiceTls() + expect(posts()).to.have.length(1) + engine.caddy.lastLoad.at -= 60_000 + await engine.syncServiceTls() + expect(posts()).to.have.length(2) + }) + }) + + it('start: binds only the plain port on the service', async () => { + const job = makeStartingJob() + engine.db.getServiceJob = sinon.stub().resolves([job]) + + await engine.processServiceStart(job) + + expect(job.status, job.statusText).to.equal(ServiceStatusNumber.Running) + const secure = job.endpoints.find((e: any) => e.containerPort === 8188) + expect(secure).to.include({ + tls: true, + url: `https://${NODE_HOST}:${secure.hostPort}` + }) + const opts = engine.docker.createContainer.firstCall.args[0] + expect(Object.keys(opts.HostConfig.PortBindings)).to.deep.equal(['8189/tcp']) + expect(Object.keys(opts.ExposedPorts)).to.have.members(['8188/tcp', '8189/tcp']) + expect(engine.docker.createContainer.calledOnce).to.equal(true) + }) + + it('restart with []: Caddy drops the port before the service publishes it', async () => { + const job = makeRunningJob() + engine.db.getServiceJob = sinon.stub().resolves([job]) + engine.db.getRunningServiceJobs.callsFake(() => Promise.resolve([job])) + const service = await engine.docker.createContainer() + engine.docker.createContainer.resetHistory() + let bodiesAtCreate: any[] = [] + engine.docker.createContainer.callsFake(() => { + bodiesAtCreate = posts().map((p) => p.body) + return Promise.resolve(service) + }) + const args = [job.serviceId, '0xowner', ...Array(11).fill(undefined), []] + + await engine.restartService(...args) + await Promise.allSettled([...engine.serviceOpPromises]) + + expect(job.status, job.statusText).to.equal(ServiceStatusNumber.Running) + expect( + engine.docker.createContainer.firstCall.args[0].HostConfig.PortBindings + ).to.deep.equal({ + '8188/tcp': [{ HostPort: '31042' }], + '8189/tcp': [{ HostPort: '31043' }] + }) + expect(bodiesAtCreate).to.deep.equal([{}]) + }) + + it('restart with a port change and []: Caddy drops the old port first', async () => { + const job = makeRunningJob() + engine.db.getServiceJob = sinon.stub().resolves([job]) + engine.db.getRunningServiceJobs.callsFake(() => Promise.resolve([job])) + const service = await engine.docker.createContainer() + engine.docker.createContainer.resetHistory() + let bodiesAtCreate: any[] = [] + engine.docker.createContainer.callsFake(() => { + bodiesAtCreate = posts().map((p) => p.body) + return Promise.resolve(service) + }) + const args = [ + job.serviceId, + '0xowner', + ...Array(9).fill(undefined), + [8188, 8189], + undefined, + [] + ] + + await engine.restartService(...args) + await Promise.allSettled([...engine.serviceOpPromises]) + + expect(job.status, job.statusText).to.equal(ServiceStatusNumber.Running) + expect( + engine.docker.createContainer.firstCall.args[0].HostConfig.PortBindings + ).to.deep.equal({ + '8188/tcp': [{ HostPort: '31042' }], + '8189/tcp': [{ HostPort: '31043' }] + }) + expect(bodiesAtCreate).to.deep.equal([{}]) + }) + + it('restart with []: fails before publishing the port when Caddy does not free it', async () => { + const job = makeRunningJob() + engine.db.getServiceJob = sinon.stub().resolves([job]) + engine.db.getRunningServiceJobs.callsFake(() => Promise.resolve([job])) + caddy.fail = true + engine.docker.createContainer.resetHistory() + const args = [job.serviceId, '0xowner', ...Array(11).fill(undefined), []] + + await engine.restartService(...args) + await Promise.allSettled([...engine.serviceOpPromises]) + + expect(job.status).to.equal(ServiceStatusNumber.Error) + expect(job.statusText).to.contain('Caddy did not release the TLS ports') + expect(engine.docker.createContainer.called).to.equal(false) + }) + + describe('getComputeEnvironments features.secureTls', () => { + async function feature() { + engine.envs = [{ id: 'env-1', resources: [], free: { resources: [] } }] + engine.getUsedResources = sinon.stub().resolves({ + totalJobs: 0, + totalFreeJobs: 0, + usedResources: {}, + usedFreeResources: {} + }) + const [env] = await engine.getComputeEnvironments() + return env.features.secureTls + } + + it('is off until Caddy holds the certificate', async () => { + caddy.hasCert = false + await engine.syncServiceTls() + expect(caddy.loads).to.have.length(1) + expect(await feature()).to.equal(false) + caddy.hasCert = true + engine.caddy.lastLoad.at -= 60_000 + await engine.syncServiceTls() + expect(await feature()).to.equal(true) + }) + + it('turns on seconds after the certificate arrives, not a minute', async () => { + const clock = sinon.useFakeTimers({ now: Date.now(), toFake: ['Date'] }) + try { + caddy.hasCert = false + await engine.syncServiceTls() + caddy.hasCert = true + await engine.syncServiceTls() + expect(await feature()).to.equal(false) + clock.tick(5_000) + await engine.syncServiceTls() + expect(await feature()).to.equal(true) + } finally { + clock.restore() + } + }) + + it('is off until Caddy accepts a sync, and off again after a rejected one', async () => { + expect(await feature()).to.equal(false) + await engine.syncServiceTls() + expect(await feature()).to.equal(true) + caddy.fail = true + engine.caddy.lastLoad.at -= 60_000 + await engine.syncServiceTls() + expect(await feature()).to.equal(false) + }) + }) +}) diff --git a/src/utils/config/schemas.ts b/src/utils/config/schemas.ts index 237ecb3f8..affb45b01 100644 --- a/src/utils/config/schemas.ts +++ b/src/utils/config/schemas.ts @@ -722,6 +722,7 @@ export const ServiceTemplateSchema = z dockerfile: z.string().min(1).optional(), additionalDockerFiles: z.record(z.string(), z.string()).optional(), exposedPorts: z.array(z.number().int().min(1).max(65535)).min(1), + secureTls: z.array(z.number().int()).optional(), envVars: z.record(z.string(), z.string()).optional(), userConfigurableEnvVars: z.array(UserConfigurableEnvVarSchema).optional(), command: z.array(z.string()).optional(), @@ -881,6 +882,7 @@ export const ServiceOnDemandConfigSchema = z .object({ enabled: z.boolean(), nodeHost: z.string().min(1), + letsEncryptAcmePath: z.string().startsWith('/').optional(), hostPortRange: z .tuple([z.number().int().min(1024), z.number().int().max(65535)]) .refine((r) => !r || r[0] < r[1], {