Previews are served by the workspace agent because the files the agent
writes live in the workspace, and the agent already has an HTTP API that
coderd and workspace proxies can reach. Serving from disk on each
request makes a file preview a live view: edits show on reload, and
coderd stores nothing.
The ID is a hash of the path the agent asked for, so a stored
`open_preview` result keeps pointing at the same preview after a
republish, an agent restart, or a change to a symlink in that path. The
model chooses the path, so `os.Root` keeps every request inside it, and
names that start with a dot below it are refused.
<details>
<summary>Implementation details</summary>
The workspace agent can publish an absolute `.html` file, or a directory
containing `index.html`, and serve it from its existing HTTP API (port
4) under `/api/v0/previews/{id}/`. Publishing does not resolve symlinks,
so a path under a symlinked directory such as macOS `/tmp` publishes as
given, which the response returns. The preview ID is the first eight hex
digits of the SHA-256 of that path, so publishing a path again, even
after the agent restarts, returns the same ID. A different path whose ID
is already taken gets a 409. Adds `AgentConn.OpenPreview` to the
workspace SDK, which decodes the ID as `appurl.PreviewID` and returns
`ErrPreviewsUnsupported` when the agent predates the route.
Each request opens the published directory again through `os.Root`, so a
directory that is deleted and rebuilt keeps serving without publishing
it again. Symlinks and junctions are followed only while they stay
inside the published path, only regular files are served, and names that
start with a dot below a published directory, such as `.git` and `.env`,
are refused. Publishing a directory requires `index.html` at its root,
and there are no listings. On Windows, names containing `\`, `:` or `~`
are refused, because Windows reads them as a path separator, an
alternate data stream or a short name such as `HIDDEN~1`. Responses are
`no-store` and `nosniff`.
</details>
**Stack** (review bottom-up). Replaces the closed #31282 stack. Security
review: coder/security-assessments#437.
1. #32438 Agent file previews, this PR
2. #32439 Strict preview hosting and experiment
3. #32522 Preview sign-in
4. #32440 open_preview chat tool
5. #32441 Agents UI
6. #32442 Docs
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
125 lines
4.3 KiB
Go
125 lines
4.3 KiB
Go
package agent
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/coder/coder/v2/agent/agentchat"
|
|
"github.com/coder/coder/v2/coderd/httpapi"
|
|
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
|
|
"github.com/coder/coder/v2/coderd/tracing"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
|
"github.com/coder/coder/v2/httpmw"
|
|
)
|
|
|
|
func (a *agent) apiHandler(upgradeListener *httpUpgrader) http.Handler {
|
|
r := chi.NewRouter()
|
|
r.Use(
|
|
httpmw.Recover(a.logger),
|
|
tracing.StatusWriterMiddleware,
|
|
// Reuse the coderd tracing middleware with a noop tracer (nil provider):
|
|
// it emits no spans or telemetry on the agent and only enriches the log
|
|
// context with client_session_id. Tracks the API, debug (for
|
|
// support-bundle correlation), and root routes.
|
|
tracing.Middleware(nil, []string{"/", "/api", "/api/**", "/debug/**"}, "agent"),
|
|
loggermw.Logger(a.logger, nil),
|
|
agentchat.Middleware,
|
|
// Install WriteDeadlineMiddleware before tool call deduplication so retries also get the deadline.
|
|
a.acpAPI.WriteDeadlineMiddleware,
|
|
a.toolCalls.Middleware,
|
|
)
|
|
r.Get("/", func(rw http.ResponseWriter, r *http.Request) {
|
|
httpapi.Write(r.Context(), rw, http.StatusOK, codersdk.Response{
|
|
Message: "Hello from the agent!",
|
|
})
|
|
})
|
|
|
|
r.Mount("/api/v0", a.filesAPI.Routes())
|
|
r.Mount("/api/v0/git", a.gitAPI.Routes())
|
|
r.Mount("/api/v0/processes", a.processAPI.Routes())
|
|
r.Mount("/api/v0/previews", a.previewAPI.Routes())
|
|
r.Mount("/api/v0/tool-calls", a.toolCalls.Routes())
|
|
r.Mount("/api/v0/desktop", a.desktopAPI.Routes())
|
|
r.Mount("/api/v0/mcp", a.mcpAPI.Routes())
|
|
r.Mount("/api/v0/acp", a.acpAPI.Routes())
|
|
r.Mount("/api/v0/context-config", a.contextConfigAPI.Routes())
|
|
if a.contextAPI != nil {
|
|
r.Mount("/api/v0/context", a.contextAPI.Routes())
|
|
}
|
|
|
|
if a.devcontainers {
|
|
r.Mount("/api/v0/containers", a.containerAPI.Routes())
|
|
} else if manifest := a.manifest.Load(); manifest != nil && manifest.ParentID != uuid.Nil {
|
|
r.HandleFunc("/api/v0/containers", func(w http.ResponseWriter, r *http.Request) {
|
|
httpapi.Write(r.Context(), w, http.StatusForbidden, codersdk.Response{
|
|
Message: "Dev Container feature not supported.",
|
|
Detail: "Dev Container integration inside other Dev Containers is explicitly not supported.",
|
|
})
|
|
})
|
|
} else {
|
|
r.HandleFunc("/api/v0/containers", func(w http.ResponseWriter, r *http.Request) {
|
|
httpapi.Write(r.Context(), w, http.StatusForbidden, codersdk.Response{
|
|
Message: "Dev Container feature not enabled.",
|
|
Detail: "To enable this feature, set CODER_AGENT_DEVCONTAINERS_ENABLE=true in your template.",
|
|
})
|
|
})
|
|
}
|
|
|
|
promHandler := PrometheusMetricsHandler(a.prometheusRegistry, a.logger)
|
|
|
|
r.Get("/api/v0/listening-ports", a.listeningPortsHandler.handler)
|
|
r.Get("/api/v0/netcheck", a.HandleNetcheck)
|
|
r.Get("/api/v0/tcp/{port}", upgradeListener.handler)
|
|
r.Get("/debug/logs", a.HandleHTTPDebugLogs)
|
|
r.Get("/debug/magicsock", a.HandleHTTPDebugMagicsock)
|
|
r.Get("/debug/magicsock/debug-logging/{state}", a.HandleHTTPMagicsockDebugLoggingState)
|
|
r.Get("/debug/manifest", a.HandleHTTPDebugManifest)
|
|
r.Get("/debug/prometheus", promHandler.ServeHTTP)
|
|
|
|
return r
|
|
}
|
|
|
|
type ListeningPortsGetter interface {
|
|
GetListeningPorts() ([]codersdk.WorkspaceAgentListeningPort, error)
|
|
}
|
|
|
|
type listeningPortsHandler struct {
|
|
// In production code, this is set to an osListeningPortsGetter, but it can be overridden for
|
|
// testing.
|
|
getter ListeningPortsGetter
|
|
ignorePorts map[int]string
|
|
}
|
|
|
|
// handler returns a list of listening ports. This is tested by coderd's
|
|
// TestWorkspaceAgentListeningPorts test.
|
|
func (lp *listeningPortsHandler) handler(rw http.ResponseWriter, r *http.Request) {
|
|
ports, err := lp.getter.GetListeningPorts()
|
|
if err != nil {
|
|
httpapi.Write(r.Context(), rw, http.StatusInternalServerError, codersdk.Response{
|
|
Message: "Could not scan for listening ports.",
|
|
Detail: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
filteredPorts := make([]codersdk.WorkspaceAgentListeningPort, 0, len(ports))
|
|
for _, port := range ports {
|
|
if port.Port < workspacesdk.AgentMinimumListeningPort {
|
|
continue
|
|
}
|
|
|
|
// Ignore ports that we've been told to ignore.
|
|
if _, ok := lp.ignorePorts[int(port.Port)]; ok {
|
|
continue
|
|
}
|
|
filteredPorts = append(filteredPorts, port)
|
|
}
|
|
|
|
httpapi.Write(r.Context(), rw, http.StatusOK, codersdk.WorkspaceAgentListeningPortsResponse{
|
|
Ports: filteredPorts,
|
|
})
|
|
}
|