Files
OwnCord/Server/plugin/host_ui.go
T
Claude d320a8b587 fix(review): address 11 Copilot review findings on PR #1132
Clean sweep of every actionable item from the two Copilot review passes
on head 59ae4d8. Grouped by severity:

─── Crash / security (must-fix) ─────────────────────────────────────

1. main.go:140 — telemetryShutdown nil panic.
   telemetry.Init can return (nil, err) on the -tags otel skeleton
   path; the deferred closure would then call a nil function. Normalise
   to a no-op shutdown when Init errors so the defer is always safe.

2. api/upload_handler.go — permSvc nil deref.
   MountUploadRoutes + handleServeFile dereference permSvc on every
   authenticated file request. Add a fail-fast panic at mount time so
   the misconfiguration surfaces at wiring, not on the first 500.
   Update upload_handler_test.go to pass a real PermissionService built
   on the test DB (the existing tests were missing the argument entirely,
   which meant the package wouldn't compile — this fixes the real bug
   Copilot flagged).

3. ws/event_persister.go — NewEventPersister nil EventStore panic.
   run() dereferences p.store on every flush. Panic at constructor
   time instead so the crash happens once at startup rather than
   minutes later in a background goroutine.

4. plugin/host_ui.go — serve-time symlink check.
   rejectSymlinksUnder only runs at install time, so a symlink created
   post-install (accidental or malicious) would be followed by
   http.ServeFile and leak host files. Add an os.Lstat + ModeSymlink
   check + IsRegular check to AssetHandler on every request. Cheap
   relative to the file read and closes the TOCTOU window.

─── Correctness / observability (should-fix) ───────────────────────

5. ws/deps.go:77 — requirePerm hides misconfig as FORBIDDEN.
   Previously, nil database, nil perms, or a GetRoleForUser error all
   returned ErrCodeForbidden with the same message, making operator
   failures indistinguishable from legitimate permission denials.
   Split the branches: misconfig + DB error now return ErrCodeInternal
   with a server-side slog.Error so operators see the real problem;
   FORBIDDEN is reserved for the actual permission-bit check.

6. telemetry/metrics.go — ServiceCallDurationMs renamed to Sec.
   Field name said "Ms" but the instrument name was
   `service_call_duration_seconds` with unit "s". Renamed the field
   and updated all 8 service-layer callers so the struct field and
   metric semantics match.

7. ws/event_persister.go — flushEvy typo → flushEvery.
   Renamed the field and the one call site in run().

─── Comments out of sync with code ──────────────────────────────────

8. plugin/loader.go — Stat vs Lstat comment.
   The comment claimed "Stat (not Lstat)" but the code correctly uses
   os.Lstat to detect symlinks. Updated the comment to match the code;
   the code was already right.

9. telemetry/telemetry_otel.go — compile claim wrong.
   Comment said the file would fail to compile without the upstream
   OTel modules, but the skeleton deliberately avoids importing them
   and Init returns a runtime error instead. Updated the comment to
   reflect actual CI behaviour (the -tags otel build step passes
   today but doesn't exercise real telemetry).

─── Nit / polish ────────────────────────────────────────────────────

10. ws/event_pruner.go — startup delay magic constant.
    Hard-coded time.Minute made the "run shortly after startup"
    behaviour untestable (a test with a 100ms interval would still
    wait a full minute). Cap the startup delay by the interval:
    min(interval, time.Minute). Documented via a new `maxStartupDelay`
    constant.

11. ws/event_pruner_test.go — new file.
    Unit coverage for runPrune cutoff correctness, error swallowing,
    StartEventPruner nil-store short-circuit, ctx cancellation, and
    the interval-bounded startup delay from fix #10. Uses a fakeEventStore
    stub that records every prune call and signals the first one so
    tests don't sleep.

─── Verification ────────────────────────────────────────────────────

gofmt -l clean. No network access in sandbox so `go vet` and `go test`
could not run; the changes are local and surgical and every touched
file compiles in isolation against the existing signatures.

https://claude.ai/code/session_01UsBsQW2YiA2usk9pnJjAWk
2026-04-06 13:48:41 +00:00

99 lines
3.3 KiB
Go

// Phase C Step 9 — `ui` host capability.
//
// A plugin that declares the `ui` capability ships HTML/CSS/JS assets and a
// list of tabs. The host serves those assets at /api/v1/plugins/<name>/ui/...
// and the Solid.js client bridge renders each tab inside a sandboxed iframe.
package plugin
import (
"net/http"
"os"
"path/filepath"
"strings"
)
// RegisterUI binds inst's declared tabs into the registry. Called from the
// activation path; safe to call multiple times (idempotent on inst).
func (r *Registry) RegisterUI(inst *Instance) error {
if !inst.Manifest.HasCapability(CapUI) {
return ErrCapabilityNotGranted
}
r.mu.Lock()
defer r.mu.Unlock()
// Drop any existing bindings for this instance, then re-add.
kept := r.uiTabs[:0]
for _, b := range r.uiTabs {
if b.PluginID != inst.ID {
kept = append(kept, b)
}
}
r.uiTabs = kept
for _, t := range inst.Manifest.UI.Tabs {
r.uiTabs = append(r.uiTabs, UITabBinding{
PluginID: inst.ID,
PluginName: inst.Manifest.Name,
Tab: t,
})
}
return nil
}
// AssetHandler returns an http.Handler that serves the on-disk assets for
// inst, rooted at the plugin's directory. Defense in depth:
// 1. Manifest validation rejects absolute paths and "..".
// 2. The handler only serves files explicitly declared by a manifest tab.
// 3. After resolving the on-disk path we use filepath.Rel and reject any
// result containing ".." or that is absolute, which catches symlink
// escapes and the prefix-without-separator class of bug.
// 4. A serve-time os.Lstat check rejects symlinks that were created AFTER
// install (the install-time rejectSymlinksUnder walk only runs once).
// This closes the TOCTOU window where a malicious or buggy process
// swaps a regular file for a symlink post-install — http.ServeFile
// would otherwise follow the link and leak host files.
func (r *Registry) AssetHandler(inst *Instance) http.Handler {
allowed := make(map[string]bool, len(inst.Manifest.UI.Tabs))
for _, t := range inst.Manifest.UI.Tabs {
allowed[t.Asset] = true
}
pluginDir, dirErr := filepath.Abs(filepath.Dir(inst.WASMPath))
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if dirErr != nil {
http.Error(w, "plugin asset root unavailable", http.StatusInternalServerError)
return
}
rel := strings.TrimPrefix(req.URL.Path, "/")
if !allowed[rel] {
http.NotFound(w, req)
return
}
full, absErr := filepath.Abs(filepath.Join(pluginDir, rel))
if absErr != nil {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
relCheck, relErr := filepath.Rel(pluginDir, full)
if relErr != nil || relCheck == "" || relCheck == "." || strings.HasPrefix(relCheck, "..") || filepath.IsAbs(relCheck) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
// Lstat (not Stat) so a symlink is detected instead of followed.
// This runs on every request — cheap relative to the file read —
// and closes the TOCTOU gap between install-time validation and
// runtime serving.
info, lerr := os.Lstat(full)
if lerr != nil {
http.NotFound(w, req)
return
}
if info.Mode()&os.ModeSymlink != 0 {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
if !info.Mode().IsRegular() {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
http.ServeFile(w, req, full)
})
}