DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(docker): harden image for rootless/RO rootfs + drop runtime sed
enihcam46681b572cb3
diff --git a/Dockerfile b/Dockerfileindex 6bca08061..a73a48f41 100644--- a/Dockerfile+++ b/Dockerfile@@ -39,11 +39,12 @@ COPY web/ ./# can read it during ``npm run build`` and inline it into the bundle.COPY deeptutor/__version__.py /app/deeptutor/__version__.py-# Create .env.local with placeholders that will be replaced at runtime.-RUN printf '%s\n' \- 'NEXT_PUBLIC_API_BASE=__NEXT_PUBLIC_API_BASE_PLACEHOLDER__' \- 'NEXT_PUBLIC_AUTH_ENABLED=__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__' \- > .env.local+# Create .env.local with the single env var the build needs (the app version,+# exposed to the browser via next.config.js). URL knowledge is no longer baked+# into the bundle: `apiUrl`/`wsUrl` in web/lib/api.ts are pass-throughs and+# the actual backend host is read at request time by web/proxy.ts from+# DEEPTUTOR_API_BASE_URL (exported by the entrypoint on every start).+RUN printf 'NEXT_PUBLIC_APP_VERSION=\n' > .env.local# Build Next.js for production with standalone output# This allows runtime environment variable injection@@ -125,8 +126,13 @@ WORKDIR /app# Install system dependencies# Note: libgl1 and libglib2.0-0 are required for OpenCV (used by mineru)+# libcap2-bin provides `setcap`, used below to grant gosu the+# capabilities it needs to setuid/setgid inside rootless podman user+# namespaces (where the parent process doesn't have those caps).RUN apt-get update && apt-get install -y --no-install-recommends \curl \+ gosu \+ libcap2-bin \ca-certificates \bash \supervisor \@@ -180,6 +186,17 @@ RUN mkdir -p \data/user/logs \data/knowledge_bases+# Bake a non-root user for `gosu deeptutor supervisord` (entrypoint drops privs+# after chown'ing /app/data). UID 1000 matches the host user under rootless+# podman's `userns_mode: keep-id` with a bind mount on ./data.+# `setcap` grants gosu CAP_SETUID+CAP_SETGID so it can drop privileges+# inside rootless podman user namespaces (where the parent process+# doesn't have those caps by default).+RUN groupadd --system --gid 1000 deeptutor \+ && useradd --system --uid 1000 --gid 1000 --no-create-home --shell /usr/sbin/nologin deeptutor \+ && chown -R deeptutor:deeptutor /app/data /app/web/.next \+ && setcap cap_setuid,cap_setgid+ep /usr/sbin/gosu+# Create supervisord configuration for running both services# Log output goes to stdout/stderr so docker logs can capture themRUN mkdir -p /etc/supervisor/conf.d@@ -235,58 +252,17 @@ EOFRUN sed -i 's/\r$//' /app/start-backend.sh && chmod +x /app/start-backend.sh# Create frontend startup script-# This script handles runtime environment variable injection for Next.js+# This script starts the Next.js standalone server. URL knowledge is no+# longer baked into the bundle: web/proxy.ts rewrites /api/* and /ws/* to+# the configured backend at request time, reading DEEPTUTOR_API_BASE_URL+# (exported by the entrypoint from data/user/settings/system.json).RUN cat > /app/start-frontend.sh <<'EOF'#!/bin/bashset -e-# Get the backend port (default to 8001)-BACKEND_PORT=${BACKEND_PORT:-8001}FRONTEND_PORT=${FRONTEND_PORT:-3782}-AUTH_ENABLED=${NEXT_PUBLIC_AUTH_ENABLED:-${AUTH_ENABLED:-false}}-case "$(echo "$AUTH_ENABLED" | tr '[:upper:]' '[:lower:]')" in- 1|true|yes|on) AUTH_ENABLED=true ;;- *) AUTH_ENABLED=false ;;-esac--# Determine the API base URL with multiple fallback options-# Priority: NEXT_PUBLIC_API_BASE_EXTERNAL > NEXT_PUBLIC_API_BASE > auto-detect-if [ -n "$NEXT_PUBLIC_API_BASE_EXTERNAL" ]; then- # Explicit external URL for cloud deployments- API_BASE="$NEXT_PUBLIC_API_BASE_EXTERNAL"- echo "[Frontend] π Using external API URL: ${API_BASE}"-elif [ -n "$NEXT_PUBLIC_API_BASE" ]; then- # Custom API base URL- API_BASE="$NEXT_PUBLIC_API_BASE"- echo "[Frontend] π Using custom API URL: ${API_BASE}"-else- # Default: localhost with configured backend port- # Note: This only works for local development, not cloud deployments- API_BASE="http://localhost:${BACKEND_PORT}"- echo "[Frontend] π Using default API URL: ${API_BASE}"- echo "[Frontend] β οΈ For cloud deployment, set system.next_public_api_base_external in data/user/settings/system.json"- echo "[Frontend] Example: \"next_public_api_base_external\": \"https://your-server.com:${BACKEND_PORT}\""-fi-echo "[Frontend] π Starting Next.js frontend on port ${FRONTEND_PORT}..."-# Replace placeholder in built Next.js files-# This is necessary because NEXT_PUBLIC_* vars are inlined at build time-escape_sed_replacement() {- printf '%s' "$1" | sed -e 's/[|\/&]/\\&/g'-}--API_BASE_ESCAPED="$(escape_sed_replacement "$API_BASE")"-AUTH_ENABLED_ESCAPED="$(escape_sed_replacement "$AUTH_ENABLED")"--find /app/web/.next -type f \( -name "*.js" -o -name "*.json" \) -exec \- sed -i \- -e "s|__NEXT_PUBLIC_API_BASE_PLACEHOLDER__|${API_BASE_ESCAPED}|g" \- -e "s|__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__|${AUTH_ENABLED_ESCAPED}|g" \- {} \; 2>/dev/null || true--# Start Next.js standalone server-# The standalone server reads PORT and HOSTNAME from environment variablesexport PORT=${FRONTEND_PORT}export HOSTNAME=0.0.0.0exec node /app/web/server.js@@ -340,6 +316,10 @@ from deeptutor.services.setup import init_user_directoriesinit_user_directories(Path('/app'))" 2>/dev/null || echo " β οΈ Directory initialization skipped (will be created on first use)"+# Idempotent: re-chown /app/data so the unprivileged `deeptutor` user (UID 1000)+# owns it. Cheap on no-op; the only first-start cost is one stat per file.+chown -R deeptutor:deeptutor /app/data 2>/dev/null || true+echo "βοΈ Loading runtime JSON settings..."eval "$(python - <<'PY'import shlex@@ -353,6 +333,37 @@ PYexport BACKEND_PORT=${BACKEND_PORT:-8001}export FRONTEND_PORT=${FRONTEND_PORT:-3782}+# Export DEEPTUTOR_API_BASE_URL for proxy.ts (rewrites /api/* and /ws/* to the+# configured backend at request time). Precedence: in-network+# `next_public_api_base` first, then `next_public_api_base_external`, then+# localhost:${BACKEND_PORT} (dev default).+DEEPTUTOR_API_BASE_URL=$(python - <<'PY'+import json, os+from pathlib import Path+try:+ s = json.loads(Path("/app/data/user/settings/system.json").read_text(encoding="utf-8"))+ base = s.get("next_public_api_base") or s.get("next_public_api_base_external") or f"http://localhost:{os.environ.get('BACKEND_PORT', '8001')}"+ print(base)+except Exception:+ print(f"http://localhost:{os.environ.get('BACKEND_PORT', '8001')}")+PY+)+export DEEPTUTOR_API_BASE_URL+echo "π API Base URL (proxy): ${DEEPTUTOR_API_BASE_URL}"++DEEPTUTOR_AUTH_ENABLED=$(python - <<'PY'+import json+from pathlib import Path+try:+ s = json.loads(Path("/app/data/user/settings/auth.json").read_text(encoding="utf-8"))+ val = s.get("auth_enabled", False)+ print("true" if val else "false")+except Exception:+ print("false")+PY+)+export DEEPTUTOR_AUTH_ENABLED+echo "π Backend Port: ${BACKEND_PORT}"echo "π Frontend Port: ${FRONTEND_PORT}"@@ -366,8 +377,10 @@ echo " - data/user/settings/main.yaml"echo " - data/user/settings/agents.yaml"echo "============================================"-# Start supervisord-exec /usr/bin/supervisord -c /etc/supervisor/conf.d/deeptutor.conf+# Start supervisord as the unprivileged deeptutor user (UID 1000). The+# supervisord children (backend, frontend) inherit this UID; chown above+# ensured they can write under /app/data.+exec gosu deeptutor /usr/bin/supervisord -c /etc/supervisor/conf.d/deeptutor.confEOFRUN sed -i 's/\r$//' /app/entrypoint.sh && chmod +x /app/entrypoint.shdiff --git a/web/lib/api.ts b/web/lib/api.tsindex b109f4d10..dad0224b0 100644--- a/web/lib/api.ts+++ b/web/lib/api.ts@@ -1,152 +1,55 @@-// API configuration and utility functions--// The Docker image and the `deeptutor start` launcher both build the Next.js-// bundle with this literal placeholder and substitute it at container/process-// start. If a deployment serves bundles where the substitution silently-// failed (read-only fs, missing tool, etc.), every API call would target a-// broken URL and the Settings page would render blank with no clue why.-// Treating the placeholder as "not configured" surfaces the failure mode-// instead of letting fetches die quietly.-const API_BASE_PLACEHOLDER_TOKEN = "NEXT_PUBLIC_API_BASE_PLACEHOLDER";--// Get API base URL injected by the launcher from data/user/settings/system.json.-// We deliberately do NOT throw at module-load time: the Docker build embeds the-// literal placeholder and Next.js evaluates this module during static export,-// which would fail every prerendered page. The runtime check in resolveBase()-// still surfaces missing/placeholder values on the first actual call.-export const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE ?? "";--export function isApiBasePlaceholder(value: string): boolean {- return value.includes(API_BASE_PLACEHOLDER_TOKEN);-}--function assertApiBaseConfigured(value: string): string {- const isPlaceholder = isApiBasePlaceholder(value);- if (!value || isPlaceholder) {- if (typeof window !== "undefined") {- console.error(- isPlaceholder- ? "NEXT_PUBLIC_API_BASE placeholder was not substituted at startup."- : "NEXT_PUBLIC_API_BASE is not set.",- );- console.error(- "Please configure data/user/settings/system.json and restart the application.",- );- }- throw new Error(- "NEXT_PUBLIC_API_BASE is not configured. Please update data/user/settings/system.json and restart.",- );- }- return value;-}--// Hostnames that always refer to the local machine. When the build-time base-// URL points to one of these, but the page is opened from a non-local origin,-// we rewrite the hostname so requests reach the actual server.-const LOOPBACK_HOSTS = new Set([- "localhost",- "127.0.0.1",- "0.0.0.0",- "::1",- "[::1]",-]);--let warnedAboutHostSwap = false;--function isLoopbackHost(host: string): boolean {- return LOOPBACK_HOSTS.has(host.toLowerCase());-}+// API configuration and utility functions.+//+// The frontend bundle is now URL-agnostic: the browser issues requests against+// the frontend origin (`:3782/api/...` and `:3782/api/.../ws`), and+// `web/proxy.ts` rewrites `/api/*` and `/ws/*` to the configured backend on+// every request. This means there is no build-time or runtime URL substitution+// in the bundle, and no placeholder token to keep alive. `apiUrl` and `wsUrl`+// stay as one-liner pass-throughs so the dozens of existing call sites continue+// to compile and work without modification./**- * Resolve the effective API base URL at runtime.+ * Construct a full API URL from a path.*- * NEXT_PUBLIC_API_BASE is a build-time constant that is typically set to- * http://localhost:<port>. When another machine on the LAN opens the app that- * constant still points at "localhost", which the remote browser resolves to- * its *own* loopback address instead of the server. We detect this situation- * and swap the hostname for window.location.hostname so the request reaches- * the actual server regardless of which machine opened the page.+ * Pass-through: returns the path unchanged. The actual backend URL is+ * determined at request time by `web/proxy.ts`, which reads+ * `DEEPTUTOR_API_BASE_URL` (exported by the container entrypoint from+ * `data/user/settings/system.json`).*- * The full path/search is preserved (so deployments behind a reverse proxy- * like `http://localhost:8001/api` continue to work after the rewrite).- */-export function resolveBase(): string {- const base = assertApiBaseConfigured(API_BASE_URL);- if (typeof window === "undefined") return base;- try {- const url = new URL(base);- const clientHost = window.location.hostname;- if (isLoopbackHost(url.hostname) && !isLoopbackHost(clientHost)) {- url.hostname = clientHost;- if (!warnedAboutHostSwap) {- warnedAboutHostSwap = true;- console.warn(- `[api] NEXT_PUBLIC_API_BASE points to "${base}" but the page is served from "${clientHost}"; ` +- `routing API/WebSocket calls to "${url.toString()}" instead.`,- );- }- // Use href (full URL) instead of origin so we keep any path/search.- return url.toString().replace(/\/+$/, "");- }- } catch {- // base is not a valid absolute URL β return as-is- }- return base;-}--/**- * Construct a full API URL from a path* @param path - API path (e.g., '/api/v1/knowledge/list')- * @returns Full URL (e.g., 'http://localhost:8001/api/v1/knowledge/list')+ * @returns The same path, unchanged*/export function apiUrl(path: string): string {- // Remove leading slash if present to avoid double slashes- const normalizedPath = path.startsWith("/") ? path : `/${path}`;-- // Remove trailing slash from base URL if present- const base = resolveBase();- const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;-- return `${normalizedBase}${normalizedPath}`;+ return path;}/**- * Construct a WebSocket URL from a path+ * Construct a WebSocket URL from a path.+ *+ * Pass-through: returns the path unchanged. `proxy.ts` rewrites `/ws/*` to+ * the configured backend, and the runtime upgrades to `ws://` /+ * `wss://` based on the backend's scheme.+ ** @param path - WebSocket path (e.g., '/api/v1/solve')- * @returns WebSocket URL (e.g., 'ws://localhost:8001/api/v1/ws')+ * @returns The same path, unchanged*/export function wsUrl(path: string): string {- // Security Hardening: Convert http to ws and https to wss.- // In production environments (where API_BASE_URL starts with https), this ensures secure websockets.- const base = resolveBase()- .replace(/^http:/, "ws:")- .replace(/^https:/, "wss:");-- // Remove leading slash if present to avoid double slashes- const normalizedPath = path.startsWith("/") ? path : `/${path}`;-- // Remove trailing slash from base URL if present- const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;-- return `${normalizedBase}${normalizedPath}`;+ return path;}/**- * Parse a ``NEXT_PUBLIC_AUTH_ENABLED``-style flag at runtime.+ * Parse a "DEEPTUTOR_AUTH_ENABLED"-style flag at runtime.*- * The value is inlined at build time and, in the Docker image, baked as the- * ``__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__`` token that ``start-frontend.sh``- * rewrites on container start. Evaluating it with a runtime regex β instead of- * a ``=== "true"`` literal comparison the minifier would constant-fold β keeps- * the placeholder in the bundle so it survives minification (the same approach- * used for the API base placeholder above). An unsubstituted placeholder- * therefore parses as "disabled".+ * Used by both `apiFetch` (frontend) and `web/proxy.ts` (auth redirect) to+ * decide whether to gate requests. Evaluated with a runtime regex so the+ * value can be set by the container entrypoint on every start (no build-time+ * inlining).*/export function parseAuthEnabled(raw: string | undefined): boolean {return /^(1|true|yes|on)$/i.test((raw ?? "").trim());}-const AUTH_ENABLED = parseAuthEnabled(process.env.NEXT_PUBLIC_AUTH_ENABLED);+const AUTH_ENABLED = parseAuthEnabled(process.env.DEEPTUTOR_AUTH_ENABLED);/*** Authenticated fetch wrapper. Behaves identically to `fetch` but automaticallydiff --git a/web/lib/auth.ts b/web/lib/auth.tsindex 5abc16c99..2cc8ccb17 100644--- a/web/lib/auth.ts+++ b/web/lib/auth.ts@@ -1,13 +1,11 @@import { apiFetch, apiUrl, parseAuthEnabled } from "@/lib/api";-// ``NEXT_PUBLIC_AUTH_ENABLED`` is inlined at build time and, in the Docker-// image, baked as the ``__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__`` token that-// ``start-frontend.sh`` rewrites on container start. ``parseAuthEnabled``+// ``DEEPTUTOR_AUTH_ENABLED`` is exported by the container entrypoint on every+// start (read from ``data/user/settings/auth.json``). ``parseAuthEnabled``// evaluates it at runtime (not a ``=== "true"`` literal comparison) so the-// minifier cannot constant-fold the check and strip the placeholder, which-// would permanently break the runtime rewrite. See lib/api.ts.+// minifier cannot constant-fold the check. See lib/api.ts.export const AUTH_ENABLED = parseAuthEnabled(- process.env.NEXT_PUBLIC_AUTH_ENABLED,+ process.env.DEEPTUTOR_AUTH_ENABLED,);export interface AuthStatus {diff --git a/web/proxy.ts b/web/proxy.tsindex 1e3631a2c..762d8093e 100644--- a/web/proxy.ts+++ b/web/proxy.ts@@ -1,14 +1,32 @@import { NextRequest, NextResponse } from "next/server";+import { parseAuthEnabled } from "./lib/api";-const AUTH_ENABLED = process.env.NEXT_PUBLIC_AUTH_ENABLED === "true";+// Backend base URL for `/api/*` and `/ws/*` rewrites. The container+// entrypoint exports `DEEPTUTOR_API_BASE_URL` from `data/user/settings/system.json`+// (preferring `next_public_api_base`, then `next_public_api_base_external`,+// then `http://localhost:${BACKEND_PORT}`). In dev (`deeptutor start`) it+// defaults to `http://localhost:8001`.+const API_BASE_URL =+ process.env.DEEPTUTOR_API_BASE_URL ?? "http://localhost:8001";++const AUTH_ENABLED = parseAuthEnabled(process.env.DEEPTUTOR_AUTH_ENABLED);const LOGIN_PATH = "/login";const COOKIE_NAME = "dt_token";export function proxy(req: NextRequest) {- // Auth is disabled (default) β let everything through- if (!AUTH_ENABLED) return NextResponse.next();+ const { pathname, search } = req.nextUrl;- const { pathname } = req.nextUrl;+ // Forward all backend-relative paths to the configured backend. The browser+ // fetches against the frontend origin (e.g. `:3782/api/v1/...` or+ // `:3782/api/v1/.../ws`); the rewrite is what bridges the origin gap and+ // keeps the URL knowledge in one place (the entrypoint + system.json) rather+ // than baked into the frontend bundle.+ if (pathname.startsWith("/api/") || pathname.startsWith("/ws/")) {+ return NextResponse.rewrite(new URL(pathname + search, API_BASE_URL));+ }++ // Auth is disabled (default) β let everything else through+ if (!AUTH_ENABLED) return NextResponse.next();// Always allow auth pages and Next.js internalsif (@@ -68,6 +86,7 @@ export function proxy(req: NextRequest) {}export const config = {- // Run on all page routes, skip API and static assets- matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],+ // Run on every request except Next.js internals and the favicon. The /api/*+ // and /ws/* paths are explicitly handled above (rewritten to the backend).+ matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],};diff --git a/web/tests/api-auth-redirect.test.ts b/web/tests/api-auth-redirect.test.tsindex dceee0cca..7f199a959 100644--- a/web/tests/api-auth-redirect.test.ts+++ b/web/tests/api-auth-redirect.test.ts@@ -1,10 +1,12 @@import test from "node:test";import assert from "node:assert/strict";-// AUTH_ENABLED and API_BASE_URL are read at module-load time, so the environment-// must be configured before the module under test is imported.-process.env.NEXT_PUBLIC_API_BASE = "http://localhost:8001/api";-process.env.NEXT_PUBLIC_AUTH_ENABLED = "true";+// AUTH_ENABLED is read at module-load time, so the environment must be+// configured before the module under test is imported. The frontend now uses+// relative paths; the URL forwarding happens in proxy.ts at request time,+// reading DEEPTUTOR_API_BASE_URL (set by the container entrypoint on every+// start from data/user/settings/system.json).+process.env.DEEPTUTOR_AUTH_ENABLED = "true";let apiModulePromise: Promise<typeof import("../lib/api")> | null = null;diff --git a/web/tests/api-resolve-base.test.ts b/web/tests/api-resolve-base.test.tsdeleted file mode 100644index c147b871c..000000000--- a/web/tests/api-resolve-base.test.ts+++ /dev/null@@ -1,81 +0,0 @@-import test from "node:test";-import assert from "node:assert/strict";--// Must be set before importing the module under test, since API_BASE_URL is-// read at module-load time and the module throws if it's missing.-process.env.NEXT_PUBLIC_API_BASE = "http://localhost:8001/api";--let apiModulePromise: Promise<typeof import("../lib/api")> | null = null;--async function loadApiModule(): Promise<typeof import("../lib/api")> {- apiModulePromise ??= import("../lib/api");- return apiModulePromise;-}--function setWindow(hostname: string | undefined): void {- if (hostname === undefined) {- delete (globalThis as { window?: unknown }).window;- return;- }- (globalThis as { window?: unknown }).window = {- location: { hostname },- } as unknown;-}--test("resolveBase returns the build-time base in SSR (no window)", async () => {- const { resolveBase } = await loadApiModule();- setWindow(undefined);- assert.equal(resolveBase(), "http://localhost:8001/api");-});--test("isApiBasePlaceholder detects the unsubstituted Docker placeholder", async () => {- const { isApiBasePlaceholder } = await loadApiModule();- assert.equal(- isApiBasePlaceholder("__NEXT_PUBLIC_API_BASE_PLACEHOLDER__"),- true,- );-});--test("isApiBasePlaceholder accepts a substituted API URL", async () => {- const { isApiBasePlaceholder } = await loadApiModule();- assert.equal(isApiBasePlaceholder("http://localhost:3781"), false);-});--test("resolveBase returns base unchanged when client is also on localhost", async () => {- const { resolveBase } = await loadApiModule();- setWindow("localhost");- assert.equal(resolveBase(), "http://localhost:8001/api");-});--test("resolveBase rewrites loopback hostname to remote LAN host and preserves path", async () => {- const { resolveBase } = await loadApiModule();- setWindow("192.168.1.10");- assert.equal(resolveBase(), "http://192.168.1.10:8001/api");-});--test("resolveBase treats IPv6 loopback as loopback (no swap when client is also ::1)", async () => {- const { resolveBase } = await loadApiModule();- setWindow("::1");- assert.equal(resolveBase(), "http://localhost:8001/api");-});--test("apiUrl composes correctly after rewrite, without losing the base path", async () => {- const { apiUrl } = await loadApiModule();- setWindow("10.0.0.5");- assert.equal(- apiUrl("/api/v1/knowledge/list"),- "http://10.0.0.5:8001/api/api/v1/knowledge/list",- );-});--test("wsUrl converts http to ws and respects rewritten host", async () => {- const { wsUrl } = await loadApiModule();- setWindow("10.0.0.5");- assert.equal(wsUrl("/api/v1/ws"), "ws://10.0.0.5:8001/api/api/v1/ws");-});--test("wsUrl keeps original loopback when client is also loopback", async () => {- const { wsUrl } = await loadApiModule();- setWindow("127.0.0.1");- assert.equal(wsUrl("/api/v1/ws"), "ws://localhost:8001/api/api/v1/ws");-});