# Program Design: ino VPS server Gate 1 and Gate 2 are approved. This Gate 3 draft pins the server/API, local bootstrap, release-client, and test interfaces before implementation. The service remains a native extension of the existing `ino once` Docker/Once implementation and introduces no separate app store or remote Docker endpoint. ## Files - `Cargo.toml` — add Actix Web, constant-time bearer-key comparison, JSON support for Reqwest, and Tokio synchronization/time features required by the existing runtime and server. - `Cargo.lock` — lock the server and HTTP-client dependency graph. - `.dockerignore` — keep host build output, Git metadata, and local files out of the server image build context. - `Dockerfile` — build the `ino` binary in a multi-stage image, set `ino once serve` as the default command, and declare `LABEL remote="silenloc/ino"`. - `src/main.rs` — keep the current top-level command dispatch and no-argument automatic-release behavior unchanged; server commands remain nested under `ino once`. - `src/commands/once/cli.rs` — add `server setup` and `server serve` argument types; setup takes a public host, optional image version, and optional internal port, but never an API key argument. - `src/commands/once/mod.rs` — keep setup and existing commands on the isolated Tokio runtime; enter an Actix System for `server serve` without nesting runtimes, and retain existing CLI output behavior. - `src/commands/once/server.rs` — validate server configuration, perform idempotent local setup, bootstrap the special app, restore the namespace, reconcile the proxy route, and start the HTTP listener. - `src/commands/once/server/api.rs` — define authenticated Actix Web routes, JSON request/response DTOs, redacted error responses, and bounded exec/log responses. - `src/commands/once/docker.rs` — add the narrow Docker operations needed for server-container runtime configuration, restart, and bounded logs; retain direct Docker Engine access through Bollard. - `src/commands/once/namespace.rs` — retain the internal server-app marker during discovery so ordinary app deployment cannot accidentally inherit server privileges. - `src/commands/once/model.rs` — add a serializable, explicitly non-sensitive app summary shared by CLI/API operation results. - `src/commands/once/operations.rs` — make API-used lifecycle operations return structured results instead of printing; add restart/log support and preserve the special socket mount/runtime key when replacing the marked server app. - `src/commands/once/proxy.rs` — allow the server route to specify its internal target port while preserving the existing default port behavior for ordinary Once apps. - `src/commands/release.rs` — parse opt-in deployment labels, validate local credentials, and after the normal image push and Git release call `PATCH /api/v1/apps/{host}` with the versioned image reference. - `tests/once_cli.rs` — cover server command parsing and prove existing top-level/default command behavior remains unchanged. - `tests/once_server.rs` — exercise the authenticated API and server setup/update behavior against Docker-shaped Once resources; Docker-dependent cases use the existing `docker-tests` feature convention. - `README.md` — add the server-image and quick-start overview without changing the existing release/Once descriptions. - `docs/once-server.md` — document setup, API schemas, deployment labels, release credentials, security boundaries, limits, and self-update behavior. ## Types & signatures CLI and bootstrap inputs: ```rust pub enum ServerCommand { Setup(ServerSetupArgs), Serve, } pub struct ServerSetupArgs { pub host: String, pub version: Option, pub port: u16, // default 80 } pub struct ServerConfig { pub namespace: String, pub listen: std::net::SocketAddr, // 0.0.0.0: pub port: u16, pub api_key: ApiKey, } pub struct ApiKey(/* redacted secret bytes */); pub async fn setup(namespace: String, args: ServerSetupArgs) -> Result<(), OnceError>; pub async fn serve(namespace: String) -> Result<(), OnceError>; ``` `INO_API_KEY` is required by both setup and serve. Setup passes it only as the special server container's `INO_API_KEY` environment value; it is not put in Once settings labels, API responses, command arguments, or logs. The already-protected Docker daemon can inspect container environment as part of its administrator-level access. The server image uses `silenloc/ino:`, with the running binary's package version as the default tag. The server app has a reserved internal marker and name; only this marked app receives the `/var/run/docker.sock` bind mount. Replacements of that marked app retain the socket mount and API key from its prior container configuration, while ordinary apps never receive either. HTTP DTOs (Serde uses camelCase JSON): ```rust pub struct AppSummary { pub name: String, pub host: String, pub image: String, pub running: bool, pub url: Option, } pub struct DeployRequest { pub image: String, pub settings: DeploySettings, } pub struct DeploySettings { pub host: String, pub disable_tls: Option, pub env: Option>, pub smtp: Option, pub resources: Option, pub auto_update: Option, pub backup: Option, pub registry: Option, } pub struct UpdateRequest { pub image: Option, pub settings: SettingsPatch, } pub struct SettingsPatch { pub host: Option, pub disable_tls: Option, pub env: Option>, pub smtp: Option, pub resources: Option, pub auto_update: Option, pub backup: Option, pub registry: Option, } pub struct ExecRequest { pub command: Vec } pub struct ExecResponse { pub exit_code: i32, pub stdout: String, pub stderr: String, pub truncated: bool, } pub struct LogsResponse { pub output: String, pub truncated: bool } pub struct ApiErrorBody { pub error: ApiErrorDetail } pub struct ApiErrorDetail { pub code: String, pub message: String } ``` An omitted setting in `PATCH` is preserved. Supplying `env: {}` clears the environment map; supplying an SMTP, resources, backup, or registry object replaces that whole section (fields within the object default as in the Once model). API request settings may contain secrets, but list/detail summaries and error bodies do not. Registry credentials are accepted only in the authenticated request body and then stored using the existing Once-compatible app settings. Logs and exec output are intentionally returned to the authenticated caller, with a 1 MiB response cap; logs default to the last 100 lines and clamp `tail` to 500. Server/API and release boundaries: ```rust pub struct ServerManager { pub namespace: Namespace } pub struct ApiState { pub manager: std::sync::Arc>, pub api_key: std::sync::Arc, } pub fn configure_api(config: &mut actix_web::web::ServiceConfig); pub async fn run_http(config: ServerConfig, state: ApiState) -> Result<(), OnceError>; pub fn authenticate(headers: &actix_web::http::header::HeaderMap, expected: &ApiKey) -> Result<(), ApiError>; pub fn list(namespace: &Namespace) -> Vec; pub async fn start(namespace: &Namespace, host: &str) -> Result; pub async fn stop(namespace: &Namespace, host: &str) -> Result; pub async fn restart(namespace: &Namespace, host: &str) -> Result; pub async fn deploy(namespace: &mut Namespace, image: &str, flags: &SettingsFlags) -> Result; pub async fn update(namespace: &mut Namespace, host: &str, args: &UpdateArgs) -> Result; pub async fn remove(namespace: &mut Namespace, host: &str, remove_data: bool) -> Result<(), OnceError>; pub async fn exec_capture(namespace: &Namespace, host: &str, command: &[String]) -> Result; pub async fn logs(namespace: &Namespace, host: &str, tail: u16, max_bytes: usize) -> Result; pub struct ImageMetadata { pub remote: String, pub deployment: Option, } pub struct DeploymentTarget { pub server: reqwest::Url, pub host: String } pub fn parse_image_metadata(dockerfile: &str) -> Result; pub async fn update_deployment( client: &reqwest::Client, target: &DeploymentTarget, api_key: &ApiKey, image: &str, ) -> Result<(), ReleaseError>; ``` Deployment opt-in is explicit and separate from the existing `remote` registry label: ```dockerfile LABEL remote="owner/app" \ ino.deploy.server="https://ino.example.com" \ ino.deploy.host="app.example.com" ``` Both `ino.deploy.server` and `ino.deploy.host` must be present or neither may be present. The release client reads the bearer credential from local `INO_API_KEY`; it is never a Dockerfile label or image build argument. The server URL must use HTTPS, except loopback HTTP URLs for local testing. A deployment target with no local key is rejected before image build/push. If the server replaces itself and the HTTP connection is dropped during container handoff, the release client retries authenticated `GET /api/v1/apps` for up to 120 seconds and treats the operation as successful only once the selected host reports the requested image and `running: true`. API route contract: | Route | Result | | --- | --- | | `GET /up` | unauthenticated `200 {"status":"ok"}` readiness response | | `GET /api/v1/apps` | `200` array of redacted `AppSummary` values | | `POST /api/v1/apps` | `201 AppSummary`; deploy the request image/settings | | `POST /api/v1/apps/{host}/start` | `200 AppSummary` | | `POST /api/v1/apps/{host}/stop` | `200 AppSummary` | | `POST /api/v1/apps/{host}/restart` | `200 AppSummary` | | `PATCH /api/v1/apps/{host}` | `200 AppSummary`; omitted settings remain unchanged | | `DELETE /api/v1/apps/{host}?remove_data=false` | `204`; data is retained unless explicitly requested | | `POST /api/v1/apps/{host}/exec` | `200 ExecResponse`; nonzero command status is data, not an HTTP failure | | `GET /api/v1/apps/{host}/logs?tail=100` | `200 LogsResponse`; output and tail are bounded | All `/api/v1` routes require `Authorization: Bearer `. Key comparison is constant-time. Stable error codes map malformed/invalid input to 400, missing app to 404, hostname/state conflicts to 409, bad/missing credentials to 401, Docker/proxy operation failures to a sanitized 502, and unexpected failures to a sanitized 500. No API error includes raw Docker details, request bodies, environment values, credentials, or keys. API requests are serialized with one async mutex; the namespace is refreshed immediately before each operation and after each mutation. `/up` does not acquire that mutex. This is process-local serialization, not a lock against an operator using Docker/Once concurrently. ## Call stack ### Local server setup `main::run` → `commands::once::run` → Tokio runtime → `server::setup` → validate host/version/port and `INO_API_KEY` → connect Docker → `Namespace::restore` → reject collisions with non-server apps → `Namespace::setup` → create/update the reserved server app using `silenloc/ino:`, Once metadata, persistent app volume, `INO_API_KEY`, `PORT`, server marker, and Docker socket bind mount → wait for `/up` through the Once proxy → reconcile route at the configured internal port → refresh namespace. Re-running setup updates/reconciles only this marked app and never migrates or replaces unrelated app containers, settings, volumes, or routes. ### Server startup and request `ino once serve` → enter an Actix System (without nesting the existing manually-managed Tokio runtime) → require `INO_API_KEY`; parse `PORT` (default 80) → connect Docker and restore selected namespace → require the marked server app to exist → ensure namespace network/proxy and reconcile the server route using its container ID and internal port → bind `0.0.0.0:$PORT` → Actix Web serves public `/up` and bearer-protected `/api/v1` routes. For a control request: authenticate → acquire namespace mutex → refresh Docker state → resolve host → call the native Once operation → refresh after mutation → map to redacted JSON/status → release mutex. `/exec` uses captured non-TTY output and never attaches the server process terminal. ### Release-triggered app update `release::run` → parse root Dockerfile's existing `remote` label and optional deployment pair → validate HTTPS target and local `INO_API_KEY` before side effects → bump package version → `docker buildx build --push` version and `latest` tags → commit/push the release as today → if opted in, authenticated `PATCH /api/v1/apps/{host}` with `{"image":":"}` → on uncertain transport loss, poll authenticated app list until the exact image is running or the 120-second confirmation deadline expires → print release/deployment result. With no deployment pair, the current release sequence and output remain unchanged. ### App management and server self-update Authenticated handler → manager mutex → namespace refresh → convert API DTO to native Once settings/operation inputs → `operations` → Docker Engine/proxy/health verification → namespace refresh → response. For a marked server app update, the native replacement path preserves only the server-specific marker, socket bind mount, and `INO_API_KEY` from the previous container's inspected runtime config; the key is not copied into the Once settings label. The ordinary app path cannot request arbitrary host mounts. Removing the server app over its own API is rejected; local `ino once remove` remains the recovery path. ## Test plan - `once_server_subcommands_parse_and_keep_default_release_behavior` — server setup/serve parse correctly, and bare `ino` still routes to automatic release. - `image_metadata_requires_complete_deployment_pair` — existing `remote` parsing remains compatible; multiline labels parse; partial URL/host opt-in is rejected. - `release_deployment_requires_local_key_before_build` — opted-in release without `INO_API_KEY` fails before invoking Docker/Git; no-opt-in release requires no API key. - `release_patches_versioned_image_with_bearer_auth` — a local fake HTTP endpoint sees the expected host path, image tag, bearer header, and timeout/read-back behavior. - `api_rejects_missing_and_invalid_bearer_credentials` — protected routes return stable 401 JSON; the key is absent from the response; `/up` remains unauthenticated. - `api_app_summary_and_errors_never_serialize_secrets` — app list summaries omit env, SMTP, registry credentials, and Once keys; operation failures are sanitized and use the documented status/code mapping. - `api_patch_preserves_omitted_settings_and_replaces_explicit_sections` — omitted values remain unchanged, while explicit empty env and nested replacement values take effect. - `api_exec_and_logs_are_non_tty_and_bounded` — command exit status is returned as JSON; output cap, default log tail, maximum tail, and truncation are asserted. - `api_serializes_mutations_and_refreshes_namespace` — concurrent API mutations do not race through the in-process manager; each mutation refreshes state even on operation failure. - `server_setup_is_idempotent_and_leaves_existing_apps_untouched` (Docker-gated) — repeat setup; assert exactly one marked server app, preserved pre-existing app container/volume/route, expected proxy host, and no extra namespace resources. - `server_update_preserves_socket_mount_and_runtime_key_only_for_marked_app` (Docker-gated) — update the server image and assert new server can reach Docker and authenticate; ordinary deployments receive no host bind mount or server marker. - `server_api_manages_once_fixture_app_end_to_end` (Docker-gated) — list, deploy, start/stop/restart, update, exec, bounded logs, and remove with default data retention against an isolated Once-shaped namespace. - Existing Once CLI, release, model, and Docker tests — all current commands and Once v0.3.4 behavior continue passing. ## Least confident decisions 1. **Self-update handoff:** replacing the API server can drop its own HTTP response. The release client therefore confirms the requested image/running state by reading the app list after transport loss. Validate this against Kamal route handoff and Docker container replacement; if it is unreliable, use an explicit accepted/background update protocol before implementation. 2. **Kamal target port syntax:** the current proxy helper truncates a container ID for its target. The server needs a target that includes a non-default internal port. Verify the pinned Kamal Proxy accepts `container-id:port` and that the health check follows the configured route; default port 80 remains the ordinary app path. 3. **Credential placement:** `INO_API_KEY` is an environment value in the special container's Docker runtime config, visible to a Docker administrator but absent from Once labels, image metadata, API responses, and logs. The Docker socket itself grants host-administrator-equivalent power; only trusted operators may reach the API. 4. **Deployment metadata in a public image:** server URL and app host are non-secret labels and opt-in is explicit. Confirm these stable names (`ino.deploy.server`, `ino.deploy.host`) are preferable to environment-only target selection before release-client implementation. 5. **Patch and output limits:** omitted settings preserve; supplied nested settings replace the section; exec/log output is capped at 1 MiB and logs at 500 lines. Confirm these semantics are sufficient for external management clients.