Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/local-remote-auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@maple/cli": minor
---

`maple start` can require credentials when it is reachable beyond loopback. Set `MAPLE_LOCAL_INGEST_KEY` to require a key on OTLP ingest (`Authorization: Bearer` or `x-maple-ingest-key`), and `MAPLE_LOCAL_ACCESS_TOKEN` to require sign-in for the dashboard and query API. The bundled dashboard shows a sign-in page, scripts send the token as a Bearer token, and CLI commands send it when the variable is set. Without them, a non-loopback start still runs and the banner warns that it is open.
13 changes: 13 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ jobs:
apps/cli/test/native-archive-gc-probe.sh
apps/cli/test/native-archive-merge-probe.sh
apps/cli/test/native-retention-probe.sh
apps/cli/test/native-remote-auth-smoke.sh

# The installers claim POSIX /bin/sh; check them against it.
- name: sh -n
Expand Down Expand Up @@ -485,6 +486,17 @@ jobs:
mkdir -p "$TMPDIR"
apps/cli/test/native-local-store-migration.sh "$GITHUB_WORKSPACE/dist"

# Ingest key, access token, sign-in and the CLI against a server off loopback.
- name: Run native remote auth smoke
timeout-minutes: 3
env:
KEEP_ROOT: "1"
TMPDIR: ${{ runner.temp }}/maple-native-remote-auth
MAPLE_TELEMETRY: off
run: |
mkdir -p "$TMPDIR"
apps/cli/test/native-remote-auth-smoke.sh "$GITHUB_WORKSPACE/dist"

# cancelled() too: a timeout or concurrency cancel mid-hang is the evidence that matters.
- name: Upload checkpoint failure evidence
if: ${{ failure() || cancelled() }}
Expand All @@ -495,6 +507,7 @@ jobs:
${{ runner.temp }}/maple-native-checkpoint
${{ runner.temp }}/maple-native-cp-refresh
${{ runner.temp }}/maple-native-migration
${{ runner.temp }}/maple-native-remote-auth
if-no-files-found: ignore

# Each leg rebuilds the ~400 MB bundle (~10s); uploading it once and downloading
Expand Down
3 changes: 2 additions & 1 deletion apps/cli/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
import { TelemetryLayer } from "./core/telemetry"
import { maybeNotifyUpdate } from "./core/update"
import { maybeNotifyWhatsNew } from "./core/changelog"
import { LocalAccessHttpClient } from "./core/local-access"
import { WarehouseExecutorFromMode } from "./core/warehouse"
import { debugEnabled } from "./lib/debug"
import { makeHelpCapture, usageHint } from "./lib/help"
Expand All @@ -33,7 +34,7 @@ const MainLayer = WarehouseExecutorFromMode.pipe(
Layer.provideMerge(Mode.layer),
Layer.provideMerge(MapleConfig.layer),
Layer.provideMerge(BunServices.layer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(LocalAccessHttpClient.pipe(Layer.provide(FetchHttpClient.layer))),
)

// Throttled, non-blocking "update available" notice before dispatching the
Expand Down
40 changes: 37 additions & 3 deletions apps/cli/src/commands/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from "node:fs"
import { dirname, resolve } from "node:path"
import { ServerBindError, startServer } from "../server/serve"
import { ACCESS_TOKEN_ENV, INGEST_KEY_ENV, type RemoteAuth, remoteAuthFromEnv } from "../server/remote-auth"
import { CURRENT_LOCAL_SCHEMA } from "../server/schema-identity"
import {
adoptLegacySidecars,
Expand Down Expand Up @@ -94,7 +95,7 @@ import {
startedBeforeWrite,
validateHost,
} from "./server-args"
import { DEFAULT_LOCAL_PORT } from "../lib/local-address"
import { DEFAULT_LOCAL_PORT, isLoopbackHostname } from "../lib/local-address"

/**
* A refused command whose precondition simply wasn't met: the server is already
Expand Down Expand Up @@ -160,6 +161,20 @@ const validatedHost = (source: string, value: string): Effect.Effect<string, Ser
new ServerOptionError({ source, message: `invalid ${source}: ${describeError(error)}` }),
})

/**
* What the banner says about authentication: which secrets guard the listener,
* or a warning when a non-loopback listener leaves ingest or reads open.
*/
export const authSummary = (auth: RemoteAuth, bindHost: string): string | undefined => {
const open = [
...(auth.ingestKey === undefined ? [`ingest (${INGEST_KEY_ENV})`] : []),
...(auth.accessToken === undefined ? [`dashboard and queries (${ACCESS_TOKEN_ENV})`] : []),
]
if (open.length === 0) return "ingest key + access token"
if (isLoopbackHostname(bindHost)) return undefined
return amber(`⚠ open to anyone who can reach this address: ${open.join(", ")}`)
}

/** The startup banner shown once the server is listening. `dashboardUrl` is the
* URL the user should open (the auto-updating `local.maple.dev` by default, or
* the bundled same-origin UI with `--offline`); `undefined` when no UI. */
Expand All @@ -170,6 +185,7 @@ const startBanner = (
dashboardUrl: string | undefined,
offline: boolean,
scope: CommandScope,
authLine: string | undefined,
): string => {
// No leading indent here: the gutter below supplies it.
const row = (key: string, value: string) => `${dim(key.padEnd(11))}${value}`
Expand All @@ -190,6 +206,7 @@ const startBanner = (
]
: []),
row("data", prettyPath(dataDir)),
...(authLine === undefined ? [] : [row("auth", authLine)]),
row("pid", `${process.pid} ${dim("· stop with")} ${bold(mapleCommand("stop", scope))}`),
]

Expand Down Expand Up @@ -513,7 +530,7 @@ const port = Flag.Int("port").pipe(

const host = Flag.String("host").pipe(
Flag.withDescription(
"Local server host (env: MAPLE_LOCAL_BIND_HOST; non-loopback start exposes unauthenticated ingest and queries)",
`Local server host (env: MAPLE_LOCAL_BIND_HOST; off loopback, set ${INGEST_KEY_ENV} and ${ACCESS_TOKEN_ENV})`,
),
Flag.withDefault(resolveBindHost(process.env.MAPLE_LOCAL_BIND_HOST)),
)
Expand Down Expand Up @@ -979,6 +996,7 @@ interface DetachedStart {
readonly minimumRawTelemetryRetentionDays: number | undefined
readonly checkpointInterval: string
readonly scope: CommandScope
readonly authLine: string | undefined
}

type ChildReadiness = { readonly kind: "ready" } | { readonly kind: "exited" } | { readonly kind: "timeout" }
Expand Down Expand Up @@ -1127,6 +1145,7 @@ const startDetached = (options: DetachedStart) =>
` ${dim("listening")} ${cyan(underline(bindAddr))}\n` +
(connectAddr === bindAddr ? "" : ` ${dim("connect")} ${cyan(connectAddr)}\n`) +
(dashboardUrl === undefined ? "" : ` ${dim("dashboard")} ${cyan(dashboardUrl)}\n`) +
(options.authLine === undefined ? "" : ` ${dim("auth")} ${options.authLine}\n`) +
` ${dim("env")} export OTEL_EXPORTER_OTLP_ENDPOINT=${connectAddr}\n` +
` ${dim("logs")} ${prettyPath(logPath)}\n` +
` ${dim("stop")} ${bold(mapleCommand("stop", options.scope))}\n`,
Expand Down Expand Up @@ -1172,6 +1191,11 @@ export const start = Command.make("start", {
const fs = yield* FileSystem
const dataDir = resolve(Option.getOrUndefined(a.dataDir) ?? defaultDataDir())
const bindHost = yield* validatedHost("--host / MAPLE_LOCAL_BIND_HOST", a.host)
const auth = yield* Effect.fromResult(remoteAuthFromEnv(process.env)).pipe(
Effect.mapError(
(error) => new ServerOptionError({ source: error.source, message: error.message }),
),
)
// Rejected up front, before anything is opened: a typo that quietly fell
// back to the default (or worse, to off) would reintroduce the data loss
// the refresh loop exists to prevent.
Expand Down Expand Up @@ -1423,6 +1447,7 @@ export const start = Command.make("start", {
minimumRawTelemetryRetentionDays: requestedRetentionDays,
checkpointInterval: a.checkpointInterval,
scope,
authLine: authSummary(auth, bindHost),
})
}

Expand Down Expand Up @@ -1450,6 +1475,7 @@ export const start = Command.make("start", {
configFile: chdbConfigFile,
minimumRawTelemetryRetentionDays: requestedRetentionDays,
assets,
auth,
})
started = true
yield* clearStartFailures(dataDir)
Expand Down Expand Up @@ -1496,7 +1522,15 @@ export const start = Command.make("start", {
: hostedDashboardUrl(hostedUiUrl, boundPort)
yield* Effect.sync(() =>
process.stderr.write(
startBanner(bindAddr, connectAddr, dataDir, dashboardUrl, a.offline, boundScope),
startBanner(
bindAddr,
connectAddr,
dataDir,
dashboardUrl,
a.offline,
boundScope,
authSummary(auth, bindHost),
),
),
)

Expand Down
57 changes: 57 additions & 0 deletions apps/cli/src/core/local-access.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { networkInterfaces } from "node:os"
import { Effect, Layer, Result } from "effect"
import { HttpClient, HttpClientRequest } from "effect/http"
import { defaultLocalUrl, isLoopbackHostname } from "../lib/local-address"
import { ACCESS_TOKEN_ENV } from "../server/remote-auth"

const bare = (hostname: string): string => hostname.replace(/^\[(.*)\]$/, "$1").toLowerCase()

/** Scheme and host of the configured target; any port, since a discovered server may not use the default. */
const targetOf = (value: string): { readonly protocol: string; readonly host: string } | undefined => {
const url = Result.try(() => new URL(value))
return Result.isSuccess(url)
? { protocol: url.success.protocol, host: bare(url.success.hostname) }
: undefined
}

/** This machine's own addresses: a server started with `--host <interface IP>` is found there. */
const ownAddresses = (): ReadonlySet<string> =>
new Set(
Object.values(networkInterfaces())
.flatMap((entries) => entries ?? [])
.map((entry) => bare(entry.address)),
)

/**
* Adds the access token to `/local/*` calls on the host the CLI targets (same
* scheme, so an https target never gets it over http), or on this machine
* (loopback or one of its own addresses). Other hosts never see it.
*/
export const withLocalAccessToken =
(token: string | undefined, localUrl: string, localHosts: ReadonlySet<string> = ownAddresses()) =>
(request: HttpClientRequest.HttpClientRequest): HttpClientRequest.HttpClientRequest => {
if (token === undefined || request.headers.authorization !== undefined) return request
const parsed = Result.try(() => new URL(request.url))
if (Result.isFailure(parsed) || !parsed.success.pathname.startsWith("/local/")) return request
const url = parsed.success
const host = bare(url.hostname)
const target = targetOf(localUrl)
const isTarget = target !== undefined && host === target.host && url.protocol === target.protocol
return isTarget || isLoopbackHostname(url.hostname) || localHosts.has(host)
? HttpClientRequest.bearerToken(request, token)
: request
}

/** The CLI's HttpClient, signed in to a self-hosted server through `MAPLE_LOCAL_ACCESS_TOKEN`. */
export const LocalAccessHttpClient = Layer.effect(
HttpClient.HttpClient,
Effect.map(HttpClient.HttpClient, (client) =>
HttpClient.mapRequest(
client,
withLocalAccessToken(
process.env[ACCESS_TOKEN_ENV]?.trim() || undefined,
process.env.MAPLE_LOCAL_URL ?? defaultLocalUrl(process.env.MAPLE_LOCAL_BIND_HOST),
),
),
),
)
Loading
Loading