forked from vhaudiquet/rhema-together
feat: add reverse ssh sandbox targets
A sandbox behind NAT could not reach the room. A reverse target dials a tunnel-only sshd on the server, forwards localhost:22 to a loopback port, and the worker connects there. The server assigns the port and writes one authorized_keys line per tunnel target. The key carries permitlisten for that port; the sshd allows remote forwarding only, with no shell or local forwarding. The tunnel private key is shown once and never stored; rotating it rewrites the file. The target list and setup dialog carry the command, and the docs include the sshd config and sidecar requirements.
This commit is contained in:
1 parent
fc684115b5
commit
d85f68a176
20 files changed
+881
-26
No files matched your search
@@ -51,7 +51,7 @@ src/config.rs YAML + TOGETHER_* env
|
||||
src/db.rs schema and migrations
|
||||
src/crypto.rs ChaCha20Poly1305 secrets, preview HMAC
|
||||
src/auth.rs sessions, cookies, CSRF
|
||||
src/state.rs AppState: db, hub, secrets, runner, tunnels
|
||||
src/state.rs AppState: db, hub, secrets, rooms, workers, presence
|
||||
src/api/ routes: auth, settings, rooms, messages, files
|
||||
src/room/agent.rs per-turn config, ssh sandbox, HostAgent assembly
|
||||
src/room/runner.rs one task per room; mention -> turn; steering
|
||||
@@ -59,6 +59,7 @@ src/room/message_tool.rs the agent's voice in the room
|
||||
src/room/preview_tool.rs the agent's preview target
|
||||
src/worker.rs disposable data plane: loopback HTTP, PTY, forward, worker spawn
|
||||
src/ssh.rs russh client and PTY pump, used only by the worker
|
||||
src/tunnel.rs reverse ssh ports and the tunnel sshd authorized_keys file
|
||||
src/preview.rs signed preview hosts, worker forward, static reads
|
||||
web/app/ Nuxt 4 SPA (no SSR)
|
||||
```
|
||||
|
||||
@@ -37,6 +37,7 @@ COPY --from=web /app/web/.output/public /app/web
|
||||
ENV TOGETHER_LISTEN=0.0.0.0:7800 \
|
||||
TOGETHER_DATABASE=/data/together.db \
|
||||
TOGETHER_SECRET_KEY_FILE=/data/secret.key \
|
||||
TOGETHER_TUNNEL_AUTHORIZED_KEYS=/data/tunnel/authorized_keys \
|
||||
TOGETHER_WEB_DIR=/app/web \
|
||||
HOME=/data \
|
||||
RUST_LOG=rhema_together=info,tower_http=warn
|
||||
|
||||
@@ -112,7 +112,8 @@ issue certificates.
|
||||
Append that line to `~/.ssh/authorized_keys` on the target. Set the
|
||||
workspace root to a directory the ssh user can write (for a normal
|
||||
user, `/home/<name>`; the default is `/root`). Test the target; a
|
||||
green check means ssh works.
|
||||
green check means ssh works. For a machine behind NAT, choose
|
||||
**Reverse SSH** instead; see below.
|
||||
3. **New room.** Pick the target and provider, give the workspace
|
||||
directory (for example `/home/me/rooms/demo`), and optionally a git
|
||||
URL. The workspace is created on the first mention and seeded from
|
||||
@@ -129,6 +130,34 @@ The agent always runs with the room's sandbox, and every command is an
|
||||
ordinary ssh command. There is no approval prompt: the sandbox is the
|
||||
boundary.
|
||||
|
||||
## Reverse SSH
|
||||
|
||||
A machine behind NAT can dial the server instead of accepting a
|
||||
connection. This is the fallback for an account that will not install a
|
||||
connector; the server still speaks ssh to the sandbox.
|
||||
|
||||
Reverse SSH needs a tunnel-only sshd in the app's network namespace.
|
||||
`deploy/tunnel` has a config and the setup steps. The app writes the
|
||||
sshd's `authorized_keys` file: one key per target, restricted to the
|
||||
target's loopback port with `permitlisten`, no shell, no local
|
||||
forwarding, and no non-loopback bind.
|
||||
|
||||
In **Settings → Sandboxes**, choose **Reverse SSH**. The server assigns
|
||||
the loopback port. Save the tunnel private key shown once as
|
||||
`rhema-tunnel-<target-id>` and run `chmod 600` on it. Add the target's
|
||||
public key to the sandbox's `~/.ssh/authorized_keys`, then run the
|
||||
command from the target's **Setup** dialog:
|
||||
|
||||
```sh
|
||||
autossh -M 0 -N -R 127.0.0.1:22000:localhost:22 -p 2222 \
|
||||
tunnel@together.example.com -i ./rhema-tunnel-<target-id> \
|
||||
-o ExitOnForwardFailure=yes -o ServerAliveInterval=30
|
||||
```
|
||||
|
||||
The sandbox needs an sshd on `localhost:22`. The tunnel key is a
|
||||
credential; rotating it invalidates the old key. The tunnel sshd is
|
||||
internet-facing, so patch it and rate-limit it.
|
||||
|
||||
## Preview
|
||||
|
||||
The preview shows one target per room. It is either a port inside the
|
||||
@@ -201,7 +230,13 @@ Every field can be set in the YAML file (`TOGETHER_CONFIG`, default
|
||||
| `TOGETHER_WEB_DIR` | `web/.output/public` | built client |
|
||||
| `TOGETHER_MAX_TURN_STEPS` | `48` | step cap per turn |
|
||||
| `TOGETHER_ALLOW_REGISTRATION` | `false` | whether `/register` works |
|
||||
| `TOGETHER_ALLOW_PRIVATE_TARGETS` | `false` | whether a sandbox target may use a loopback or private address |
|
||||
| `TOGETHER_ALLOW_PRIVATE_TARGETS` | `false` | whether a direct sandbox target may use a loopback or private address |
|
||||
| `TOGETHER_TUNNEL_AUTHORIZED_KEYS` | `data/tunnel/authorized_keys` | file the tunnel sshd reads; the app writes it |
|
||||
| `TOGETHER_TUNNEL_SSH_HOST` | host from `TOGETHER_PUBLIC_URL` | host shown in the reverse ssh command |
|
||||
| `TOGETHER_TUNNEL_SSH_PORT` | `2222` | tunnel sshd port |
|
||||
| `TOGETHER_TUNNEL_USER` | `tunnel` | account the tunnel sshd accepts |
|
||||
| `TOGETHER_TUNNEL_PORT_START` | `22000` | first loopback port assigned to a reverse target |
|
||||
| `TOGETHER_TUNNEL_PORT_END` | `22999` | last loopback port assigned to a reverse target |
|
||||
|
||||
## Security model
|
||||
|
||||
|
||||
@@ -131,3 +131,10 @@ Settings, then create a room.
|
||||
GID 10001; the chart sets `fsGroup` for that.
|
||||
- Set `app.previewOrigin: ""` to disable previews. The ingress wildcard
|
||||
can then be removed.
|
||||
- Reverse SSH is not installed by this chart. It needs a tunnel-only
|
||||
sshd sidecar in the same pod, because the forwarded loopback port must
|
||||
be in the app's network namespace. The app writes
|
||||
`/data/tunnel/authorized_keys`; mount the data volume into the sidecar
|
||||
read-only and expose port 2222 with a TCP service. See
|
||||
`deploy/tunnel` for the sshd config and the app's `TOGETHER_TUNNEL_*`
|
||||
settings.
|
||||
@@ -53,6 +53,8 @@ spec:
|
||||
value: /data/together.db
|
||||
- name: TOGETHER_SECRET_KEY_FILE
|
||||
value: /data/secret.key
|
||||
- name: TOGETHER_TUNNEL_AUTHORIZED_KEYS
|
||||
value: /data/tunnel/authorized_keys
|
||||
- name: TOGETHER_WEB_DIR
|
||||
value: /app/web
|
||||
- name: TOGETHER_ALLOW_REGISTRATION
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# Reverse SSH targets
|
||||
|
||||
A reverse SSH target is for a machine that cannot accept an inbound
|
||||
connection. The sandbox dials a tunnel-only sshd on the server, forwards
|
||||
its own `localhost:22` to a loopback port, and the worker connects to that
|
||||
port as if the sandbox were local.
|
||||
|
||||
The app is the only writer of the tunnel sshd's `authorized_keys` file.
|
||||
For every reverse target it writes one line:
|
||||
|
||||
```
|
||||
restrict,port-forwarding,permitlisten="127.0.0.1:22000" ssh-ed25519 AAAA... <target-id>
|
||||
```
|
||||
|
||||
The key can bind that one port and nothing else. The sshd in this
|
||||
directory allows only remote forwarding, no shell, no local forwarding,
|
||||
and no non-loopback binds.
|
||||
|
||||
## Host setup
|
||||
|
||||
1. Create the tunnel account. It needs no shell:
|
||||
|
||||
```sh
|
||||
useradd --system --create-home --home-dir /var/lib/rhema-tunnel \
|
||||
--shell /usr/sbin/nologin tunnel
|
||||
# The app writes authorized_keys, so its uid owns the directory. The
|
||||
# sshd runs as root and can read the 0640 file.
|
||||
install -d -o 10001 -g 10001 -m 0750 /data/tunnel
|
||||
ssh-keygen -t ed25519 -N '' -f /data/tunnel/host_ed25519
|
||||
```
|
||||
|
||||
2. Point the app at the file and the public endpoint:
|
||||
|
||||
```sh
|
||||
TOGETHER_TUNNEL_AUTHORIZED_KEYS=/data/tunnel/authorized_keys
|
||||
TOGETHER_TUNNEL_SSH_HOST=together.example.com
|
||||
TOGETHER_TUNNEL_SSH_PORT=2222
|
||||
TOGETHER_TUNNEL_USER=tunnel
|
||||
TOGETHER_TUNNEL_PORT_START=22000
|
||||
TOGETHER_TUNNEL_PORT_END=22999
|
||||
```
|
||||
|
||||
The app creates the file on startup and rewrites it when a reverse
|
||||
target is added, deleted, or has its key rotated. The file is mode
|
||||
0640; the tunnel sshd must be able to read it.
|
||||
|
||||
3. Run the sshd in the **same network namespace** as the app:
|
||||
|
||||
```sh
|
||||
/usr/sbin/sshd -D -f /etc/ssh/sshd_config.tunnel
|
||||
```
|
||||
|
||||
In Kubernetes this is a sidecar container in the app pod, not a
|
||||
separate deployment and not the node's sshd. A separate pod has a
|
||||
different loopback, so the worker would connect to nothing. The app
|
||||
image does not ship sshd; use an sshd image and mount the data volume
|
||||
at `/data` read-only. The host key can live in an `emptyDir` at
|
||||
`/data/tunnel-host` with `HostKey /data/tunnel-host/host_ed25519`;
|
||||
`authorized_keys` comes from the app's volume.
|
||||
|
||||
4. Expose port 2222 with a TCP load balancer, NodePort, or a separate
|
||||
TCP ingress. Do not route it through the HTTP ingress, and do not
|
||||
expose the host's port 22 in its place.
|
||||
|
||||
## Adding a target
|
||||
|
||||
1. In Settings, choose **Reverse SSH**, name the target, and enter the
|
||||
sandbox's ssh user and workspace root. The server assigns the
|
||||
loopback port.
|
||||
2. Copy the target's public key into the sandbox's
|
||||
`~/.ssh/authorized_keys`. This is the key the worker uses after the
|
||||
tunnel is up.
|
||||
3. Save the tunnel private key shown once as
|
||||
`rhema-tunnel-<target-id>` in the directory where you run the command,
|
||||
then run `chmod 600` on it.
|
||||
4. Run the command shown in the target's **Setup** dialog:
|
||||
|
||||
```sh
|
||||
autossh -M 0 -N -R 127.0.0.1:22000:localhost:22 -p 2222 \
|
||||
tunnel@together.example.com -i ./rhema-tunnel-<target-id> \
|
||||
-o ExitOnForwardFailure=yes -o ServerAliveInterval=30
|
||||
```
|
||||
|
||||
If `autossh` is not installed, `ssh -N` with the same options works;
|
||||
use a service manager or a reconnect loop to keep it alive.
|
||||
5. Press **Test**. The worker reaches `127.0.0.1:<port>` and logs in with
|
||||
the target's stored key.
|
||||
|
||||
## Limits
|
||||
|
||||
- The sandbox must run an sshd on `localhost:22`. A different sshd port
|
||||
needs a different tunnel command; the target form does not model it.
|
||||
- The tunnel key is a credential. Delete the target or rotate the key if
|
||||
it leaks; both rewrite the authorized_keys file.
|
||||
- The tunnel sshd is internet-facing. Keep it patched, disable password
|
||||
auth, and rate-limit at the network edge. A successful login can still
|
||||
consume a port in the configured range, so alert on repeated failures.
|
||||
- The worker's normal host-key pinning still applies after the tunnel.
|
||||
The tunnel sshd has its own host key; `ssh` asks once and remembers it.
|
||||
@@ -0,0 +1,37 @@
|
||||
# A tunnel-only sshd for reverse ssh sandbox targets.
|
||||
#
|
||||
# The app writes `AuthorizedKeysFile`; each key is restricted to one
|
||||
# loopback port with permitlisten. Run this as a separate sshd, not as
|
||||
# the host's sshd. It must share a network namespace with the app so
|
||||
# 127.0.0.1:<port> is the app's loopback.
|
||||
|
||||
Port 2222
|
||||
AddressFamily any
|
||||
ListenAddress 0.0.0.0
|
||||
|
||||
HostKey /data/tunnel/host_ed25519
|
||||
PidFile /run/sshd-tunnel.pid
|
||||
|
||||
AuthorizedKeysFile /data/tunnel/authorized_keys
|
||||
StrictModes no
|
||||
UsePAM no
|
||||
UseDNS no
|
||||
|
||||
PasswordAuthentication no
|
||||
KbdInteractiveAuthentication no
|
||||
PermitRootLogin no
|
||||
AllowUsers tunnel
|
||||
|
||||
AllowTcpForwarding remote
|
||||
GatewayPorts no
|
||||
PermitOpen none
|
||||
PermitTunnel no
|
||||
PermitTTY no
|
||||
X11Forwarding no
|
||||
AllowAgentForwarding no
|
||||
AllowStreamLocalForwarding no
|
||||
ForceCommand /bin/false
|
||||
|
||||
ClientAliveInterval 30
|
||||
ClientAliveCountMax 3
|
||||
LogLevel VERBOSE
|
||||
+32
-5
@@ -272,14 +272,18 @@ belong to the API and the config, not to the worker.
|
||||
The ssh backend already runs commands on a remote box with no daemon on
|
||||
the far end. It can offer the three things the panes need: a pty for
|
||||
the terminal, long-lived processes for a dev server, and file reads for
|
||||
the editor.
|
||||
the editor. The connector link changes how the server reaches that sshd,
|
||||
not what it speaks.
|
||||
|
||||
### What ecrou needs for a terminal
|
||||
|
||||
The ecrou backend is one microVM per command. It boots, runs the command
|
||||
with the workspace shared in, and powers off. Its stdin is null, it
|
||||
exposes no pty, and nothing outlives the command. `--persist` keeps disk
|
||||
state across boots, not processes.
|
||||
exposes no pty, and nothing outlives the command. The ecrou repository's
|
||||
`SPEC.md` is explicit about the boundary: a guest agent, long-lived
|
||||
machines, and port publishing are Later rows, and the current engine
|
||||
publishes no guest port. Disk state persists only through a virtiofs
|
||||
share, not through processes.
|
||||
|
||||
A web terminal needs a byte stream into a live process. Two ways to get
|
||||
one from ecrou:
|
||||
@@ -307,6 +311,13 @@ files, and preview. Option 1 stays a candidate as a degraded mode for
|
||||
accounts that only have ecrou, if a command runner is acceptable. Option
|
||||
2 is the one to design when ecrou grows sessions.
|
||||
|
||||
ecrou is the preferred runtime when that happens, not a replacement for
|
||||
reachability. The connector client still dials out; the client then runs
|
||||
one long-lived room machine and speaks the sandbox protocol to an
|
||||
in-guest agent. A per-command machine can back the agent's `exec` without
|
||||
the terminal or preview, so it is a fallback for accounts that accept
|
||||
that loss, not the room's default.
|
||||
|
||||
### Seam additions
|
||||
|
||||
The `Sandbox` trait gets three capabilities. Each has a default method
|
||||
@@ -562,6 +573,21 @@ are rejected. An operator on one private network can set
|
||||
the control plane. A DNS name that resolves to a public address when the
|
||||
worker starts and to a private one later is outside this check.
|
||||
|
||||
Reverse ssh is a second opt-in fallback for a machine behind NAT that
|
||||
cannot install the connector. The sandbox dials a tunnel-only sshd on
|
||||
the server and forwards its `localhost:22` to a loopback port; the
|
||||
worker dials `127.0.0.1:<port>`. A tunnel target is the only kind for
|
||||
which the loopback rejection is skipped, and only the target's own port
|
||||
is reachable. The API allocates the port from
|
||||
`tunnel_port_start..=tunnel_port_end` and writes one restricted key per
|
||||
target to the tunnel sshd's `authorized_keys` file. The key line carries
|
||||
`permitlisten="127.0.0.1:<port>"`; the sshd allows remote forwarding
|
||||
only, no shell, no local forwarding, and no non-loopback bind. The
|
||||
tunnel private key is shown once and never stored; deleting the target
|
||||
removes the line, and rotating the key replaces it. The tunnel sshd must
|
||||
share the app's network namespace, which makes it a sidecar, not a
|
||||
separate deployment or the node's sshd.
|
||||
|
||||
### Secrets
|
||||
|
||||
Provider keys and sandbox private keys are encrypted at rest with a key
|
||||
@@ -701,8 +727,9 @@ explanation.
|
||||
Settled:
|
||||
|
||||
1. Sandbox: the per-room disposable worker owns every transport. A
|
||||
connector link is the default; direct SSH is opt-in. ecrou waits for a
|
||||
live mode, with the shell-on-top runner as a possible degraded mode.
|
||||
connector link is the default; direct SSH and reverse SSH are opt-in
|
||||
fallbacks. ecrou waits for a live mode, with the shell-on-top runner
|
||||
as a possible degraded mode.
|
||||
2. Provider and model: the room owner picks both, and only the owner
|
||||
changes them. Every turn spends from that config.
|
||||
3. Interrupts: any member. v1 has no rate limit.
|
||||
|
||||
@@ -59,6 +59,10 @@ pub fn router(state: Shared) -> Router {
|
||||
)
|
||||
.route("/sandbox-targets/{id}", delete(settings::delete_target))
|
||||
.route("/sandbox-targets/{id}/test", post(settings::test_target))
|
||||
.route(
|
||||
"/sandbox-targets/{id}/tunnel-key",
|
||||
post(settings::rotate_tunnel_key),
|
||||
)
|
||||
.route("/rooms", get(rooms::list).post(rooms::create))
|
||||
.route(
|
||||
"/rooms/{id}",
|
||||
|
||||
+85
-5
@@ -336,7 +336,7 @@ pub async fn delete_provider(
|
||||
pub async fn list_targets(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, name, host, port, user_name, workspace_root, public_key, host_fingerprint
|
||||
"SELECT id, name, host, port, user_name, workspace_root, public_key, host_fingerprint, kind
|
||||
FROM sandbox_targets WHERE account_id = ?1 ORDER BY created_at ASC",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![user.user.id], |row| {
|
||||
@@ -349,6 +349,15 @@ pub async fn list_targets(user: AuthUser, State(state): State<Shared>) -> AppRes
|
||||
workspace_root: row.get(5)?,
|
||||
public_key: row.get(6)?,
|
||||
host_fingerprint: row.get(7)?,
|
||||
kind: row.get(8)?,
|
||||
tunnel_command: if row.get::<_, String>(8)? == "tunnel" {
|
||||
Some(state.config.tunnel_command(
|
||||
u16::try_from(row.get::<_, i64>(3)?).unwrap_or(0),
|
||||
&row.get::<_, String>(0)?,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
},
|
||||
})
|
||||
})?;
|
||||
let targets = rows.collect::<Result<Vec<_>, _>>()?;
|
||||
@@ -358,7 +367,11 @@ pub async fn list_targets(user: AuthUser, State(state): State<Shared>) -> AppRes
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateTarget {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub host: String,
|
||||
/// `direct` (the default) or `tunnel` for a machine behind NAT.
|
||||
#[serde(default)]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub port: Option<u16>,
|
||||
#[serde(default)]
|
||||
@@ -382,6 +395,16 @@ pub async fn create_target(
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::bad_request("name must be 1 to 60 characters"));
|
||||
}
|
||||
let kind = body.kind.trim();
|
||||
let kind = if kind.is_empty() { "direct" } else { kind };
|
||||
if kind != "direct" && kind != "tunnel" {
|
||||
return Err(AppError::bad_request("kind must be direct or tunnel"));
|
||||
}
|
||||
let (host, port, tunnel_public_key, tunnel_private_key) = if kind == "tunnel" {
|
||||
let port = crate::tunnel::next_port(&state)?;
|
||||
let (private, public) = crate::tunnel::new_key()?;
|
||||
("127.0.0.1".to_owned(), port, Some(public), Some(private))
|
||||
} else {
|
||||
let host = body.host.trim();
|
||||
if host.is_empty() || host.contains(char::is_whitespace) {
|
||||
return Err(AppError::bad_request("host must be a hostname or address"));
|
||||
@@ -392,6 +415,8 @@ pub async fn create_target(
|
||||
.await
|
||||
.map_err(AppError::bad_request)?;
|
||||
}
|
||||
(host.to_owned(), port, None, None)
|
||||
};
|
||||
let user_name = body
|
||||
.user_name
|
||||
.map(|value| value.trim().to_owned())
|
||||
@@ -426,8 +451,9 @@ pub async fn create_target(
|
||||
let id = random_id(12);
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO sandbox_targets (id, account_id, name, host, port, user_name,
|
||||
workspace_root, private_key_ciphertext, public_key, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
workspace_root, private_key_ciphertext, public_key,
|
||||
kind, tunnel_public_key, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
rusqlite::params![
|
||||
id,
|
||||
user.user.id,
|
||||
@@ -438,10 +464,26 @@ pub async fn create_target(
|
||||
workspace_root.trim_end_matches('/'),
|
||||
sealed,
|
||||
public_key,
|
||||
kind,
|
||||
tunnel_public_key,
|
||||
crate::util::now_ms()
|
||||
],
|
||||
)?;
|
||||
Ok(Json(json!({ "id": id, "public_key": public_key })))
|
||||
if kind == "tunnel"
|
||||
&& let Err(err) = crate::tunnel::refresh(&state)
|
||||
{
|
||||
let _ = state.db.conn().execute(
|
||||
"DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
let mut response = json!({ "id": id, "public_key": public_key, "kind": kind });
|
||||
if kind == "tunnel" {
|
||||
response["tunnel_private_key"] = json!(tunnel_private_key);
|
||||
response["tunnel_command"] = json!(state.config.tunnel_command(port, &id));
|
||||
}
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
fn generate_key() -> AppResult<(String, String)> {
|
||||
@@ -458,6 +500,41 @@ fn generate_key() -> AppResult<(String, String)> {
|
||||
Ok((private, public))
|
||||
}
|
||||
|
||||
/// Replaces a reverse ssh target's tunnel key. The old key stops
|
||||
/// working when the authorized_keys file is rewritten.
|
||||
pub async fn rotate_tunnel_key(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let (kind, port): (String, i64) = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT kind, port FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.map_err(|_| AppError::not_found("sandbox target not found"))?;
|
||||
if kind != "tunnel" {
|
||||
return Err(AppError::bad_request(
|
||||
"this sandbox is not a reverse ssh target",
|
||||
));
|
||||
}
|
||||
let (private, public) = crate::tunnel::new_key()?;
|
||||
state.db.conn().execute(
|
||||
"UPDATE sandbox_targets SET tunnel_public_key = ?1 WHERE id = ?2 AND account_id = ?3",
|
||||
rusqlite::params![public, id, user.user.id],
|
||||
)?;
|
||||
crate::tunnel::refresh(&state)?;
|
||||
let port = u16::try_from(port)
|
||||
.map_err(|_| AppError::internal("the tunnel port is outside the valid range"))?;
|
||||
Ok(Json(json!({
|
||||
"tunnel_private_key": private,
|
||||
"tunnel_command": state.config.tunnel_command(port, &id),
|
||||
})))
|
||||
}
|
||||
|
||||
/// Deletes a target.
|
||||
pub async fn delete_target(
|
||||
user: AuthUser,
|
||||
@@ -468,6 +545,7 @@ pub async fn delete_target(
|
||||
"DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
)?;
|
||||
crate::tunnel::refresh(&state)?;
|
||||
state.workers.remove_target(&id).await;
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
@@ -485,7 +563,7 @@ pub async fn test_target(
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
"SELECT host, port, user_name, private_key_ciphertext, host_fingerprint, kind
|
||||
FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
|row| {
|
||||
@@ -495,6 +573,7 @@ pub async fn test_target(
|
||||
row.get::<_, String>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
row.get::<_, Option<String>>(4)?,
|
||||
row.get::<_, String>(5)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
@@ -506,6 +585,7 @@ pub async fn test_target(
|
||||
user_name: row.2.clone(),
|
||||
private_key_ciphertext: row.3,
|
||||
host_fingerprint: row.4,
|
||||
kind: row.5,
|
||||
};
|
||||
let sandbox = crate::worker::WorkerSandbox::new(state.clone(), "/", &target);
|
||||
let cancelled = AtomicBool::new(false);
|
||||
|
||||
@@ -38,12 +38,51 @@ pub struct Config {
|
||||
/// cannot turn the server into a probe of its own network.
|
||||
#[serde(default)]
|
||||
pub allow_private_targets: bool,
|
||||
/// The host sandboxes dial for a reverse ssh tunnel. Empty uses the
|
||||
/// host from `public_url`.
|
||||
#[serde(default)]
|
||||
pub tunnel_ssh_host: String,
|
||||
/// The port the tunnel sshd listens on.
|
||||
#[serde(default = "default_tunnel_ssh_port")]
|
||||
pub tunnel_ssh_port: u16,
|
||||
/// The account the tunnel sshd accepts.
|
||||
#[serde(default = "default_tunnel_user")]
|
||||
pub tunnel_user: String,
|
||||
/// The loopback port range the server hands to tunnel targets.
|
||||
#[serde(default = "default_tunnel_port_start")]
|
||||
pub tunnel_port_start: u16,
|
||||
#[serde(default = "default_tunnel_port_end")]
|
||||
pub tunnel_port_end: u16,
|
||||
/// The authorized_keys file the tunnel sshd reads. The server writes
|
||||
/// one restricted key per tunnel target.
|
||||
#[serde(default = "default_tunnel_authorized_keys")]
|
||||
pub tunnel_authorized_keys: PathBuf,
|
||||
}
|
||||
|
||||
fn default_steps() -> u32 {
|
||||
48
|
||||
}
|
||||
|
||||
fn default_tunnel_ssh_port() -> u16 {
|
||||
2222
|
||||
}
|
||||
|
||||
fn default_tunnel_user() -> String {
|
||||
"tunnel".into()
|
||||
}
|
||||
|
||||
fn default_tunnel_port_start() -> u16 {
|
||||
22000
|
||||
}
|
||||
|
||||
fn default_tunnel_port_end() -> u16 {
|
||||
22999
|
||||
}
|
||||
|
||||
fn default_tunnel_authorized_keys() -> PathBuf {
|
||||
PathBuf::from("data/tunnel/authorized_keys")
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -57,6 +96,12 @@ impl Default for Config {
|
||||
allowed_frame_ancestors: Vec::new(),
|
||||
allow_registration: false,
|
||||
allow_private_targets: false,
|
||||
tunnel_ssh_host: String::new(),
|
||||
tunnel_ssh_port: default_tunnel_ssh_port(),
|
||||
tunnel_user: default_tunnel_user(),
|
||||
tunnel_port_start: default_tunnel_port_start(),
|
||||
tunnel_port_end: default_tunnel_port_end(),
|
||||
tunnel_authorized_keys: default_tunnel_authorized_keys(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,11 +143,65 @@ impl Config {
|
||||
if let Ok(value) = std::env::var("TOGETHER_ALLOW_PRIVATE_TARGETS") {
|
||||
config.allow_private_targets = matches!(value.as_str(), "1" | "true" | "yes");
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_SSH_HOST") {
|
||||
config.tunnel_ssh_host = value;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_SSH_PORT") {
|
||||
config.tunnel_ssh_port = value.parse()?;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_USER") {
|
||||
config.tunnel_user = value;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_PORT_START") {
|
||||
config.tunnel_port_start = value.parse()?;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_PORT_END") {
|
||||
config.tunnel_port_end = value.parse()?;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_AUTHORIZED_KEYS") {
|
||||
config.tunnel_authorized_keys = value.into();
|
||||
}
|
||||
if config.tunnel_port_start == 0 || config.tunnel_port_start > config.tunnel_port_end {
|
||||
anyhow::bail!("the tunnel port range is invalid");
|
||||
}
|
||||
if config.tunnel_ssh_port == 0 {
|
||||
anyhow::bail!("the tunnel ssh port is invalid");
|
||||
}
|
||||
config.tunnel_ssh_host = config.tunnel_ssh_host.trim().to_owned();
|
||||
config.tunnel_user = config.tunnel_user.trim().to_owned();
|
||||
if config.tunnel_user.is_empty() || config.tunnel_user.contains(char::is_whitespace) {
|
||||
anyhow::bail!("the tunnel user is invalid");
|
||||
}
|
||||
config.public_url = config.public_url.trim_end_matches('/').to_owned();
|
||||
config.preview_origin = config.preview_origin.trim_end_matches('/').to_owned();
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// The host a sandbox passes to `autossh -R`.
|
||||
pub fn tunnel_host(&self) -> String {
|
||||
if !self.tunnel_ssh_host.is_empty() {
|
||||
return self.tunnel_ssh_host.clone();
|
||||
}
|
||||
let rest = self
|
||||
.public_url
|
||||
.split("://")
|
||||
.nth(1)
|
||||
.unwrap_or(&self.public_url);
|
||||
let host = rest.split('/').next().unwrap_or(rest);
|
||||
host.split(':').next().unwrap_or(host).to_owned()
|
||||
}
|
||||
|
||||
/// The command that turns a sandbox's local sshd into a loopback
|
||||
/// port on the server.
|
||||
pub fn tunnel_command(&self, port: u16, target_id: &str) -> String {
|
||||
format!(
|
||||
"autossh -M 0 -N -R 127.0.0.1:{port}:localhost:22 -p {} {}@{} -i ./rhema-tunnel-{target_id} -o ExitOnForwardFailure=yes -o ServerAliveInterval=30",
|
||||
self.tunnel_ssh_port,
|
||||
self.tunnel_user,
|
||||
self.tunnel_host(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether cookies should carry `Secure`.
|
||||
pub fn secure_cookies(&self) -> bool {
|
||||
self.public_url.starts_with("https://")
|
||||
|
||||
@@ -26,6 +26,7 @@ impl Db {
|
||||
conn.pragma_update(None, "foreign_keys", "ON")?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
migrate(&conn)?;
|
||||
Ok(Self {
|
||||
conn: Arc::new(Mutex::new(conn)),
|
||||
})
|
||||
@@ -47,6 +48,43 @@ impl Db {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds columns that arrived after the first release. `CREATE TABLE IF
|
||||
/// NOT EXISTS` leaves an existing table alone, so each column is checked
|
||||
/// before the ALTER.
|
||||
fn migrate(conn: &Connection) -> rusqlite::Result<()> {
|
||||
if !has_column(conn, "sandbox_targets", "kind")? {
|
||||
conn.execute(
|
||||
"ALTER TABLE sandbox_targets ADD COLUMN kind TEXT NOT NULL DEFAULT 'direct'",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
if !has_column(conn, "sandbox_targets", "tunnel_public_key")? {
|
||||
conn.execute(
|
||||
"ALTER TABLE sandbox_targets ADD COLUMN tunnel_public_key TEXT",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
// A tunnel target owns one loopback port. Direct targets may share a
|
||||
// port, so the index is partial.
|
||||
conn.execute_batch(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS sandbox_tunnel_port
|
||||
ON sandbox_targets(port) WHERE kind = 'tunnel';",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result<bool> {
|
||||
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
|
||||
let mut rows = stmt.query([])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let name: String = row.get(1)?;
|
||||
if name == column {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
const SCHEMA: &str = r#"
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
@@ -100,6 +138,8 @@ CREATE TABLE IF NOT EXISTS sandbox_targets (
|
||||
private_key_ciphertext TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
host_fingerprint TEXT,
|
||||
kind TEXT NOT NULL DEFAULT 'direct',
|
||||
tunnel_public_key TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;
|
||||
|
||||
@@ -165,3 +205,50 @@ CREATE INDEX IF NOT EXISTS members_room ON members(room_id);
|
||||
CREATE INDEX IF NOT EXISTS events_room_seq ON events(room_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_account ON auth_sessions(account_id);
|
||||
"#;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_old_target_table_gains_the_tunnel_columns() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("rhema-db-migrate-{}", crate::util::random_token(6)));
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let path = dir.join("old.db");
|
||||
{
|
||||
let conn = Connection::open(&path).expect("old db");
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE sandbox_targets (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
host TEXT NOT NULL,
|
||||
port INTEGER NOT NULL DEFAULT 22,
|
||||
user_name TEXT NOT NULL,
|
||||
workspace_root TEXT NOT NULL,
|
||||
private_key_ciphertext TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
host_fingerprint TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;",
|
||||
)
|
||||
.expect("old schema");
|
||||
}
|
||||
let db = Db::open(&path).expect("open");
|
||||
let conn = db.conn();
|
||||
let mut stmt = conn
|
||||
.prepare("PRAGMA table_info(sandbox_targets)")
|
||||
.expect("pragma");
|
||||
let columns: Vec<String> = stmt
|
||||
.query_map([], |row| row.get(1))
|
||||
.expect("rows")
|
||||
.collect::<Result<_, _>>()
|
||||
.expect("columns");
|
||||
assert!(columns.iter().any(|column| column == "kind"));
|
||||
assert!(columns.iter().any(|column| column == "tunnel_public_key"));
|
||||
drop(stmt);
|
||||
drop(conn);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ mod preview;
|
||||
mod room;
|
||||
mod ssh;
|
||||
mod state;
|
||||
mod tunnel;
|
||||
mod util;
|
||||
mod worker;
|
||||
|
||||
@@ -54,6 +55,9 @@ async fn main() -> anyhow::Result<()> {
|
||||
presence: Default::default(),
|
||||
logins: Default::default(),
|
||||
});
|
||||
if let Err(err) = tunnel::refresh(&state) {
|
||||
tracing::warn!(error = %err.message, "could not write the tunnel authorized_keys file");
|
||||
}
|
||||
let app = api::router(state).layer(TraceLayer::new_for_http());
|
||||
let listener = tokio::net::TcpListener::bind(&config.listen).await?;
|
||||
tracing::info!(listen = %config.listen, "rhema-together");
|
||||
|
||||
@@ -116,6 +116,8 @@ pub struct SandboxTarget {
|
||||
pub workspace_root: String,
|
||||
pub public_key: String,
|
||||
pub host_fingerprint: Option<String>,
|
||||
pub kind: String,
|
||||
pub tunnel_command: Option<String>,
|
||||
}
|
||||
|
||||
/// A directory entry in the read-only file pane.
|
||||
|
||||
+5
-2
@@ -51,6 +51,7 @@ pub struct TargetRow {
|
||||
pub user_name: String,
|
||||
pub private_key_ciphertext: String,
|
||||
pub host_fingerprint: Option<String>,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
/// Reads everything a turn needs.
|
||||
@@ -105,7 +106,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
|
||||
},
|
||||
)?;
|
||||
let target = conn.query_row(
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint, kind
|
||||
FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![target_id],
|
||||
|row| {
|
||||
@@ -116,6 +117,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
|
||||
user_name: row.get(3)?,
|
||||
private_key_ciphertext: row.get(4)?,
|
||||
host_fingerprint: row.get(5)?,
|
||||
kind: row.get(6)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
@@ -192,7 +194,7 @@ pub fn load_room_target(state: &Shared, room: &str) -> AppResult<(String, Target
|
||||
let target_id =
|
||||
target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?;
|
||||
let target = conn.query_row(
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint, kind
|
||||
FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![target_id],
|
||||
|row| {
|
||||
@@ -203,6 +205,7 @@ pub fn load_room_target(state: &Shared, room: &str) -> AppResult<(String, Target
|
||||
user_name: row.get(3)?,
|
||||
private_key_ciphertext: row.get(4)?,
|
||||
host_fingerprint: row.get(5)?,
|
||||
kind: row.get(6)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
//! Reverse ssh targets: the sandbox dials out to the tunnel sshd, and
|
||||
//! the worker reaches its sshd through a loopback port on the server.
|
||||
//!
|
||||
//! The server writes the tunnel sshd's authorized_keys file. Each key
|
||||
//! carries `permitlisten` for the one port the target owns, so a tunnel
|
||||
//! key cannot bind another target's port.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
use ssh_key::{Algorithm, LineEnding, PrivateKey};
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::state::Shared;
|
||||
|
||||
/// Generates the key the sandbox uses to authenticate to the tunnel
|
||||
/// sshd. The private half is shown once and never stored.
|
||||
pub(crate) fn new_key() -> AppResult<(String, String)> {
|
||||
let key = PrivateKey::random(&mut rand::rngs::OsRng, Algorithm::Ed25519)
|
||||
.map_err(|err| AppError::internal(format!("could not generate a tunnel key: {err}")))?;
|
||||
let private = key
|
||||
.to_openssh(LineEnding::LF)
|
||||
.map_err(|err| AppError::internal(format!("could not encode a tunnel key: {err}")))?
|
||||
.to_string();
|
||||
let public = key
|
||||
.public_key()
|
||||
.to_openssh()
|
||||
.map_err(|err| AppError::internal(format!("could not encode a tunnel key: {err}")))?;
|
||||
Ok((private, public))
|
||||
}
|
||||
|
||||
/// Picks the first free loopback port in the configured range.
|
||||
pub(crate) fn next_port(state: &Shared) -> AppResult<u16> {
|
||||
let used: HashSet<i64> = {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare("SELECT port FROM sandbox_targets WHERE kind = 'tunnel'")?;
|
||||
let rows = stmt.query_map([], |row| row.get::<_, i64>(0))?;
|
||||
rows.collect::<Result<_, _>>()?
|
||||
};
|
||||
(state.config.tunnel_port_start..=state.config.tunnel_port_end)
|
||||
.find(|port| !used.contains(&(*port as i64)))
|
||||
.ok_or_else(|| AppError::bad_request("no tunnel ports are free"))
|
||||
}
|
||||
|
||||
/// Rewrites the authorized_keys file the tunnel sshd reads. One key per
|
||||
/// tunnel target, restricted to that target's loopback port.
|
||||
pub(crate) fn refresh(state: &Shared) -> AppResult<()> {
|
||||
let rows = {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, tunnel_public_key, port FROM sandbox_targets
|
||||
WHERE kind = 'tunnel' AND tunnel_public_key IS NOT NULL
|
||||
ORDER BY port",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, i64>(2)?,
|
||||
))
|
||||
})?;
|
||||
rows.collect::<Result<Vec<_>, _>>()?
|
||||
};
|
||||
let mut text = String::new();
|
||||
for (id, public_key, port) in rows {
|
||||
let key = public_key.trim();
|
||||
if key.is_empty() || key.contains('\n') {
|
||||
continue;
|
||||
}
|
||||
let port = u16::try_from(port).unwrap_or(0);
|
||||
if port == 0 {
|
||||
continue;
|
||||
}
|
||||
text.push_str(&format!(
|
||||
"restrict,port-forwarding,permitlisten=\"127.0.0.1:{port}\" {key} {id}\n"
|
||||
));
|
||||
}
|
||||
write_atomic(&state.config.tunnel_authorized_keys, text.as_bytes())
|
||||
}
|
||||
|
||||
fn write_atomic(path: &std::path::Path, body: &[u8]) -> AppResult<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|err| {
|
||||
AppError::internal(format!(
|
||||
"could not create the tunnel key directory {}: {err}",
|
||||
parent.display()
|
||||
))
|
||||
})?;
|
||||
}
|
||||
let tmp = path.with_extension("tmp");
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(&tmp)
|
||||
.map_err(|err| {
|
||||
AppError::internal(format!(
|
||||
"could not write the tunnel key file {}: {err}",
|
||||
tmp.display()
|
||||
))
|
||||
})?;
|
||||
file.write_all(body)
|
||||
.map_err(|err| AppError::internal(format!("could not write the tunnel key file: {err}")))?;
|
||||
file.sync_all()
|
||||
.map_err(|err| AppError::internal(format!("could not sync the tunnel key file: {err}")))?;
|
||||
let mut perms = file
|
||||
.metadata()
|
||||
.map_err(|err| AppError::internal(format!("could not stat the tunnel key file: {err}")))?
|
||||
.permissions();
|
||||
perms.set_mode(0o640);
|
||||
std::fs::set_permissions(&tmp, perms)
|
||||
.map_err(|err| AppError::internal(format!("could not chmod the tunnel key file: {err}")))?;
|
||||
drop(file);
|
||||
std::fs::rename(&tmp, path).map_err(|err| {
|
||||
AppError::internal(format!(
|
||||
"could not install the tunnel key file {}: {err}",
|
||||
path.display()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
use crate::config::Config;
|
||||
use crate::crypto::Secrets;
|
||||
use crate::db::Db;
|
||||
use crate::state::AppState;
|
||||
|
||||
fn test_state() -> (Shared, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"rhema-tunnel-test-{}",
|
||||
crate::util::random_token(6)
|
||||
));
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let config = Config {
|
||||
database: dir.join("test.db"),
|
||||
secret_key_file: dir.join("test.key"),
|
||||
tunnel_authorized_keys: dir.join("tunnel/authorized_keys"),
|
||||
..Config::default()
|
||||
};
|
||||
let db = Db::open(&config.database).expect("db");
|
||||
let secrets = Secrets::load_or_create(&config.secret_key_file).expect("secrets");
|
||||
db.conn()
|
||||
.execute(
|
||||
"INSERT INTO accounts (id, handle, display_name, kind, created_at)
|
||||
VALUES ('a1', 'a', 'A', 'user', 0)",
|
||||
[],
|
||||
)
|
||||
.expect("account");
|
||||
db.conn()
|
||||
.execute(
|
||||
"INSERT INTO sandbox_targets
|
||||
(id, account_id, name, host, port, user_name, workspace_root,
|
||||
private_key_ciphertext, public_key, kind, tunnel_public_key, created_at)
|
||||
VALUES ('t1', 'a1', 'sandbox', '127.0.0.1', 22000, 'root', '/root',
|
||||
'sealed', 'ssh-ed25519 AAAA target', 'tunnel',
|
||||
'ssh-ed25519 AAAA tunnel', 0)",
|
||||
[],
|
||||
)
|
||||
.expect("target");
|
||||
let state = Arc::new(AppState {
|
||||
config,
|
||||
db,
|
||||
secrets,
|
||||
hub: Default::default(),
|
||||
rooms: Default::default(),
|
||||
workers: Default::default(),
|
||||
presence: Default::default(),
|
||||
logins: Default::default(),
|
||||
});
|
||||
(state, dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tunnel_keys_are_restricted_to_their_port() {
|
||||
let (state, dir) = test_state();
|
||||
assert_eq!(next_port(&state).expect("port"), 22001);
|
||||
refresh(&state).expect("refresh");
|
||||
let text = std::fs::read_to_string(&state.config.tunnel_authorized_keys).expect("file");
|
||||
assert!(
|
||||
text.contains(
|
||||
"restrict,port-forwarding,permitlisten=\"127.0.0.1:22000\" ssh-ed25519 AAAA tunnel t1"
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -318,7 +318,7 @@ impl WorkerSandbox {
|
||||
private_key: key,
|
||||
host_fingerprint: target.host_fingerprint.clone(),
|
||||
},
|
||||
allow_private: state.config.allow_private_targets,
|
||||
allow_private: state.config.allow_private_targets || target.kind == "tunnel",
|
||||
})
|
||||
};
|
||||
self.state
|
||||
@@ -515,6 +515,9 @@ impl WorkerState {
|
||||
user_name: self.target.user_name.clone(),
|
||||
private_key_ciphertext: String::new(),
|
||||
host_fingerprint: self.target.host_fingerprint.clone(),
|
||||
// The worker does not use the kind; it is already past the
|
||||
// target check. A valid value keeps the row honest.
|
||||
kind: "direct".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -877,6 +880,7 @@ mod smoke {
|
||||
user_name: "vhaudiquet".into(),
|
||||
private_key_ciphertext: secrets.seal_str(&key).expect("seal"),
|
||||
host_fingerprint: None,
|
||||
kind: "direct".into(),
|
||||
};
|
||||
let state = Arc::new(AppState {
|
||||
config,
|
||||
|
||||
@@ -2141,6 +2141,20 @@ body.files-resizing-y * {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.command-block {
|
||||
margin: 0;
|
||||
padding: var(--sp-3);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--r-control);
|
||||
color: var(--text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
line-height: var(--lh-body);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
|
||||
+158
-9
@@ -9,6 +9,7 @@ import type {
|
||||
LoginFlowStatus,
|
||||
ProviderConfig,
|
||||
ProviderListResponse,
|
||||
SandboxKind,
|
||||
SandboxListResponse,
|
||||
SandboxTarget,
|
||||
StartLoginResponse,
|
||||
@@ -93,6 +94,7 @@ const flowInstruction = computed(() => {
|
||||
}
|
||||
})
|
||||
|
||||
const sandboxKind = ref<SandboxKind>('direct')
|
||||
const sandboxName = ref('')
|
||||
const sandboxHost = ref('')
|
||||
const sandboxPort = ref<number | string>(22)
|
||||
@@ -101,6 +103,10 @@ const sandboxRoot = ref('/root')
|
||||
const sandboxKey = ref('')
|
||||
const sandboxBusy = ref(false)
|
||||
const sandboxError = ref('')
|
||||
const tunnelSetup = ref<{ id: string; name: string; privateKey: string; command: string } | null>(null)
|
||||
const tunnelBusy = ref(false)
|
||||
const tunnelError = ref('')
|
||||
const copiedTunnel = ref<string | null>(null)
|
||||
|
||||
const deletingProvider = ref<string | null>(null)
|
||||
const deletingTarget = ref<string | null>(null)
|
||||
@@ -306,6 +312,7 @@ function openSandboxDialog() {
|
||||
|
||||
function closeSandboxDialog() {
|
||||
sandboxDialog.value = false
|
||||
sandboxKind.value = 'direct'
|
||||
sandboxKey.value = ''
|
||||
sandboxError.value = ''
|
||||
}
|
||||
@@ -339,21 +346,33 @@ async function addSandbox() {
|
||||
sandboxBusy.value = true
|
||||
sandboxError.value = ''
|
||||
const body: CreateSandboxBody = {
|
||||
kind: sandboxKind.value,
|
||||
name: sandboxName.value.trim(),
|
||||
host: sandboxHost.value.trim(),
|
||||
port: Number(sandboxPort.value) || 22,
|
||||
user_name: sandboxUser.value.trim() || 'root',
|
||||
workspace_root: sandboxRoot.value.trim() || '/root',
|
||||
}
|
||||
if (sandboxKind.value === 'direct') {
|
||||
body.host = sandboxHost.value.trim()
|
||||
body.port = Number(sandboxPort.value) || 22
|
||||
}
|
||||
if (sandboxKey.value.trim()) body.private_key = sandboxKey.value.trim()
|
||||
try {
|
||||
await api.post<CreateSandboxResponse>('/sandbox-targets', body)
|
||||
const result = await api.post<CreateSandboxResponse>('/sandbox-targets', body)
|
||||
if (result.kind === 'tunnel') {
|
||||
tunnelSetup.value = {
|
||||
id: result.id,
|
||||
name: sandboxName.value.trim(),
|
||||
privateKey: result.tunnel_private_key ?? '',
|
||||
command: result.tunnel_command ?? '',
|
||||
}
|
||||
}
|
||||
sandboxName.value = ''
|
||||
sandboxHost.value = ''
|
||||
sandboxPort.value = 22
|
||||
sandboxUser.value = 'root'
|
||||
sandboxRoot.value = '/root'
|
||||
sandboxKey.value = ''
|
||||
sandboxKind.value = 'direct'
|
||||
await loadLists()
|
||||
sandboxDialog.value = false
|
||||
} catch (err) {
|
||||
@@ -363,6 +382,47 @@ async function addSandbox() {
|
||||
}
|
||||
}
|
||||
|
||||
function openTunnelSetup(target: SandboxTarget) {
|
||||
tunnelError.value = ''
|
||||
copiedTunnel.value = null
|
||||
tunnelSetup.value = {
|
||||
id: target.id,
|
||||
name: target.name,
|
||||
privateKey: '',
|
||||
command: target.tunnel_command ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
async function regenerateTunnelKey() {
|
||||
const setup = tunnelSetup.value
|
||||
if (!setup || tunnelBusy.value) return
|
||||
tunnelBusy.value = true
|
||||
tunnelError.value = ''
|
||||
try {
|
||||
const result = await api.post<CreateSandboxResponse>(`/sandbox-targets/${setup.id}/tunnel-key`)
|
||||
setup.privateKey = result.tunnel_private_key ?? ''
|
||||
setup.command = result.tunnel_command ?? setup.command
|
||||
copiedTunnel.value = null
|
||||
await loadLists()
|
||||
} catch (err) {
|
||||
tunnelError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
tunnelBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function copyTunnelValue(value: string, key: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value)
|
||||
copiedTunnel.value = key
|
||||
window.setTimeout(() => {
|
||||
if (copiedTunnel.value === key) copiedTunnel.value = null
|
||||
}, 1800)
|
||||
} catch {
|
||||
tunnelError.value = 'The clipboard is not available. Select the text and copy it by hand.'
|
||||
}
|
||||
}
|
||||
|
||||
async function removeProvider(provider: ProviderConfig) {
|
||||
if (deleteBusy.value) return
|
||||
deleteBusy.value = true
|
||||
@@ -591,7 +651,7 @@ async function copyKey(target: SandboxTarget) {
|
||||
Add sandbox
|
||||
</button>
|
||||
</div>
|
||||
<p class="hint">A sandbox is an ssh machine the room works on. The public key belongs in its authorized_keys file.</p>
|
||||
<p class="hint">A sandbox is an ssh machine the room works on. Direct targets are reached at their address. Reverse SSH targets dial this server, so they can sit behind NAT.</p>
|
||||
|
||||
<div v-if="!loading && targets.length === 0" class="empty">No sandboxes yet. Use Add sandbox to connect one.</div>
|
||||
|
||||
@@ -599,7 +659,10 @@ async function copyKey(target: SandboxTarget) {
|
||||
<div v-for="target in targets" :key="target.id" class="settings-row">
|
||||
<div class="settings-row-main">
|
||||
<div class="settings-row-title">{{ target.name }}</div>
|
||||
<div class="settings-row-detail">{{ target.user_name }}@{{ target.host }}:{{ target.port }}</div>
|
||||
<div v-if="target.kind === 'tunnel'" class="settings-row-detail">
|
||||
Tunnel port {{ target.port }} on this server, sandbox {{ target.user_name }}@localhost:22
|
||||
</div>
|
||||
<div v-else class="settings-row-detail">{{ target.user_name }}@{{ target.host }}:{{ target.port }}</div>
|
||||
<div class="settings-row-detail">Workspace root: {{ target.workspace_root }}</div>
|
||||
<div class="key-line">
|
||||
<span class="key-text">{{ target.public_key }}</span>
|
||||
@@ -623,6 +686,14 @@ async function copyKey(target: SandboxTarget) {
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-row-actions">
|
||||
<button
|
||||
v-if="target.kind === 'tunnel'"
|
||||
type="button"
|
||||
class="btn btn-sm"
|
||||
@click="openTunnelSetup(target)"
|
||||
>
|
||||
Setup
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm"
|
||||
@@ -669,21 +740,35 @@ async function copyKey(target: SandboxTarget) {
|
||||
<input id="sandbox-name" v-model="sandboxName" class="input" type="text" maxlength="60" autofocus required>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-host">Host</label>
|
||||
<input id="sandbox-host" v-model="sandboxHost" class="input" type="text" spellcheck="false" required>
|
||||
<label class="field-label" for="sandbox-kind">Connection</label>
|
||||
<select id="sandbox-kind" v-model="sandboxKind" class="select">
|
||||
<option value="direct">Direct SSH</option>
|
||||
<option value="tunnel">Reverse SSH</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-grid">
|
||||
<div v-if="sandboxKind === 'direct'" class="form-grid">
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-host">Host</label>
|
||||
<input id="sandbox-host" v-model="sandboxHost" class="input" type="text" spellcheck="false" required>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-port">Port</label>
|
||||
<input id="sandbox-port" v-model.number="sandboxPort" class="input" type="number" min="1" max="65535" required>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="field">
|
||||
<span class="hint">
|
||||
The server assigns a loopback port. After adding, run the tunnel command on the sandbox and add this target's public key to its authorized_keys.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-user">SSH user</label>
|
||||
<input id="sandbox-user" v-model="sandboxUser" class="input" type="text" spellcheck="false">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-root">Workspace root</label>
|
||||
@@ -713,6 +798,70 @@ async function copyKey(target: SandboxTarget) {
|
||||
</div>
|
||||
</form>
|
||||
</BaseDialog>
|
||||
|
||||
<BaseDialog
|
||||
v-if="tunnelSetup"
|
||||
title="Reverse SSH setup"
|
||||
:description="`Run the tunnel on ${tunnelSetup.name}, then test the target.`"
|
||||
@close="tunnelSetup = null"
|
||||
>
|
||||
<div class="form">
|
||||
<p class="hint">
|
||||
Add the target's public key to the sandbox's authorized_keys. The tunnel sshd reads the authorized_keys file this server writes.
|
||||
</p>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label">Tunnel command</label>
|
||||
<pre class="command-block">{{ tunnelSetup.command }}</pre>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-quiet"
|
||||
@click="copyTunnelValue(tunnelSetup.command, 'setup-command')"
|
||||
>
|
||||
<component :is="copiedTunnel === 'setup-command' ? Check : Copy" :size="14" aria-hidden="true" />
|
||||
{{ copiedTunnel === 'setup-command' ? 'Copied' : 'Copy' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label">
|
||||
Tunnel private key
|
||||
<span v-if="tunnelSetup.privateKey" class="field-optional">shown once</span>
|
||||
</label>
|
||||
<textarea
|
||||
v-if="tunnelSetup.privateKey"
|
||||
:value="tunnelSetup.privateKey"
|
||||
class="textarea"
|
||||
rows="5"
|
||||
readonly
|
||||
></textarea>
|
||||
<p v-else class="hint">
|
||||
The key was shown when the target was added. Regenerate it if it was lost; the old key stops working.
|
||||
</p>
|
||||
<button
|
||||
v-if="tunnelSetup.privateKey"
|
||||
type="button"
|
||||
class="btn btn-sm btn-quiet"
|
||||
@click="copyTunnelValue(tunnelSetup.privateKey, 'setup-key')"
|
||||
>
|
||||
<component :is="copiedTunnel === 'setup-key' ? Check : Copy" :size="14" aria-hidden="true" />
|
||||
{{ copiedTunnel === 'setup-key' ? 'Copied' : 'Copy key' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="hint">
|
||||
Save the key as <code>rhema-tunnel-{{ tunnelSetup.id }}</code> in the directory where you run the command, then run <code>chmod 600</code> on it.
|
||||
</p>
|
||||
<p v-if="tunnelError" class="form-error" role="alert">{{ tunnelError }}</p>
|
||||
|
||||
<div class="dialog-actions">
|
||||
<button type="button" class="btn" @click="tunnelSetup = null">Close</button>
|
||||
<button type="button" class="btn" :disabled="tunnelBusy" @click="regenerateTunnelKey">
|
||||
{{ tunnelBusy ? 'Regenerating' : 'Regenerate key' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</BaseDialog>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
+9
-1
@@ -202,6 +202,8 @@ export interface IdResponse {
|
||||
id: string
|
||||
}
|
||||
|
||||
export type SandboxKind = 'direct' | 'tunnel'
|
||||
|
||||
export interface SandboxTarget {
|
||||
id: string
|
||||
name: string
|
||||
@@ -211,6 +213,8 @@ export interface SandboxTarget {
|
||||
workspace_root: string
|
||||
public_key: string
|
||||
host_fingerprint: string | null
|
||||
kind: SandboxKind
|
||||
tunnel_command: string | null
|
||||
}
|
||||
|
||||
export interface SandboxListResponse {
|
||||
@@ -219,7 +223,8 @@ export interface SandboxListResponse {
|
||||
|
||||
export interface CreateSandboxBody {
|
||||
name: string
|
||||
host: string
|
||||
kind?: SandboxKind
|
||||
host?: string
|
||||
port?: number
|
||||
user_name?: string
|
||||
workspace_root?: string
|
||||
@@ -229,6 +234,9 @@ export interface CreateSandboxBody {
|
||||
export interface CreateSandboxResponse {
|
||||
id: string
|
||||
public_key: string
|
||||
kind?: SandboxKind
|
||||
tunnel_private_key?: string
|
||||
tunnel_command?: string
|
||||
}
|
||||
|
||||
export interface TestSandboxResponse {
|
||||
|
||||
Reference in new issue
Block a user