diff --git a/docs/superpowers/plans/2026-11-14-vps-cloudflared.md b/docs/superpowers/plans/2026-11-14-vps-cloudflared.md new file mode 100644 index 00000000..551e6285 --- /dev/null +++ b/docs/superpowers/plans/2026-11-14-vps-cloudflared.md @@ -0,0 +1,121 @@ +# VPS over Cloudflare Tunnel Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A saved VPS can be marked "via Cloudflare Tunnel" and every VPS feature (Test, metrics, processes, `vps_run`, upload/download) works over it. + +**Architecture:** `internal/vps.dial` gets its `net.Conn` from a transport switch: direct TCP (today) or a WebSocket to `wss:///` carrying SSH in binary frames, the same protocol `cloudflared access ssh` speaks. Three new `vps_hosts` columns (migration v4) hold the mode and an optional Access service token (secret encrypted at rest). The API, agent tool and dashboard dialog pass the fields through. + +**Tech Stack:** Go (`golang.org/x/crypto/ssh`, `golang.org/x/net/websocket`, already in `go.mod`), SQLite/Postgres migrations, React + TypeScript (Vite, bun). + +**Spec:** `docs/superpowers/specs/2026-11-14-vps-cloudflared-design.md` + +## Global Constraints + +- No new Go or npm dependencies. +- Tunnel mode value is exactly `"cloudflared"`; empty string means direct SSH. Anything else is stored as `""`. +- Tunnel dial: `wss:///`, origin `https://`, header `User-Agent: antares`, `PayloadType = websocket.BinaryFrame`, 20s dial timeout, ctx cancellation honoured. Port is ignored in tunnel mode. +- Headers `Cf-Access-Client-Id` / `Cf-Access-Client-Secret` are sent only when non-empty. +- `cf_client_secret` is encrypted at rest with the store's secret box and is never returned by the API (only `has_cf_secret`). +- Refused upgrade error text: `cloudflare refused the tunnel connection to : if the hostname is protected by Cloudflare Access add a service token; otherwise check that the tunnel routes it to ssh://localhost:22`. +- Host-key TOFU behaviour is unchanged in both modes. +- Tests must not touch the real `~/.antares/.secretkey`: inject a box built with `secret.NewBox`. + +## Review Focus + +1. Editing a tunnel host with the Client Secret left blank keeps the stored secret → `TestKeepStoredSecretsKeepsBlankCFSecret` (Task 3). +2. Pasting `https://ssh.example.com/` as the hostname saves `ssh.example.com` → `TestVPSFromBodyNormalizesTunnelHost` (Task 3). +3. A tunnel endpoint that accepts TCP but never answers must time out, not hang → `TestTunnelDialHonoursContext` (Task 2). +4. TOFU still works over the tunnel: Ping returns the presented host key → asserted in `TestPingOverCloudflaredTunnel` (Task 2). +5. Rows saved without a tunnel stay direct after the migration → `TestVPSHostDefaultsToDirect` (Task 1). + +--- + +### Task 1: Store columns (migration v4) + +**Files:** +- Modify: `internal/store/migrations.go` (add `vpsTunnelV4` next to `devicesV3`) +- Modify: `internal/store/migrate.go:22-40` (register v4, extend doc comment) +- Modify: `internal/store/types.go:111-131` (`VPSHost`) +- Modify: `internal/store/vps.go` (cols, put, scan, decrypt) +- Test: `internal/store/vps_test.go` (new) + +**Interfaces:** +- Produces: `store.VPSHost` fields `Tunnel string \`json:"tunnel"\``, `CFClientID string \`json:"cf_client_id,omitempty"\``, `CFClientSecret string \`json:"cf_client_secret,omitempty"\``. + +- [ ] **Step 1: Write the failing tests** in `internal/store/vps_test.go`. Helper `newVPSTestStore(t) *sqlStore`: `newTestStore(t).(*sqlStore)`, then `ss.boxOnce.Do(func(){ ss.box, ss.boxErr = secret.NewBox(bytes.Repeat([]byte{7}, 32)) })`. + - `TestVPSHostTunnelFieldsRoundTrip`: Put `{ID:"vps_t", Host:"ssh.example.com", Tunnel:"cloudflared", CFClientID:"abc.access", CFClientSecret:"s3cret", AuthMethod:"password", Password:"pw"}`; Get returns the same three values; `SELECT cf_client_secret FROM vps_hosts WHERE id='vps_t'` is non-empty and `!= "s3cret"`. Put again with `CFClientSecret:"new"` → Get returns `"new"` (conflict-update set includes the new columns). + - `TestVPSHostDefaultsToDirect`: Put `{ID:"vps_d", Host:"1.2.3.4", Password:"pw"}` → Get `.Tunnel == ""`, `.CFClientID == ""`, `.CFClientSecret == ""`. +- [ ] **Step 2: Run** `go test ./internal/store/ -run 'VPSHost' -v` → FAIL (unknown fields). +- [ ] **Step 3: Implement.** `vpsTunnelV4` = three statements: `ALTER TABLE vps_hosts ADD COLUMN tunnel TEXT NOT NULL DEFAULT ''`, `... cf_client_id TEXT NOT NULL DEFAULT ''`, `... cf_client_secret TEXT NOT NULL DEFAULT ''`. Register `{version: 4, statements: append([]string(nil), vpsTunnelV4...)}`. Append `tunnel,cf_client_id,cf_client_secret` to `vpsCols` (keep `created_at,updated_at` last or update placeholders consistently), encrypt `CFClientSecret` in `PutVPSHost`, add the three columns to the `onConflict` update set, scan and decrypt them. +- [ ] **Step 4: Run** `go test ./internal/store/ -v` → PASS, including every `Migrat*` test (ledger counts derive from `baselineMigrations`, so they absorb v4). +- [ ] **Step 5: Commit** `git add internal/store && git commit -m "store: vps_hosts tunnel and Access service token columns (migration v4)"` + +### Task 2: Tunnel transport in `internal/vps` + +**Files:** +- Create: `internal/vps/tunnel.go` +- Modify: `internal/vps/vps.go:19-42` (Target, endpoint), `:87-111` (dial uses transport) +- Test: `internal/vps/tunnel_test.go` (new) + +**Interfaces:** +- Produces: `const TunnelCloudflared = "cloudflared"`; `Target` fields `Tunnel, CFClientID, CFClientSecret string`; `func NormalizeTunnelHost(s string) string`; `var ErrTunnelRefused error`; unexported `func dialTransport(ctx context.Context, t Target) (net.Conn, error)`, `func (t Target) endpoint() string` (`wss://host` in tunnel mode, else `addr()`), and test seam `var tunnelEndpoint = func(host string) (location, origin string)` defaulting to `("wss://"+host+"/", "https://"+host)`. + +- [ ] **Step 1: Write the failing tests** in `internal/vps/tunnel_test.go`. Helper `newTunnelBridge(t, sshAddr string) (host string, got *http.Header)`: `httptest.NewServer(websocket.Server{Handshake: record r.Header into *got; return nil, Handler: set PayloadType=BinaryFrame, net.Dial sshAddr, copy both ways until either side closes})`; override `tunnelEndpoint` to `ws:///` + `http://` and restore with `t.Cleanup`. + - `TestRunOverCloudflaredTunnel`: `newTestSSHServer` with `execOutput "tunnel-ok\n"`; target = `srv.target()` with `Tunnel: TunnelCloudflared, Host: bridgeHost, Port: 1`; `Run(ctx, target, "whoami")` → out `"tunnel-ok\n"`, err nil. + - `TestPingOverCloudflaredTunnel`: Ping over the bridge → err nil, `seenHostKey` starts with `"ssh-"`. + - `TestTunnelSendsAccessHeaders`: with `CFClientID:"abc.access", CFClientSecret:"s3cret"` → recorded `Cf-Access-Client-Id == "abc.access"`, `Cf-Access-Client-Secret == "s3cret"`, `User-Agent` contains `"antares"`; a second Ping with both empty → both headers `== ""`. + - `TestTunnelRefusedIsReadable`: tunnel endpoint at an `httptest` server answering every request `403` → Ping err; `errors.Is(err, ErrTunnelRefused)`; `strings.Contains(err.Error(), "service token")`. + - `TestTunnelDialHonoursContext`: endpoint at a raw `net.Listen` that accepts and never writes; ctx 300ms → Ping returns within 2s; `errors.Is(err, ErrTimeout)`. + - `TestNormalizeTunnelHost`: `"https://ssh.example.com/"`, `"ssh://ssh.example.com"`, `"wss://ssh.example.com/x/y"`, `" ssh.example.com "`, `"ssh.example.com"` → all `"ssh.example.com"`. + - `TestLiveCloudflaredBanner`: `t.Skip` unless env `ANTARES_LIVE_TUNNEL_HOST` is set; `dialTransport` with that host in tunnel mode, read until `\n` within 15s, assert prefix `"SSH-2.0-"`. Sends no credentials. +- [ ] **Step 2: Run** `go test ./internal/vps/ -run 'Tunnel|Cloudflared' -v` → FAIL (undefined). +- [ ] **Step 3: Implement** `dialTransport`: direct → existing `net.Dialer{Timeout: 20s}.DialContext(ctx, "tcp", t.addr())`; tunnel → `websocket.NewConfig(tunnelEndpoint(host))`, headers per Global Constraints, `Dialer = &net.Dialer{Timeout: 20 * time.Second}`, `DialContext(ctx)`; map `errors.Is(err, websocket.ErrBadStatus)` to the refused error (wrapping `ErrTunnelRefused`), set `PayloadType = websocket.BinaryFrame`. In `dial`, call `dialTransport` and use `t.endpoint()` in every error message and as the `ssh.NewClientConn` address; the existing ctx-timeout wrapping with `ErrTimeout` stays. +- [ ] **Step 4: Run** `go test ./internal/vps/ -v` → PASS (old tests unchanged; live test SKIP). +- [ ] **Step 5: Commit** `git add internal/vps && git commit -m "vps: dial over Cloudflare Tunnel (cloudflared WebSocket carrier)"` + +### Task 3: API and agent tool + +**Files:** +- Modify: `internal/server/handlers_vps.go` (body, view, save, test, targetFor) +- Modify: `internal/tools/vps.go:42-48` (`targetFromHost`), `formatVPSList` +- Modify: `docs/tools.md:72-78` (one paragraph on tunnel hosts) +- Test: `internal/server/handlers_vps_test.go` (new), `internal/tools/vps_list_test.go` (new) + +**Interfaces:** +- Consumes: Task 1 fields; Task 2 `vps.TunnelCloudflared`, `vps.NormalizeTunnelHost`, `Target` fields. +- Produces: `vpsBody` JSON fields `tunnel`, `cf_client_id`, `cf_client_secret`; view fields `tunnel`, `cf_client_id`, `has_cf_secret`; helpers `func vpsFromBody(body vpsBody) *store.VPSHost` and `func keepStoredSecrets(v, prev *store.VPSHost)`. + +- [ ] **Step 1: Write the failing tests.** + - `TestVPSFromBodyNormalizesTunnelHost`: body `{Host:"https://ssh.example.com/", Tunnel:"cloudflared"}` → `Host == "ssh.example.com"`, `Tunnel == "cloudflared"`, `Username == "root"`, `Label == "ssh.example.com"`. + - `TestVPSFromBodyUnknownTunnelIsDirect`: `Tunnel:"bogus"` → `Tunnel == ""`; direct-mode host is only trimmed, not normalized. + - `TestKeepStoredSecretsKeepsBlankCFSecret`: prev `{CFClientSecret:"old", Password:"pw", CreatedAt:t0}`, v with blanks → v gets `"old"`, `"pw"`, `t0`; v with `CFClientSecret:"new"` keeps `"new"`. + - `TestVPSViewHidesCFSecret`: view of `{CFClientSecret:"s3cret", CFClientID:"abc", Tunnel:"cloudflared"}` has `has_cf_secret == true`, `cf_client_id == "abc"`, `tunnel == "cloudflared"`, and no value anywhere equals `"s3cret"`. + - `TestTargetForMapsTunnel`: `targetFor` copies `Tunnel`, `CFClientID`, `CFClientSecret`. + - `TestFormatVPSListShowsCloudflared` (tools): tunnel host line contains `via cloudflared` and no `:22`; direct host line still `user@host:port`. +- [ ] **Step 2: Run** `go test -run 'VPS|TargetFor|FormatVPSList' -v ./internal/server/ ./internal/tools/` → FAIL. +- [ ] **Step 3: Implement.** `handleSaveVPS` = `vpsFromBody` + (on edit) `keepStoredSecrets`. `handleTestVPS`: build `v := vpsFromBody(body)`; with an id, load prev, `keepStoredSecrets(v, prev)`, `v.HostKey = prev.HostKey`, so Test checks what the form shows; pin onto prev as today. `targetFor`/`targetFromHost` map the three fields. `formatVPSList` prints `user@host via cloudflared` for tunnel hosts. Docs: tunnel hosts use the tunnel hostname, need no cloudflared install, optional service token. +- [ ] **Step 4: Run** `go test ./internal/server/ ./internal/tools/ -v` → PASS. +- [ ] **Step 5: Commit** `git add internal/server internal/tools docs/tools.md && git commit -m "server: VPS API and vps tools accept Cloudflare Tunnel hosts"` + +### Task 4: Dashboard dialog + +**Files:** +- Modify: `web/src/pages/VPSPage.tsx` (`VPSHost` type :35-44, card :188, `VPSDialog` :398-596) +- Modify: `web/src/lib/i18n.tsx` (en keys after `'vps.passphrasePh'`), `web/src/lib/locales/{id,ja,ru,zh}.ts` + +**Interfaces:** +- Consumes: Task 3 JSON fields. + +- [ ] **Step 1: Add i18n keys** (en / id): `vps.connection` Connection / Koneksi; `vps.connDirect` Direct SSH / SSH langsung; `vps.connCloudflared` Cloudflare Tunnel (cloudflared) / same; `vps.tunnelHost` Tunnel hostname / Hostname tunnel; `vps.tunnelHint` "Same hostname as --hostname in your cloudflared ProxyCommand." / "Hostname yang sama dengan --hostname di ProxyCommand cloudflared-mu."; `vps.cfToken` "Cloudflare Access service token (optional)" / "Service token Cloudflare Access (opsional)"; `vps.cfTokenHint` "Only needed if this hostname is protected by Cloudflare Access." / "Hanya perlu kalau hostname ini dilindungi Cloudflare Access."; `vps.cfClientId` Client ID; `vps.cfClientSecret` Client Secret; `vps.viaCloudflared` cloudflared. Translate the same keys into ja/ru/zh. +- [ ] **Step 2: Dialog.** `VPSHost` gains `tunnel?: string`, `cf_client_id?: string`, `has_cf_secret?: boolean`. State `tunnel`, `cfClientId`, `cfClientSecret`, reset on open like the others (secret always reset to `''`). A "Connection" select (styled like the auth select) right after Label. Tunnel mode: host label `vps.tunnelHost`, placeholder `ssh.example.com`, Port field hidden, hint `vps.tunnelHint` under it, and a service-token block (`vps.cfToken` heading, `vps.cfTokenHint`, Client ID input, Client Secret password input with `••••••••` placeholder when `has_cf_secret` on edit). `body()` sends `tunnel`, and the token fields only in tunnel mode (`''` otherwise). +- [ ] **Step 3: Card.** Tunnel hosts render `{username}@{host}` plus a small tag `vps.viaCloudflared` instead of `:{port}`. +- [ ] **Step 4: Verify** `cd web && bun run typecheck` → no errors; `bun test` → PASS. +- [ ] **Step 5: Look at it.** Run the dashboard, open Add server, switch Connection both ways: the Port field and the token block toggle, and the card shows the tag after saving a tunnel host. +- [ ] **Step 6: Commit** `git add web/src && git commit -m "web: Cloudflare Tunnel option in the VPS dialog"` + +### Task 5: Whole-branch verification + +- [ ] **Step 1:** `go vet ./... && go test ./...` → PASS. +- [ ] **Step 2:** Live smoke (no credentials): `ANTARES_LIVE_TUNNEL_HOST= go test ./internal/vps/ -run TestLiveCloudflaredBanner -v` → PASS with an `SSH-2.0-` banner. +- [ ] **Step 3:** `cd web && bun run build` → succeeds (do not commit build output unless it is already tracked). diff --git a/docs/superpowers/specs/2026-11-14-vps-cloudflared-design.md b/docs/superpowers/specs/2026-11-14-vps-cloudflared-design.md new file mode 100644 index 00000000..3bb3bdda --- /dev/null +++ b/docs/superpowers/specs/2026-11-14-vps-cloudflared-design.md @@ -0,0 +1,136 @@ +# VPS over Cloudflare Tunnel (cloudflared): design + +Date: 2026-11-14 · Size: small change (short design) + +## Intent + +Some servers expose SSH only through a Cloudflare Tunnel: port 22 is closed to +the internet, and people reach the box with an ssh config like + +``` +Host vps-example + HostName ssh.example.com + User root + ProxyCommand cloudflared access ssh --hostname %h +``` + +Antares dials `host:port` over raw TCP today, so such a server cannot be added +on the VPS page. The goal: a saved VPS can be marked "via Cloudflare Tunnel", +and every VPS feature (Test button, metrics, process list, agent `vps_run`, +file upload/download) works against it unchanged. + +## Goals / non-goals / anti-goals + +- Goal: connect to a tunnel hostname such as `ssh.example.com` with no extra + software on the machine running Antares (Docker, another VPS, Windows, + desktop app). +- Goal: optional Cloudflare Access **service token** (Client ID + Secret) for + hostnames protected by Access. Empty for hosts with no Access policy. +- Non-goal: interactive Access login (browser). A background agent cannot do + it; a service token is the supported path. +- Non-goal: HTTP(S) proxy support for the WebSocket dial (`HTTPS_PROXY`). +- Non-goal: a free-form ProxyCommand field. +- Anti-goal: weakening host-key pinning (TOFU) or storing the service-token + secret in the clear. + +## Approaches + +1. **Native WebSocket bridge in Go (picked).** Antares opens + `wss:///` itself and runs SSH over binary frames, exactly what + `cloudflared access ssh` does internally (verified in cloudflared's + `carrier/websocket.go` and `cmd/cloudflared/access/carrier.go`: GET upgrade + to the hostname, binary frames, `User-Agent`, optional + `Cf-Access-Client-Id` / `Cf-Access-Client-Secret`). Uses + `golang.org/x/net/websocket`, already in `go.mod`: no new dependency. + Trade-off: if Cloudflare changes the carrier protocol, our code must follow. +2. **Spawn `cloudflared access ssh --hostname …` and pipe its stdio.** Identical + to the user's laptop, but requires cloudflared wherever Antares runs, and + the metrics poll would spawn many short-lived processes. +3. **Free-form ProxyCommand field.** Dropped: a dashboard field that runs any + local command, and it still needs cloudflared installed. + +The user picked approach 1. + +## Design + +**Data.** Migration v4 adds three columns to `vps_hosts`: + +- `tunnel TEXT NOT NULL DEFAULT ''`: `''` = direct SSH (today's behavior), + `'cloudflared'` = Cloudflare Tunnel. +- `cf_client_id TEXT NOT NULL DEFAULT ''`: the service token's Client ID, which + is an identifier, not a secret. +- `cf_client_secret TEXT NOT NULL DEFAULT ''`: encrypted at rest with the same + secret box as password/key. + +`store.VPSHost` and `vps.Target` gain `Tunnel`, `CFClientID`, `CFClientSecret`. +Existing rows default to direct, so nothing changes for current users. + +**Dial (`internal/vps`).** `dial` stops calling `net.Dialer` directly and asks +the target for its transport: + +- direct: unchanged TCP dial to `host:port`. +- cloudflared: WebSocket dial to `wss:///` (port 443; the saved Port is + ignored), with a 20s dial timeout and ctx cancellation, + `PayloadType = BinaryFrame`, `User-Agent: antares`, plus the two + `Cf-Access-*` headers when set. The resulting `*websocket.Conn` is a + `net.Conn`, so the SSH handshake, TOFU host-key check, keepalive, Run, + transfers and metrics run on it unchanged. + +A rejected upgrade surfaces as a readable error that wraps `ErrTunnelRefused` +and names the HTTP status. The wording follows the status class: +401/403 or a redirect to an Access login says the hostname is protected by +Cloudflare Access (add or check the service token); 502/503/504/530 says the +tunnel is offline (check that cloudflared is running on the server); any other +status says the hostname is not routed to SSH (check the ingress for +`ssh://localhost:22`). x/net discards the status, so the upgrade is performed +over a connection that records the start of the response. + +Hostname input is normalized in cloudflared mode: a leading `https://`, +`wss://` or `ssh://` and any trailing `/` or path are stripped. + +**API (`internal/server/handlers_vps.go`).** `vpsBody` accepts `tunnel`, +`cf_client_id`, `cf_client_secret`. Save keeps a blank secret on edit (same +rule as password/key). `vpsView` returns `tunnel`, `cf_client_id` and +`has_cf_secret`, never the secret. `/vps/test` tests what the form shows, +including a just-typed secret override. Stored secrets and the pinned host key +are only used while the form still points at the saved address; once the +address changes, only typed credentials are sent, nothing is pinned, and a +blank password/key is refused, so a dashboard session cannot redirect a saved +host's secrets to another server. `tools/vps.go` `targetFromHost` maps +the new fields; the agent's server list shows "via cloudflared". + +**Dashboard (`web/src/pages/VPSPage.tsx`).** The add/edit dialog gets a +"Connection" select: "Direct SSH" / "Cloudflare Tunnel (cloudflared)". In +tunnel mode: + +``` +Connection [ Cloudflare Tunnel (cloudflared) v ] +Hostname [ ssh.example.com ] (no Port field) + Same hostname as --hostname in your cloudflared ProxyCommand. +Username [ root ] Auth method [ Key v ] +... +Cloudflare Access service token (optional) +Client ID [ ] +Client Secret [ •••••••• ] (blank on edit = keep) +``` + +The host card shows a small "cloudflared" tag. New strings go into the English +defaults (`i18n.tsx`) and the id/ja/ru/zh locale files. + +## Verification + +- Go unit test: an `httptest` WebSocket server bridging to the existing + in-process test SSH server; `Run` and `Ping` succeed over the tunnel + transport, and the test asserts the `Cf-Access-*` headers arrive when set + and are absent when empty. +- Go unit test: a non-101 upgrade response yields the readable error. +- Store test: round-trip of the new fields with the secret encrypted at rest. +- Migration tests stay green with v4 in the registry. +- Live smoke check against the user's real tunnel hostname: dial over the new + transport and read only the server's SSH banner (no credentials, no login). +- Web: typecheck/build, then a look at the dialog in both modes. + +## Left to the builder + +Exact component layout inside the dialog, wording of hints in each locale, and +test helper structure. diff --git a/docs/tools.md b/docs/tools.md index de32372b..f3b6ad77 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -81,6 +81,12 @@ Default command timeout is 120 seconds (raise `timeout_seconds` up to 900 for `systemctl restart` / upgrades). Transfers are capped at 256 MiB. Credentials stay encrypted at rest; host keys are pinned on first connect (TOFU). +A server can instead be reached through a Cloudflare Tunnel: pick "Cloudflare Tunnel +(cloudflared)" in the VPS dialog's Connection select and use the tunnel's public +hostname as the host (the port is ignored). No `cloudflared` install is needed on the Antares side; an optional +Cloudflare Access service token (client ID and secret) covers protected +hostnames. The token secret is encrypted at rest and never returned by the API. + ### Web | Tool | What it does | diff --git a/internal/server/handlers_vps.go b/internal/server/handlers_vps.go index 2cee687c..b8c60f59 100644 --- a/internal/server/handlers_vps.go +++ b/internal/server/handlers_vps.go @@ -23,6 +23,7 @@ func targetFor(v *store.VPSHost) vps.Target { Host: v.Host, Port: v.Port, Username: v.Username, AuthMethod: v.AuthMethod, Password: v.Password, PrivateKey: v.PrivateKey, Passphrase: v.Passphrase, KnownHostKey: v.HostKey, + Tunnel: v.Tunnel, CFClientID: v.CFClientID, CFClientSecret: v.CFClientSecret, } } @@ -42,16 +43,19 @@ func (s *Server) pinHostKey(ctx context.Context, v *store.VPSHost, seen string) // saying whether a password / key is on file. func vpsView(v store.VPSHost) map[string]any { return map[string]any{ - "id": v.ID, - "label": v.Label, - "host": v.Host, - "port": v.Port, - "username": v.Username, - "auth_method": v.AuthMethod, - "has_password": v.Password != "", - "has_key": v.PrivateKey != "", - "created_at": v.CreatedAt, - "updated_at": v.UpdatedAt, + "id": v.ID, + "label": v.Label, + "host": v.Host, + "port": v.Port, + "username": v.Username, + "auth_method": v.AuthMethod, + "has_password": v.Password != "", + "has_key": v.PrivateKey != "", + "tunnel": v.Tunnel, + "cf_client_id": v.CFClientID, + "has_cf_secret": v.CFClientSecret != "", + "created_at": v.CreatedAt, + "updated_at": v.UpdatedAt, } } @@ -78,34 +82,34 @@ type vpsBody struct { Password string `json:"password"` PrivateKey string `json:"private_key"` Passphrase string `json:"passphrase"` -} -// handleSaveVPS creates or updates a host. On update, a blank password/key -// keeps the stored one (the client never receives the secret to echo back). -func (s *Server) handleSaveVPS(w http.ResponseWriter, r *http.Request) { - if s.requireDashboardPassword(w, r) { - return - } - var body vpsBody - if err := decodeBody(r, &body); err != nil { - writeError(w, http.StatusBadRequest, err) - return - } - if strings.TrimSpace(body.Host) == "" { - writeError(w, http.StatusBadRequest, errors.New("host is required")) - return - } + Tunnel string `json:"tunnel"` + CFClientID string `json:"cf_client_id"` + CFClientSecret string `json:"cf_client_secret"` +} +// vpsFromBody builds a host record from a request body, applying the form +// defaults. It does not assign an ID. Tunnel mode is "cloudflared" or empty +// (direct SSH); the host is normalized to a bare hostname only in tunnel mode. +func vpsFromBody(body vpsBody) *store.VPSHost { v := &store.VPSHost{ - ID: strings.TrimSpace(body.ID), - Label: strings.TrimSpace(body.Label), - Host: strings.TrimSpace(body.Host), - Port: body.Port, - Username: strings.TrimSpace(body.Username), - AuthMethod: strings.TrimSpace(body.AuthMethod), - Password: body.Password, - PrivateKey: body.PrivateKey, - Passphrase: body.Passphrase, + ID: strings.TrimSpace(body.ID), + Label: strings.TrimSpace(body.Label), + Host: strings.TrimSpace(body.Host), + Port: body.Port, + Username: strings.TrimSpace(body.Username), + AuthMethod: strings.TrimSpace(body.AuthMethod), + Password: body.Password, + PrivateKey: body.PrivateKey, + Passphrase: body.Passphrase, + CFClientID: strings.TrimSpace(body.CFClientID), + CFClientSecret: strings.TrimSpace(body.CFClientSecret), + } + if strings.TrimSpace(body.Tunnel) == vps.TunnelCloudflared { + v.Tunnel = vps.TunnelCloudflared + v.Host = vps.NormalizeTunnelHost(v.Host) + } else { + v.CFClientID, v.CFClientSecret = "", "" } if v.Username == "" { v.Username = "root" @@ -120,24 +124,86 @@ func (s *Server) handleSaveVPS(w http.ResponseWriter, r *http.Request) { if v.Label == "" { v.Label = v.Host } + return v +} + +// keepStoredSecrets fills blank secrets on v from the stored record, so a round +// trip through the masked view never wipes them. +func keepStoredSecrets(v, prev *store.VPSHost) { + v.CreatedAt = prev.CreatedAt + if v.Password == "" { + v.Password = prev.Password + } + if v.PrivateKey == "" { + v.PrivateKey = prev.PrivateKey + } + if v.Passphrase == "" { + v.Passphrase = prev.Passphrase + } + // The Access secret is only meaningful beside its Client ID: clearing the ID + // (or leaving tunnel mode) drops the token. + if v.CFClientSecret == "" && v.Tunnel == vps.TunnelCloudflared && v.CFClientID != "" { + v.CFClientSecret = prev.CFClientSecret + } +} + +// sameEndpoint reports whether a and b dial the same place. In tunnel mode the +// port is ignored; a zero port means the default 22. +func sameEndpoint(a, b *store.VPSHost) bool { + return a.Host == b.Host && a.Tunnel == b.Tunnel && (a.Tunnel != "" || sshPort(a.Port) == sshPort(b.Port)) +} + +func sshPort(p int) int { + if p == 0 { + return 22 + } + return p +} + +// errAddressChanged is returned when a saved host is tested at a different +// address without typing its credentials again. +var errAddressChanged = errors.New("the address changed: enter the password or key again to test it (saved credentials are only sent to the saved server)") +// applySavedForTest decides what a Test of a saved host may borrow from the +// stored record. While the form still points at the saved endpoint it fills +// blank secrets and the pinned host key from prev, and returns prev as the +// record to pin onto. Once the address changed, nothing stored leaves home: +// only what the form carries is used, no key is pinned (a fresh TOFU check), +// and a missing password/key is errAddressChanged. Without this a dashboard +// session could point a saved host at any server and receive its secrets. +func applySavedForTest(v, prev *store.VPSHost) (pinTo *store.VPSHost, err error) { + if sameEndpoint(v, prev) { + keepStoredSecrets(v, prev) + v.HostKey = prev.HostKey + return prev, nil + } + v.HostKey = "" + if (v.AuthMethod == "key" && v.PrivateKey == "") || (v.AuthMethod != "key" && v.Password == "") { + return nil, errAddressChanged + } + return nil, nil +} + +// handleSaveVPS creates or updates a host. On update, a blank password/key +// keeps the stored one (the client never receives the secret to echo back). +func (s *Server) handleSaveVPS(w http.ResponseWriter, r *http.Request) { + if s.requireDashboardPassword(w, r) { + return + } + var body vpsBody + if err := decodeBody(r, &body); err != nil { + writeError(w, http.StatusBadRequest, err) + return + } + v := vpsFromBody(body) + if v.Host == "" { + writeError(w, http.StatusBadRequest, errors.New("host is required")) + return + } if v.ID == "" { v.ID = "vps_" + randHex(6) - } else { - // Editing: preserve secrets left blank so a round trip through the masked - // view never wipes them. - if prev, err := s.db.GetVPSHost(r.Context(), v.ID); err == nil { - v.CreatedAt = prev.CreatedAt - if v.Password == "" { - v.Password = prev.Password - } - if v.PrivateKey == "" { - v.PrivateKey = prev.PrivateKey - } - if v.Passphrase == "" { - v.Passphrase = prev.Passphrase - } - } + } else if prev, err := s.db.GetVPSHost(r.Context(), v.ID); err == nil { + keepStoredSecrets(v, prev) } if err := s.db.PutVPSHost(r.Context(), v); err != nil { @@ -165,34 +231,24 @@ func (s *Server) handleTestVPS(w http.ResponseWriter, r *http.Request) { var body vpsBody _ = decodeBody(r, &body) - var t vps.Target - var saved *store.VPSHost // set only when testing a stored host, so we can pin - if id := strings.TrimSpace(body.ID); id != "" { - v, err := s.db.GetVPSHost(r.Context(), id) + v := vpsFromBody(body) + if v.Host == "" { + writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "host is required"}) + return + } + var saved *store.VPSHost // set only when testing a stored host at its saved address, so we can pin + if v.ID != "" { + prev, err := s.db.GetVPSHost(r.Context(), v.ID) if err != nil { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "host not found"}) return } - saved = v - t = targetFor(v) - // Allow overriding a just-typed secret before saving. - if body.Password != "" { - t.Password = body.Password - } - if body.PrivateKey != "" { - t.PrivateKey = body.PrivateKey - } - } else { - t = vps.Target{ - Host: strings.TrimSpace(body.Host), Port: body.Port, - Username: strings.TrimSpace(body.Username), AuthMethod: strings.TrimSpace(body.AuthMethod), - Password: body.Password, PrivateKey: body.PrivateKey, Passphrase: body.Passphrase, + if saved, err = applySavedForTest(v, prev); err != nil { + writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()}) + return } } - if t.Host == "" { - writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "host is required"}) - return - } + t := targetFor(v) ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() diff --git a/internal/server/handlers_vps_test.go b/internal/server/handlers_vps_test.go new file mode 100644 index 00000000..a4063a02 --- /dev/null +++ b/internal/server/handlers_vps_test.go @@ -0,0 +1,166 @@ +package server + +import ( + "errors" + "testing" + "time" + + "github.com/enowdev/antares/internal/store" +) + +func TestVPSFromBodyNormalizesTunnelHost(t *testing.T) { + v := vpsFromBody(vpsBody{Host: "https://ssh.example.com/", Tunnel: "cloudflared"}) + if v.Host != "ssh.example.com" || v.Tunnel != "cloudflared" || v.Username != "root" || v.Label != "ssh.example.com" { + t.Fatalf("unexpected host: %+v", v) + } +} + +func TestVPSFromBodyUnknownTunnelIsDirect(t *testing.T) { + v := vpsFromBody(vpsBody{Host: " https://ssh.example.com/ ", Tunnel: "bogus"}) + if v.Tunnel != "" { + t.Fatalf("tunnel = %q, want empty", v.Tunnel) + } + if v.Host != "https://ssh.example.com/" { + t.Fatalf("direct host should only be trimmed, got %q", v.Host) + } +} + +func TestKeepStoredSecretsKeepsBlankCFSecret(t *testing.T) { + t0 := time.Unix(1000, 0) + prev := &store.VPSHost{CFClientSecret: "old", Password: "pw", CreatedAt: t0} + v := &store.VPSHost{Tunnel: "cloudflared", CFClientID: "id"} + keepStoredSecrets(v, prev) + if v.CFClientSecret != "old" || v.Password != "pw" || !v.CreatedAt.Equal(t0) { + t.Fatalf("blank secrets not kept: %+v", v) + } + v2 := &store.VPSHost{Tunnel: "cloudflared", CFClientID: "id", CFClientSecret: "new"} + keepStoredSecrets(v2, prev) + if v2.CFClientSecret != "new" { + t.Fatalf("explicit secret overwritten: %q", v2.CFClientSecret) + } +} + +func TestKeepStoredSecretsCFRules(t *testing.T) { + prev := &store.VPSHost{Tunnel: "cloudflared", CFClientID: "id", CFClientSecret: "old"} + // tunnel, Client ID kept, secret blank: keep stored secret + v := &store.VPSHost{Tunnel: "cloudflared", CFClientID: "id"} + keepStoredSecrets(v, prev) + if v.CFClientSecret != "old" { + t.Errorf("secret not kept: %q", v.CFClientSecret) + } + // tunnel, Client ID cleared: secret dropped + v = &store.VPSHost{Tunnel: "cloudflared"} + keepStoredSecrets(v, prev) + if v.CFClientSecret != "" { + t.Errorf("secret survived cleared Client ID: %q", v.CFClientSecret) + } + // direct mode: nothing carried over + v = vpsFromBody(vpsBody{Host: "1.2.3.4", CFClientID: "id", CFClientSecret: "sec"}) + keepStoredSecrets(v, prev) + if v.CFClientID != "" || v.CFClientSecret != "" { + t.Errorf("direct mode kept CF fields: %+v", v) + } +} + +func TestVPSFromBodyEmptyTunnelHost(t *testing.T) { + if v := vpsFromBody(vpsBody{Host: "https://", Tunnel: "cloudflared"}); v.Host != "" { + t.Fatalf("Host = %q", v.Host) + } +} + +func TestSameEndpoint(t *testing.T) { + cases := []struct { + name string + a, b store.VPSHost + want bool + }{ + {"identical direct", store.VPSHost{Host: "h", Port: 22}, store.VPSHost{Host: "h", Port: 22}, true}, + {"port differs", store.VPSHost{Host: "h", Port: 22}, store.VPSHost{Host: "h", Port: 2222}, false}, + {"host differs", store.VPSHost{Host: "h", Port: 22}, store.VPSHost{Host: "g", Port: 22}, false}, + {"tunnel vs direct", store.VPSHost{Host: "h", Tunnel: "cloudflared"}, store.VPSHost{Host: "h"}, false}, + {"tunnel ports ignored", store.VPSHost{Host: "h", Tunnel: "cloudflared", Port: 1}, store.VPSHost{Host: "h", Tunnel: "cloudflared", Port: 22}, true}, + } + for _, c := range cases { + if got := sameEndpoint(&c.a, &c.b); got != c.want { + t.Errorf("%s: got %v", c.name, got) + } + } +} + +func TestVPSViewHidesCFSecret(t *testing.T) { + m := vpsView(store.VPSHost{CFClientSecret: "s3cret", CFClientID: "abc", Tunnel: "cloudflared"}) + if m["has_cf_secret"] != true || m["cf_client_id"] != "abc" || m["tunnel"] != "cloudflared" { + t.Fatalf("bad view: %+v", m) + } + for k, val := range m { + if val == "s3cret" { + t.Fatalf("secret leaked in %q", k) + } + } +} + +func TestTargetForMapsTunnel(t *testing.T) { + tg := targetFor(&store.VPSHost{Tunnel: "cloudflared", CFClientID: "id", CFClientSecret: "sec"}) + if tg.Tunnel != "cloudflared" || tg.CFClientID != "id" || tg.CFClientSecret != "sec" { + t.Fatalf("bad target: %+v", tg) + } +} + +func TestApplySavedForTestSameEndpointUsesSavedSecrets(t *testing.T) { + prev := &store.VPSHost{ID: "vps_1", Host: "1.2.3.4", Port: 22, Password: "pw", HostKey: "ssh-ed25519 AAAA"} + v := &store.VPSHost{ID: "vps_1", Host: "1.2.3.4", Port: 22, AuthMethod: "password"} + pinTo, err := applySavedForTest(v, prev) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if pinTo != prev { + t.Fatalf("pinTo = %v, want the saved record", pinTo) + } + if v.Password != "pw" || v.HostKey != "ssh-ed25519 AAAA" { + t.Fatalf("saved secret/host key not used: %+v", v) + } +} + +func TestApplySavedForTestChangedAddressKeepsSavedSecretsHome(t *testing.T) { + prev := &store.VPSHost{ID: "vps_1", Host: "1.2.3.4", Port: 22, Password: "pw", PrivateKey: "KEY", Passphrase: "pp", + Tunnel: "cloudflared", CFClientID: "abc", CFClientSecret: "cfs", HostKey: "ssh-ed25519 AAAA"} + v := &store.VPSHost{ID: "vps_1", Host: "evil.example.com", Port: 22, AuthMethod: "password", Tunnel: "cloudflared", CFClientID: "abc"} + pinTo, err := applySavedForTest(v, prev) + if !errors.Is(err, errAddressChanged) { + t.Fatalf("err = %v, want errAddressChanged", err) + } + if pinTo != nil { + t.Fatal("must not pin onto the saved record for a different address") + } + if v.Password != "" || v.PrivateKey != "" || v.Passphrase != "" || v.CFClientSecret != "" || v.HostKey != "" { + t.Fatalf("saved secrets leaked into a changed-address test: %+v", v) + } +} + +func TestApplySavedForTestChangedAddressWithTypedSecret(t *testing.T) { + prev := &store.VPSHost{ID: "vps_1", Host: "1.2.3.4", Port: 22, Password: "pw", CFClientSecret: "cfs", HostKey: "ssh-ed25519 AAAA"} + v := &store.VPSHost{ID: "vps_1", Host: "5.6.7.8", Port: 22, AuthMethod: "password", Password: "typed"} + pinTo, err := applySavedForTest(v, prev) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if pinTo != nil || v.HostKey != "" { + t.Fatalf("changed address must run a fresh TOFU check: pinTo=%v hostKey=%q", pinTo, v.HostKey) + } + if v.Password != "typed" || v.CFClientSecret != "" { + t.Fatalf("only typed secrets may be used: %+v", v) + } + + k := &store.VPSHost{ID: "vps_1", Host: "5.6.7.8", Port: 22, AuthMethod: "key", Password: "typed-but-key-auth"} + if _, err := applySavedForTest(k, prev); !errors.Is(err, errAddressChanged) { + t.Fatalf("key auth without a typed key: err = %v, want errAddressChanged", err) + } +} + +func TestApplySavedForTestPortZeroIsDefault(t *testing.T) { + prev := &store.VPSHost{ID: "vps_1", Host: "1.2.3.4", Port: 22, Password: "pw"} + v := &store.VPSHost{ID: "vps_1", Host: "1.2.3.4", Port: 0, AuthMethod: "password"} + if _, err := applySavedForTest(v, prev); err != nil || v.Password != "pw" { + t.Fatalf("port 0 should mean the default 22: err=%v password=%q", err, v.Password) + } +} diff --git a/internal/store/migrate.go b/internal/store/migrate.go index 829c9018..b7b18eeb 100644 --- a/internal/store/migrate.go +++ b/internal/store/migrate.go @@ -31,11 +31,15 @@ type migration struct { // // Version 3 adds the devices table (paired clients holding a device token; // see docs/plans/2026-10-02-desktop-contract.md). Identical on both dialects. +// +// Version 4 adds the vps_hosts tunnel columns (tunnel, cf_client_id, +// cf_client_secret) for hosts reached through a Cloudflare Tunnel. func baselineMigrations(dialect string) []migration { return []migration{ {version: 1, statements: baselineV1(dialect)}, {version: 2, statements: baselineV2(dialect)}, {version: 3, statements: append([]string(nil), devicesV3...)}, + {version: 4, statements: append([]string(nil), vpsTunnelV4...)}, } } diff --git a/internal/store/migrations.go b/internal/store/migrations.go index 0d093d33..93b6dd2d 100644 --- a/internal/store/migrations.go +++ b/internal/store/migrations.go @@ -327,3 +327,13 @@ var devicesV3 = []string{ )`, `CREATE INDEX IF NOT EXISTS idx_devices_created ON devices(created_at DESC)`, } + +// vpsTunnelV4 adds the Cloudflare Tunnel columns to vps_hosts: tunnel is "" +// for a direct SSH connection or "cloudflared"; cf_client_id/cf_client_secret +// are the optional Cloudflare Access service token (the secret is encrypted at +// rest by the store). Portable across SQLite and Postgres. +var vpsTunnelV4 = []string{ + `ALTER TABLE vps_hosts ADD COLUMN tunnel TEXT NOT NULL DEFAULT ''`, + `ALTER TABLE vps_hosts ADD COLUMN cf_client_id TEXT NOT NULL DEFAULT ''`, + `ALTER TABLE vps_hosts ADD COLUMN cf_client_secret TEXT NOT NULL DEFAULT ''`, +} diff --git a/internal/store/types.go b/internal/store/types.go index ac153c47..04c58aad 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -122,6 +122,12 @@ type VPSHost struct { Password string `json:"password,omitempty"` PrivateKey string `json:"private_key,omitempty"` Passphrase string `json:"passphrase,omitempty"` + // Tunnel is "" for a direct SSH connection or "cloudflared" when the host + // is reached through a Cloudflare Tunnel. CFClientID/CFClientSecret are the + // optional Cloudflare Access service token (secret encrypted at rest). + Tunnel string `json:"tunnel"` + CFClientID string `json:"cf_client_id,omitempty"` + CFClientSecret string `json:"cf_client_secret,omitempty"` // HostKey is the server's SSH public key, pinned on first connect (TOFU). // A later connection presenting a different key is refused. Not secret. HostKey string `json:"host_key,omitempty"` diff --git a/internal/store/vps.go b/internal/store/vps.go index 439a8848..356b3eaf 100644 --- a/internal/store/vps.go +++ b/internal/store/vps.go @@ -9,7 +9,7 @@ import ( "github.com/enowdev/antares/internal/secret" ) -const vpsCols = `id,label,host,port,username,auth_method,password,private_key,passphrase,host_key,created_at,updated_at` +const vpsCols = `id,label,host,port,username,auth_method,password,private_key,passphrase,host_key,tunnel,cf_client_id,cf_client_secret,created_at,updated_at` // crypter returns the process secret box, obtained once. VPS credentials are // unusable without it, so a failure here fails the operation rather than @@ -47,15 +47,21 @@ func (s *sqlStore) PutVPSHost(ctx context.Context, v *VPSHost) error { return err } + encCF, err := box.Encrypt(v.CFClientSecret) + if err != nil { + return err + } + // host_key is deliberately NOT in the conflict-update set: it is pinned by // SetVPSHostKey on first connect and must survive an edit of the other // fields. On insert it starts empty. - _, err = s.exec(ctx, `INSERT INTO vps_hosts (`+vpsCols+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`+ + _, err = s.exec(ctx, `INSERT INTO vps_hosts (`+vpsCols+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`+ onConflict("id", `label=EXCLUDED.label, host=EXCLUDED.host, port=EXCLUDED.port, username=EXCLUDED.username, auth_method=EXCLUDED.auth_method, password=EXCLUDED.password, - private_key=EXCLUDED.private_key, passphrase=EXCLUDED.passphrase, updated_at=EXCLUDED.updated_at`), + private_key=EXCLUDED.private_key, passphrase=EXCLUDED.passphrase, tunnel=EXCLUDED.tunnel, + cf_client_id=EXCLUDED.cf_client_id, cf_client_secret=EXCLUDED.cf_client_secret, updated_at=EXCLUDED.updated_at`), v.ID, v.Label, v.Host, v.Port, v.Username, v.AuthMethod, - encPass, encKey, encPhrase, v.HostKey, ms(v.CreatedAt), ms(v.UpdatedAt)) + encPass, encKey, encPhrase, v.HostKey, v.Tunnel, v.CFClientID, encCF, ms(v.CreatedAt), ms(v.UpdatedAt)) return err } @@ -116,7 +122,7 @@ func scanVPSHost(sc interface{ Scan(...any) error }) (*VPSHost, error) { var v VPSHost var created, updated int64 if err := sc.Scan(&v.ID, &v.Label, &v.Host, &v.Port, &v.Username, &v.AuthMethod, - &v.Password, &v.PrivateKey, &v.Passphrase, &v.HostKey, &created, &updated); err != nil { + &v.Password, &v.PrivateKey, &v.Passphrase, &v.HostKey, &v.Tunnel, &v.CFClientID, &v.CFClientSecret, &created, &updated); err != nil { return nil, err } v.CreatedAt = fromMS(created) @@ -136,5 +142,8 @@ func decryptVPS(box *secret.Box, v *VPSHost) (*VPSHost, error) { if v.Passphrase, err = box.Decrypt(v.Passphrase); err != nil { return nil, err } + if v.CFClientSecret, err = box.Decrypt(v.CFClientSecret); err != nil { + return nil, err + } return v, nil } diff --git a/internal/store/vps_test.go b/internal/store/vps_test.go new file mode 100644 index 00000000..df8ebddb --- /dev/null +++ b/internal/store/vps_test.go @@ -0,0 +1,66 @@ +package store + +import ( + "bytes" + "context" + "testing" + + "github.com/enowdev/antares/internal/secret" +) + +func newVPSTestStore(t *testing.T) *sqlStore { + t.Helper() + ss := newTestStore(t).(*sqlStore) + ss.boxOnce.Do(func() { ss.box, ss.boxErr = secret.NewBox(bytes.Repeat([]byte{7}, 32)) }) + return ss +} + +func TestVPSHostTunnelFieldsRoundTrip(t *testing.T) { + ctx := context.Background() + ss := newVPSTestStore(t) + h := &VPSHost{ID: "vps_t", Host: "ssh.example.com", Tunnel: "cloudflared", + CFClientID: "abc.access", CFClientSecret: "s3cret", AuthMethod: "password", Password: "pw"} + if err := ss.PutVPSHost(ctx, h); err != nil { + t.Fatal(err) + } + got, err := ss.GetVPSHost(ctx, "vps_t") + if err != nil { + t.Fatal(err) + } + if got.Tunnel != "cloudflared" || got.CFClientID != "abc.access" || got.CFClientSecret != "s3cret" { + t.Fatalf("round trip mismatch: %+v", got) + } + var raw string + if err := ss.row(ctx, `SELECT cf_client_secret FROM vps_hosts WHERE id='vps_t'`).Scan(&raw); err != nil { + t.Fatal(err) + } + if raw == "" || raw == "s3cret" { + t.Fatalf("cf_client_secret not encrypted at rest: %q", raw) + } + h.CFClientSecret = "new" + if err := ss.PutVPSHost(ctx, h); err != nil { + t.Fatal(err) + } + got, err = ss.GetVPSHost(ctx, "vps_t") + if err != nil || got.CFClientSecret != "new" { + t.Fatalf("update: %v %+v", err, got) + } +} + +func TestVPSHostDefaultsToDirect(t *testing.T) { + ctx := context.Background() + ss := newVPSTestStore(t) + // A row as a pre-v4 binary wrote it: none of the tunnel columns are named. + if _, err := ss.db.ExecContext(ctx, `INSERT INTO vps_hosts + (id, label, host, port, username, auth_method, password, private_key, passphrase, host_key, created_at, updated_at) + VALUES ('vps_d', 'old', '1.2.3.4', 22, 'root', 'password', '', '', '', '', 1, 1)`); err != nil { + t.Fatal(err) + } + got, err := ss.GetVPSHost(ctx, "vps_d") + if err != nil { + t.Fatal(err) + } + if got.Tunnel != "" || got.CFClientID != "" || got.CFClientSecret != "" { + t.Fatalf("expected direct defaults: %+v", got) + } +} diff --git a/internal/tools/vps.go b/internal/tools/vps.go index af3382f5..07872ad2 100644 --- a/internal/tools/vps.go +++ b/internal/tools/vps.go @@ -44,6 +44,7 @@ func targetFromHost(h *store.VPSHost) vps.Target { Host: h.Host, Port: h.Port, Username: h.Username, AuthMethod: h.AuthMethod, Password: h.Password, PrivateKey: h.PrivateKey, Passphrase: h.Passphrase, KnownHostKey: h.HostKey, + Tunnel: h.Tunnel, CFClientID: h.CFClientID, CFClientSecret: h.CFClientSecret, } } @@ -60,6 +61,10 @@ func formatVPSList(hosts []store.VPSHost) string { var b strings.Builder fmt.Fprintf(&b, "Saved servers (%d) — pass id or label as `vps`:\n\n", len(hosts)) for _, h := range hosts { + if h.Tunnel == vps.TunnelCloudflared { + fmt.Fprintf(&b, " - id=%s label=%q %s@%s via cloudflared\n", h.ID, h.Label, h.Username, h.Host) + continue + } fmt.Fprintf(&b, " - id=%s label=%q %s@%s:%d\n", h.ID, h.Label, h.Username, h.Host, h.Port) } return b.String() diff --git a/internal/tools/vps_list_test.go b/internal/tools/vps_list_test.go new file mode 100644 index 00000000..6b17f682 --- /dev/null +++ b/internal/tools/vps_list_test.go @@ -0,0 +1,30 @@ +package tools + +import ( + "strings" + "testing" + + "github.com/enowdev/antares/internal/store" +) + +func TestFormatVPSListShowsCloudflared(t *testing.T) { + out := formatVPSList([]store.VPSHost{ + {ID: "a", Label: "tun", Host: "ssh.example.com", Port: 22, Username: "root", Tunnel: "cloudflared"}, + {ID: "b", Label: "dir", Host: "1.2.3.4", Port: 2222, Username: "bob"}, + }) + var tun, dir string + for _, l := range strings.Split(out, "\n") { + if strings.Contains(l, "id=a") { + tun = l + } + if strings.Contains(l, "id=b") { + dir = l + } + } + if !strings.Contains(tun, "root@ssh.example.com via cloudflared") || strings.Contains(tun, ":22") { + t.Fatalf("tunnel line: %q", tun) + } + if !strings.Contains(dir, "bob@1.2.3.4:2222") { + t.Fatalf("direct line: %q", dir) + } +} diff --git a/internal/vps/tunnel.go b/internal/vps/tunnel.go new file mode 100644 index 00000000..bd1ec35d --- /dev/null +++ b/internal/vps/tunnel.go @@ -0,0 +1,214 @@ +package vps + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "net" + "net/http" + "os" + "strconv" + "strings" + "time" + + "golang.org/x/net/websocket" +) + +// TunnelCloudflared is the Target.Tunnel value for hosts whose SSH port is only +// reachable through a Cloudflare Tunnel. Empty means direct SSH. +const TunnelCloudflared = "cloudflared" + +// ErrTunnelRefused is returned when Cloudflare rejects the WebSocket upgrade. +var ErrTunnelRefused = errors.New("cloudflare refused the tunnel connection") + +// tunnelDialTimeout bounds the WebSocket upgrade. It is a variable so a test +// can shrink it. +var tunnelDialTimeout = 20 * time.Second + +// tunnelEndpoint returns the WebSocket location and Origin for a tunnel host. +// It is a variable so tests can point it at a local server. +var tunnelEndpoint = func(host string) (location, origin string) { + return "wss://" + host + "/", "https://" + host +} + +// NormalizeTunnelHost reduces a pasted URL or hostname to a bare host: scheme, +// path and userinfo are dropped; an explicit :port is kept. +func NormalizeTunnelHost(s string) string { + s = strings.TrimSpace(s) + if i := strings.Index(s, "://"); i >= 0 { + s = s[i+3:] + } + if i := strings.IndexAny(s, "/?#"); i >= 0 { + s = s[:i] + } + if i := strings.LastIndex(s, "@"); i >= 0 { + s = s[i+1:] + } + return s +} + +// endpoint is the human-readable address of the target, for error messages. +func (t Target) endpoint() string { + if t.Tunnel == TunnelCloudflared { + return "wss://" + t.Host + } + return t.addr() +} + +// dialTransport opens the raw byte stream SSH runs over: plain TCP, or a +// WebSocket to a Cloudflare Tunnel the way `cloudflared access ssh` does. +func dialTransport(ctx context.Context, t Target) (net.Conn, error) { + d := &net.Dialer{Timeout: 20 * time.Second} + if t.Tunnel != TunnelCloudflared { + return d.DialContext(ctx, "tcp", t.addr()) + } + return dialTunnel(ctx, t, d) +} + +// dialTunnel performs the WebSocket upgrade itself rather than through +// websocket.Config.DialContext: x/net reports every refused upgrade as a bare +// ErrBadStatus, and the HTTP status is what tells an offline tunnel apart from +// an Access policy. The connection records the first bytes it reads so the +// status line and Location header can be recovered on refusal. +func dialTunnel(ctx context.Context, t Target, d *net.Dialer) (net.Conn, error) { + loc, origin := tunnelEndpoint(t.Host) + cfg, err := websocket.NewConfig(loc, origin) + if err != nil { + return nil, fmt.Errorf("tunnel endpoint %s: %w", t.Host, err) + } + cfg.Header.Set("User-Agent", "antares") + if t.CFClientID != "" { + cfg.Header.Set("Cf-Access-Client-Id", t.CFClientID) + } + if t.CFClientSecret != "" { + cfg.Header.Set("Cf-Access-Client-Secret", t.CFClientSecret) + } + + dctx, cancel := context.WithTimeout(ctx, tunnelDialTimeout) + defer cancel() + raw, err := dialTunnelConn(dctx, d, cfg) + if err != nil { + return nil, tunnelDialErr(ctx, dctx, t, err) + } + // Bound the handshake by dctx: its deadline, and an early unblock if the + // caller cancels. + if dl, ok := dctx.Deadline(); ok { + _ = raw.SetDeadline(dl) + } + stop := context.AfterFunc(dctx, func() { _ = raw.SetDeadline(time.Now()) }) + rc := &recordingConn{Conn: raw, limit: upgradeRecordLimit} + ws, err := websocket.NewClient(cfg, rc) + stopped := stop() + if err != nil { + _ = raw.Close() + if errors.Is(err, websocket.ErrBadStatus) { + status, location := parseUpgradeResponse(rc.recorded()) + return nil, refusedError(t.Host, status, location) + } + return nil, tunnelDialErr(ctx, dctx, t, err) + } + if !stopped { + // dctx ended as the handshake finished; the deadline is already in the past. + _ = ws.Close() + return nil, tunnelDialErr(ctx, dctx, t, context.DeadlineExceeded) + } + _ = raw.SetDeadline(time.Time{}) + rc.stopRecording() + ws.PayloadType = websocket.BinaryFrame + return ws, nil +} + +// dialTunnelConn opens the TCP (ws) or TLS (wss) connection the upgrade runs on. +func dialTunnelConn(ctx context.Context, d *net.Dialer, cfg *websocket.Config) (net.Conn, error) { + u := cfg.Location + addr := u.Host + if u.Port() == "" { + port := "80" + if u.Scheme == "wss" { + port = "443" + } + addr = net.JoinHostPort(u.Hostname(), port) + } + if u.Scheme == "wss" { + td := &tls.Dialer{NetDialer: d, Config: cfg.TlsConfig} + return td.DialContext(ctx, "tcp", addr) + } + return d.DialContext(ctx, "tcp", addr) +} + +// tunnelDialErr maps a failed connect or handshake: running out of the tunnel's +// own budget while the caller's context is still live is a timeout; anything +// else (including the caller's cancellation, which dial wraps) passes through. +func tunnelDialErr(ctx, dctx context.Context, t Target, err error) error { + if ctx.Err() == nil && (errors.Is(dctx.Err(), context.DeadlineExceeded) || errors.Is(err, os.ErrDeadlineExceeded)) { + return fmt.Errorf("%w: no response from %s", ErrTimeout, t.endpoint()) + } + return err +} + +// refusedError words a refused upgrade by what Cloudflare's status implies. +// Every result wraps ErrTunnelRefused. +func refusedError(host string, status int, location string) error { + switch { + case status == http.StatusUnauthorized || status == http.StatusForbidden || + (status >= 300 && status < 400 && isAccessLogin(location)): + return fmt.Errorf("%w to %s (HTTP %d): the hostname is protected by Cloudflare Access; add a service token, or check that its Client ID and Secret are allowed by the Access policy", ErrTunnelRefused, host, status) + case status == http.StatusBadGateway || status == http.StatusServiceUnavailable || + status == http.StatusGatewayTimeout || status == 530: + return fmt.Errorf("%w to %s (HTTP %d): the tunnel is offline; check that cloudflared is running on the server and connected to Cloudflare", ErrTunnelRefused, host, status) + case status > 0: + return fmt.Errorf("%w to %s (HTTP %d): the hostname is not routed to SSH; check that the tunnel's ingress sends it to ssh://localhost:22", ErrTunnelRefused, host, status) + default: + return fmt.Errorf("%w to %s: if the hostname is protected by Cloudflare Access add a service token; otherwise check that the tunnel routes it to ssh://localhost:22", ErrTunnelRefused, host) + } +} + +// isAccessLogin reports whether a redirect target is a Cloudflare Access login. +func isAccessLogin(location string) bool { + l := strings.ToLower(location) + return strings.Contains(l, "cloudflareaccess.com") || strings.Contains(l, "/cdn-cgi/access/") +} + +// parseUpgradeResponse pulls the status code and Location header out of the +// recorded start of an HTTP response. It returns 0 when no status line is +// readable; the body and any header past the recorded bytes are ignored. +func parseUpgradeResponse(b []byte) (status int, location string) { + lines := strings.Split(string(b), "\r\n") + if f := strings.Fields(lines[0]); len(f) >= 2 && strings.HasPrefix(f[0], "HTTP/") { + status, _ = strconv.Atoi(f[1]) + } + for _, line := range lines[1:] { + if line == "" { + break + } + if name, value, ok := strings.Cut(line, ":"); ok && strings.EqualFold(strings.TrimSpace(name), "Location") { + location = strings.TrimSpace(value) + } + } + return status, location +} + +// upgradeRecordLimit caps how much of the upgrade response is kept: enough +// for the status line and Cloudflare's headers, matching bufio's default read. +const upgradeRecordLimit = 4096 + +// recordingConn copies the first bytes read from the connection so a refused +// upgrade's status can be recovered. Recording stops after the handshake. +type recordingConn struct { + net.Conn + buf []byte + limit int +} + +func (c *recordingConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + if room := c.limit - len(c.buf); room > 0 && n > 0 { + c.buf = append(c.buf, p[:min(n, room)]...) + } + return n, err +} + +func (c *recordingConn) recorded() []byte { return c.buf } + +func (c *recordingConn) stopRecording() { c.buf, c.limit = nil, 0 } diff --git a/internal/vps/tunnel_test.go b/internal/vps/tunnel_test.go new file mode 100644 index 00000000..dc8524b9 --- /dev/null +++ b/internal/vps/tunnel_test.go @@ -0,0 +1,281 @@ +package vps + +import ( + "bufio" + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" + + "golang.org/x/net/websocket" +) + +// useTunnelEndpoint points the tunnel dial at a plain-ws test server. +func useTunnelEndpoint(t *testing.T, host string) { + t.Helper() + old := tunnelEndpoint + tunnelEndpoint = func(string) (string, string) { return "ws://" + host + "/", "http://" + host } + t.Cleanup(func() { tunnelEndpoint = old }) +} + +// newTunnelBridge serves a WebSocket endpoint that forwards binary frames to a +// plain TCP SSH server, like cloudflared does. It records the upgrade headers. +func newTunnelBridge(t *testing.T, sshAddr string) (string, *http.Header) { + t.Helper() + var mu sync.Mutex + got := &http.Header{} + srv := httptest.NewServer(websocket.Server{ + Handshake: func(_ *websocket.Config, r *http.Request) error { + mu.Lock() + *got = r.Header.Clone() + mu.Unlock() + return nil + }, + Handler: func(ws *websocket.Conn) { + ws.PayloadType = websocket.BinaryFrame + up, err := net.Dial("tcp", sshAddr) + if err != nil { + return + } + defer up.Close() + done := make(chan struct{}, 2) + go func() { _, _ = io.Copy(up, ws); done <- struct{}{} }() + go func() { _, _ = io.Copy(ws, up); done <- struct{}{} }() + <-done + }, + }) + t.Cleanup(srv.Close) + host := strings.TrimPrefix(srv.URL, "http://") + useTunnelEndpoint(t, host) + return host, got +} + +func tunnelTarget(srv *testSSHServer, host string) Target { + tg := srv.target() + tg.Tunnel, tg.Host, tg.Port = TunnelCloudflared, host, 1 + return tg +} + +func TestRunOverCloudflaredTunnel(t *testing.T) { + srv := newTestSSHServer(t, func(s *testSSHServer) { s.execOutput = "tunnel-ok\n" }) + host, _ := newTunnelBridge(t, srv.addr) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + out, _, err := Run(ctx, tunnelTarget(srv, host), "whoami") + if err != nil { + t.Fatal(err) + } + if out != "tunnel-ok\n" { + t.Fatalf("out = %q", out) + } +} + +func TestPingOverCloudflaredTunnel(t *testing.T) { + srv := newTestSSHServer(t) + host, _ := newTunnelBridge(t, srv.addr) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + _, seen, err := Ping(ctx, tunnelTarget(srv, host)) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(seen, "ssh-") { + t.Fatalf("seenHostKey = %q", seen) + } +} + +func TestTunnelSendsAccessHeaders(t *testing.T) { + srv := newTestSSHServer(t) + host, got := newTunnelBridge(t, srv.addr) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + tg := tunnelTarget(srv, host) + tg.CFClientID, tg.CFClientSecret = "abc.access", "s3cret" + if _, _, err := Ping(ctx, tg); err != nil { + t.Fatal(err) + } + if got.Get("Cf-Access-Client-Id") != "abc.access" || got.Get("Cf-Access-Client-Secret") != "s3cret" { + t.Fatalf("access headers = %v", *got) + } + if !strings.Contains(got.Get("User-Agent"), "antares") { + t.Fatalf("user agent = %q", got.Get("User-Agent")) + } + tg.CFClientID, tg.CFClientSecret = "", "" + if _, _, err := Ping(ctx, tg); err != nil { + t.Fatal(err) + } + if got.Get("Cf-Access-Client-Id") != "" || got.Get("Cf-Access-Client-Secret") != "" { + t.Fatalf("headers should be absent, got %v", *got) + } +} + +// TestTunnelRefusedIsReadable checks that a refused upgrade always satisfies +// ErrTunnelRefused and that the message names the likely cause for the status +// Cloudflare answered with. +func TestTunnelRefusedIsReadable(t *testing.T) { + const accessLogin = "https://team.cloudflareaccess.com/cdn-cgi/access/login/ssh.example.com?kid=abc" + cases := []struct { + name string + status int + location string + want []string + notWant string + }{ + {name: "access forbidden", status: http.StatusForbidden, want: []string{"HTTP 403", "Cloudflare Access", "service token"}}, + {name: "access unauthorized", status: http.StatusUnauthorized, want: []string{"HTTP 401", "service token"}}, + {name: "access login redirect", status: http.StatusFound, location: accessLogin, want: []string{"HTTP 302", "Cloudflare Access", "service token"}}, + {name: "tunnel offline 530", status: 530, want: []string{"HTTP 530", "cloudflared is running"}, notWant: "service token"}, + {name: "tunnel offline 502", status: http.StatusBadGateway, want: []string{"HTTP 502", "cloudflared is running"}, notWant: "service token"}, + {name: "not routed 404", status: http.StatusNotFound, want: []string{"HTTP 404", "ingress", "ssh://localhost:22"}, notWant: "service token"}, + {name: "plain redirect", status: http.StatusFound, location: "https://example.com/", want: []string{"HTTP 302", "ingress"}, notWant: "service token"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if tc.location != "" { + w.Header().Set("Location", tc.location) + } + w.WriteHeader(tc.status) + })) + defer ts.Close() + host := strings.TrimPrefix(ts.URL, "http://") + useTunnelEndpoint(t, host) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, _, err := Ping(ctx, Target{Host: host, Tunnel: TunnelCloudflared, Password: "x"}) + if err == nil { + t.Fatal("expected error") + } + if !errors.Is(err, ErrTunnelRefused) { + t.Fatalf("not ErrTunnelRefused: %v", err) + } + for _, w := range tc.want { + if !strings.Contains(err.Error(), w) { + t.Errorf("error %q lacks %q", err, w) + } + } + if tc.notWant != "" && strings.Contains(err.Error(), tc.notWant) { + t.Errorf("error %q should not mention %q", err, tc.notWant) + } + }) + } +} + +func TestTunnelDialHonoursContext(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + var mu sync.Mutex + var conns []net.Conn + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + mu.Lock() + conns = append(conns, c) + mu.Unlock() + } + }() + defer func() { + mu.Lock() + for _, c := range conns { + c.Close() + } + mu.Unlock() + }() + host := ln.Addr().String() + useTunnelEndpoint(t, host) + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + start := time.Now() + _, _, err = Ping(ctx, Target{Host: host, Tunnel: TunnelCloudflared, Password: "x"}) + if time.Since(start) > 2*time.Second { + t.Fatalf("took %v", time.Since(start)) + } + if !errors.Is(err, ErrTimeout) { + t.Fatalf("want ErrTimeout, got %v", err) + } +} + +func TestNormalizeTunnelHost(t *testing.T) { + for _, in := range []string{ + "https://ssh.example.com/", "ssh://ssh.example.com", "wss://ssh.example.com/x/y", + " ssh.example.com ", "ssh.example.com", + "root@ssh.example.com", + } { + if got := NormalizeTunnelHost(in); got != "ssh.example.com" { + t.Errorf("NormalizeTunnelHost(%q) = %q", in, got) + } + } +} + +func TestNormalizeTunnelHostKeepsPort(t *testing.T) { + if got := NormalizeTunnelHost("ssh.example.com:8443"); got != "ssh.example.com:8443" { + t.Errorf("got %q", got) + } +} + +func TestTunnelUpgradeTimeout(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + t.Cleanup(func() { c.Close() }) + } + }() + useTunnelEndpoint(t, ln.Addr().String()) + old := tunnelDialTimeout + tunnelDialTimeout = 200 * time.Millisecond + t.Cleanup(func() { tunnelDialTimeout = old }) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + start := time.Now() + _, _, err = Ping(ctx, Target{Host: "ssh.example.com", Tunnel: TunnelCloudflared, Username: "u", Password: "p"}) + if !errors.Is(err, ErrTimeout) { + t.Fatalf("err = %v, want ErrTimeout", err) + } + if time.Since(start) > 2*time.Second { + t.Fatalf("took %v", time.Since(start)) + } +} + +func TestLiveCloudflaredBanner(t *testing.T) { + host := os.Getenv("ANTARES_LIVE_TUNNEL_HOST") + if host == "" { + t.Skip("set ANTARES_LIVE_TUNNEL_HOST to run against a real tunnel") + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + c, err := dialTransport(ctx, Target{Host: host, Tunnel: TunnelCloudflared}) + if err != nil { + t.Fatal(err) + } + defer c.Close() + _ = c.SetReadDeadline(time.Now().Add(15 * time.Second)) + line, err := bufio.NewReader(c).ReadString('\n') + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(line, "SSH-2.0-") { + t.Fatalf("banner = %q", line) + } +} diff --git a/internal/vps/vps.go b/internal/vps/vps.go index 2628e2e0..c887a8ff 100644 --- a/internal/vps/vps.go +++ b/internal/vps/vps.go @@ -31,6 +31,12 @@ type Target struct { // means the presented key MUST match, or the dial fails — this is what stops // a MITM from harvesting the credentials. KnownHostKey string + // Tunnel selects the transport: "" is direct SSH, TunnelCloudflared reaches + // Host through a Cloudflare Tunnel (Port is then ignored). CFClientID and + // CFClientSecret are an optional Cloudflare Access service token. + Tunnel string + CFClientID string + CFClientSecret string } func (t Target) addr() string { @@ -49,6 +55,11 @@ var ErrHostKeyChanged = errors.New("host key changed since it was first trusted // The error text includes the duration; partial output may accompany it from Run. var ErrTimeout = errors.New("vps operation timed out") +// ErrAuthFailed is returned when the server rejects the login. x/crypto/ssh +// reports this only as text ("ssh: unable to authenticate ..."), so dial +// recognises it by that phrase and rewords it with the username tried. +var ErrAuthFailed = errors.New("the server rejected the login") + // conn wraps an ssh.Client with the host key the server actually presented, so // the caller can pin it after a first-use connect. type conn struct { @@ -86,26 +97,32 @@ func dial(ctx context.Context, t Target) (*conn, error) { } // Dial timeout is separate from the overall command timeout so a slow host // does not burn the whole vps_run budget before the command starts. - d := net.Dialer{Timeout: 20 * time.Second} - netConn, err := d.DialContext(ctx, "tcp", t.addr()) + netConn, err := dialTransport(ctx, t) if err != nil { if ctx.Err() != nil { - return nil, fmt.Errorf("%w while connecting to %s: %v", ErrTimeout, t.addr(), err) + return nil, fmt.Errorf("%w while connecting to %s: %v", ErrTimeout, t.endpoint(), err) } - return nil, fmt.Errorf("connect %s: %w", t.addr(), err) + return nil, fmt.Errorf("connect %s: %w", t.endpoint(), err) } // Honour cancellation during the SSH handshake too. if deadline, ok := ctx.Deadline(); ok { _ = netConn.SetDeadline(deadline) } - c, chans, reqs, err := ssh.NewClientConn(netConn, t.addr(), cfg) + c, chans, reqs, err := ssh.NewClientConn(netConn, t.endpoint(), cfg) if err != nil { netConn.Close() if errors.Is(err, ErrHostKeyChanged) { return nil, ErrHostKeyChanged } if ctx.Err() != nil { - return nil, fmt.Errorf("%w during ssh handshake with %s: %v", ErrTimeout, t.addr(), err) + return nil, fmt.Errorf("%w during ssh handshake with %s: %v", ErrTimeout, t.endpoint(), err) + } + if strings.Contains(err.Error(), "ssh: unable to authenticate") { + secret := "password" + if t.AuthMethod == "key" || (t.AuthMethod == "" && t.PrivateKey != "") { + secret = "private key" + } + return nil, fmt.Errorf("%w for user %q on %s: check the username (it defaults to root) and the %s", ErrAuthFailed, user, t.endpoint(), secret) } return nil, fmt.Errorf("ssh handshake: %w", err) } diff --git a/internal/vps/vps_test.go b/internal/vps/vps_test.go index 9286b4a2..e3aa1c5a 100644 --- a/internal/vps/vps_test.go +++ b/internal/vps/vps_test.go @@ -10,6 +10,7 @@ import ( "net" "os" "path/filepath" + "strings" "sync" "testing" "time" @@ -323,3 +324,25 @@ func (w *writeCounter) Write(p []byte) (int, error) { w.n += len(p) return len(p), nil } + +// TestLoginRejectedNamesUser checks that a refused login says which user was +// tried, so a wrong username (it defaults to root) is easy to spot. +func TestLoginRejectedNamesUser(t *testing.T) { + srv := newTestSSHServer(t) + target := srv.target() + target.Password = "wrong" + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, _, err := Ping(ctx, target) + if err == nil { + t.Fatal("expected the login to be rejected") + } + if !errors.Is(err, ErrAuthFailed) { + t.Fatalf("not ErrAuthFailed: %v", err) + } + for _, want := range []string{`"test"`, "username", "password"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q lacks %q", err, want) + } + } +} diff --git a/web/src/lib/i18n.tsx b/web/src/lib/i18n.tsx index 2d197760..deb3270a 100644 --- a/web/src/lib/i18n.tsx +++ b/web/src/lib/i18n.tsx @@ -145,6 +145,16 @@ const en = { 'vps.privateKey': 'Private key', 'vps.passphrase': 'Key passphrase (optional)', 'vps.passphrasePh': 'Only if the key is encrypted', + 'vps.connection': 'Connection', + 'vps.connDirect': 'Direct SSH', + 'vps.connCloudflared': 'Cloudflare Tunnel (cloudflared)', + 'vps.tunnelHost': 'Tunnel hostname', + 'vps.tunnelHint': 'Same hostname as --hostname in your cloudflared ProxyCommand.', + 'vps.cfToken': 'Cloudflare Access service token (optional)', + 'vps.cfTokenHint': 'Only needed if this hostname is protected by Cloudflare Access.', + 'vps.cfClientId': 'Client ID', + 'vps.cfClientSecret': 'Client Secret', + 'vps.viaCloudflared': 'cloudflared', 'vps.test': 'Test', 'vps.testing': 'Connecting…', 'vps.testOk': 'Connected as {as}', diff --git a/web/src/lib/locales/id.ts b/web/src/lib/locales/id.ts index 154b5043..433fd978 100644 --- a/web/src/lib/locales/id.ts +++ b/web/src/lib/locales/id.ts @@ -125,6 +125,16 @@ const id: Dict = { 'vps.privateKey': 'Private key', 'vps.passphrase': 'Passphrase key (opsional)', 'vps.passphrasePh': 'Hanya jika key terenkripsi', + 'vps.connection': 'Koneksi', + 'vps.connDirect': 'SSH langsung', + 'vps.connCloudflared': 'Cloudflare Tunnel (cloudflared)', + 'vps.tunnelHost': 'Hostname tunnel', + 'vps.tunnelHint': 'Hostname yang sama dengan --hostname di ProxyCommand cloudflared-mu.', + 'vps.cfToken': 'Service token Cloudflare Access (opsional)', + 'vps.cfTokenHint': 'Hanya perlu kalau hostname ini dilindungi Cloudflare Access.', + 'vps.cfClientId': 'Client ID', + 'vps.cfClientSecret': 'Client Secret', + 'vps.viaCloudflared': 'cloudflared', 'vps.test': 'Tes', 'vps.testing': 'Menghubungkan…', 'vps.testOk': 'Terhubung sebagai {as}', diff --git a/web/src/lib/locales/ja.ts b/web/src/lib/locales/ja.ts index 4d1df0cf..cb65887a 100644 --- a/web/src/lib/locales/ja.ts +++ b/web/src/lib/locales/ja.ts @@ -98,6 +98,16 @@ const ja: Dict = { 'vps.privateKey': '秘密鍵', 'vps.passphrase': '鍵のパスフレーズ(任意)', 'vps.passphrasePh': '鍵が暗号化されている場合のみ', + 'vps.connection': '接続方式', + 'vps.connDirect': '直接 SSH', + 'vps.connCloudflared': 'Cloudflare Tunnel (cloudflared)', + 'vps.tunnelHost': 'トンネルのホスト名', + 'vps.tunnelHint': 'cloudflared の ProxyCommand にある --hostname と同じホスト名です。', + 'vps.cfToken': 'Cloudflare Access サービストークン(任意)', + 'vps.cfTokenHint': 'このホスト名が Cloudflare Access で保護されている場合のみ必要です。', + 'vps.cfClientId': 'Client ID', + 'vps.cfClientSecret': 'Client Secret', + 'vps.viaCloudflared': 'cloudflared', 'vps.test': 'テスト', 'vps.testing': '接続中…', 'vps.testOk': '{as} として接続', diff --git a/web/src/lib/locales/ru.ts b/web/src/lib/locales/ru.ts index eaaab5b9..c40ac6e1 100644 --- a/web/src/lib/locales/ru.ts +++ b/web/src/lib/locales/ru.ts @@ -98,6 +98,16 @@ const ru: Dict = { 'vps.privateKey': 'Приватный ключ', 'vps.passphrase': 'Пароль ключа (необязательно)', 'vps.passphrasePh': 'Только если ключ зашифрован', + 'vps.connection': 'Подключение', + 'vps.connDirect': 'Прямой SSH', + 'vps.connCloudflared': 'Cloudflare Tunnel (cloudflared)', + 'vps.tunnelHost': 'Хост туннеля', + 'vps.tunnelHint': 'Тот же хост, что и --hostname в вашем ProxyCommand для cloudflared.', + 'vps.cfToken': 'Сервисный токен Cloudflare Access (необязательно)', + 'vps.cfTokenHint': 'Нужен, только если этот хост защищён Cloudflare Access.', + 'vps.cfClientId': 'Client ID', + 'vps.cfClientSecret': 'Client Secret', + 'vps.viaCloudflared': 'cloudflared', 'vps.test': 'Проверить', 'vps.testing': 'Подключение…', 'vps.testOk': 'Подключено как {as}', diff --git a/web/src/lib/locales/zh.ts b/web/src/lib/locales/zh.ts index d9484f5c..860d5eea 100644 --- a/web/src/lib/locales/zh.ts +++ b/web/src/lib/locales/zh.ts @@ -98,6 +98,16 @@ const zh: Dict = { 'vps.privateKey': '私钥', 'vps.passphrase': '密钥口令(可选)', 'vps.passphrasePh': '仅当密钥已加密时', + 'vps.connection': '连接方式', + 'vps.connDirect': '直连 SSH', + 'vps.connCloudflared': 'Cloudflare Tunnel (cloudflared)', + 'vps.tunnelHost': '隧道主机名', + 'vps.tunnelHint': '与 cloudflared ProxyCommand 中 --hostname 相同的主机名。', + 'vps.cfToken': 'Cloudflare Access 服务令牌(可选)', + 'vps.cfTokenHint': '仅当此主机名受 Cloudflare Access 保护时才需要。', + 'vps.cfClientId': 'Client ID', + 'vps.cfClientSecret': 'Client Secret', + 'vps.viaCloudflared': 'cloudflared', 'vps.test': '测试', 'vps.testing': '连接中…', 'vps.testOk': '已以 {as} 连接', diff --git a/web/src/pages/VPSPage.tsx b/web/src/pages/VPSPage.tsx index ac647456..be424ba7 100644 --- a/web/src/pages/VPSPage.tsx +++ b/web/src/pages/VPSPage.tsx @@ -41,6 +41,9 @@ interface VPSHost { auth_method: string has_password: boolean has_key: boolean + tunnel?: string + cf_client_id?: string + has_cf_secret?: boolean } interface Metrics { @@ -183,9 +186,11 @@ function VPSCard({ host, onEdit, onRemove }: { host: VPSHost; onEdit: () => void ) ) : null} + {host.tunnel === 'cloudflared' ? {t('vps.viaCloudflared')} : null} -

- {host.username}@{host.host}:{host.port} +

+ {host.username}@{host.host} + {host.tunnel === 'cloudflared' ? null : `:${host.port}`}

@@ -409,6 +414,9 @@ function VPSDialog({ const [password, setPassword] = useState('') const [privateKey, setPrivateKey] = useState('') const [passphrase, setPassphrase] = useState('') + const [tunnel, setTunnel] = useState('') + const [cfClientId, setCfClientId] = useState('') + const [cfClientSecret, setCfClientSecret] = useState('') const [busy, setBusy] = useState(false) const [testing, setTesting] = useState(false) const [testResult, setTestResult] = useState<{ ok: boolean; as?: string; error?: string } | null>(null) @@ -425,10 +433,15 @@ function VPSDialog({ setPassword('') setPrivateKey('') setPassphrase('') + setTunnel(host?.tunnel ?? '') + setCfClientId(host?.cf_client_id ?? '') + setCfClientSecret('') setTestResult(null) setError(undefined) }, [open, host]) + const viaTunnel = tunnel === 'cloudflared' + const body = () => ({ id: host?.id, label: label.trim(), @@ -440,6 +453,10 @@ function VPSDialog({ password: authMethod === 'password' ? password : '', private_key: authMethod === 'key' ? privateKey : '', passphrase: authMethod === 'key' ? passphrase : '', + tunnel, + cf_client_id: viaTunnel ? cfClientId.trim() : '', + // Blank on edit = keep stored secret. + cf_client_secret: viaTunnel ? cfClientSecret : '', }) const valid = hostname.trim() !== '' @@ -482,16 +499,57 @@ function VPSDialog({ setLabel(e.target.value)} placeholder={t('vps.labelPh')} />
-
+
+ + +
+
- - setHostname(e.target.value)} placeholder="1.2.3.4 / vps.example.com" /> + + setHostname(e.target.value)} + placeholder={viaTunnel ? 'ssh.example.com' : '1.2.3.4 / vps.example.com'} + /> + {viaTunnel ?

{t('vps.tunnelHint')}

: null}
+ {viaTunnel ? null : ( +
+ + setPort(e.target.value)} placeholder="22" /> +
+ )} +
+ {viaTunnel ? (
- - setPort(e.target.value)} placeholder="22" /> + +

{t('vps.cfTokenHint')}

+
+ setCfClientId(e.target.value)} + placeholder={t('vps.cfClientId')} + aria-label={t('vps.cfClientId')} + autoComplete="off" + /> + setCfClientSecret(e.target.value)} + placeholder={isEdit && host?.has_cf_secret ? '••••••••' : t('vps.cfClientSecret')} + aria-label={t('vps.cfClientSecret')} + autoComplete="off" + /> +
-
+ ) : null}