Files
OwnCord/Server/plugin/loader.go
T
Claude 7476c177b7 chore(phase-bc): pass 3 cleanup — perf, observability, hardening
Eight focused follow-ups from the medium-severity review bucket. All
in-sandbox tractable; no module changes, no new dependencies.

Performance
- Drop the defensive memcpy in EventPersister.Enqueue. The hub already
  passes a fresh slice from wrapWithSeq and the copy was happening under
  seqMu, serializing broadcast throughput. Documented the no-mutate
  contract on the call site.

Observability
- AppMetrics gains WSEventsPersistErrors counter; the persister run loop
  bumps both it and the existing WSEventsPersisted counter via cached
  metrics handle.
- Hub.persistEvent now extracts the real event type ("chat_message",
  "voice_join", ...) from the wrapped JSON envelope via a small
  no-allocation byte scan instead of recording the generic
  "broadcast"/"channel_broadcast" label.
- Added OTel spans + ServiceCallDurationMs histogram entries on one
  public method per remaining service: DMService.CreateDM,
  VoiceService.JoinChannel, InviteService.CreateInvite,
  ModerationService.BanUser, BlockService.BlockUser,
  UserService.UpdateProfile. Mirrors the existing pattern from
  MessageService.SendMessage.

Hardening
- plugin/loader now Lstat-walks each plugin directory and rejects any
  symlink, plus refuses an entrypoint that is itself a symlink. The
  asset handler's prefix check stays as defense in depth.
- ipAllowed (plugin HTTP capability) now rejects RFC6598 carrier-grade
  NAT (100.64.0.0/10), closing a gap in net.IP.IsPrivate which only
  covers RFC1918 + RFC4193.
- Registry.activateAll syncs Instance.Enabled := true after a successful
  activate so callers reading the in-memory flag see the live state.

Documentation
- defaultYAML now documents the new event_persistence, telemetry, and
  plugins config blocks with their defaults and one-line descriptions.
- PHASE_BC_LOCAL_TODO.md ticks off five items (defaultYAML docs ×2,
  remaining service spans, registry wiring already-fixed in Pass 2).

https://claude.ai/code/session_01UsBsQW2YiA2usk9pnJjAWk
2026-04-06 09:49:03 +00:00

113 lines
3.4 KiB
Go

// Phase C Step 9 — On-disk plugin discovery.
//
// Each plugin lives in its own subdirectory under PluginsConfig.Directory:
//
// plugins/
// hello/
// plugin.json
// hello.wasm
// game-detection/
// plugin.json
// detector.wasm
// assets/...
//
// Loader walks the directory, parses every plugin.json, and returns a slice
// of foundPlugin records. The Registry then persists each into the store.
package plugin
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
type foundPlugin struct {
Manifest *Manifest
Dir string
WASMPath string
}
// scanPluginDirectory walks dir non-recursively and parses plugin.json from
// every immediate subdirectory. Errors on individual plugins are wrapped and
// returned alongside the successful entries.
func scanPluginDirectory(dir string) ([]foundPlugin, error) {
if dir == "" {
return nil, nil
}
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
// Directory absent is fine — operators may not have created it yet.
return nil, nil
}
return nil, err
}
var found []foundPlugin
for _, e := range entries {
if !e.IsDir() {
continue
}
pluginDir := filepath.Join(dir, e.Name())
manifestPath := filepath.Join(pluginDir, "plugin.json")
raw, rdErr := os.ReadFile(manifestPath)
if rdErr != nil {
if os.IsNotExist(rdErr) {
continue
}
return nil, fmt.Errorf("plugin %q: read plugin.json: %w", e.Name(), rdErr)
}
manifest, parseErr := ParseManifest(raw)
if parseErr != nil {
return nil, fmt.Errorf("plugin %q: %w", e.Name(), parseErr)
}
// Reject any symlinks anywhere in the plugin directory tree. The asset
// handler enforces that resolved paths stay rooted at pluginDir, but
// http.ServeFile / os.Open follow symlinks transparently — a malicious
// plugin .zip containing `assets/index.html -> /etc/passwd` would
// otherwise serve host files. Stat (not Lstat) is used for the
// entrypoint because we want to refuse it being a symlink even if
// the target is valid.
if err := rejectSymlinksUnder(pluginDir); err != nil {
return nil, fmt.Errorf("plugin %q: %w", e.Name(), err)
}
wasmPath := filepath.Join(pluginDir, manifest.Entrypoint)
if info, statErr := os.Lstat(wasmPath); statErr != nil {
return nil, fmt.Errorf("plugin %q: missing entrypoint %s: %w", e.Name(), manifest.Entrypoint, statErr)
} else if info.Mode()&os.ModeSymlink != 0 {
return nil, fmt.Errorf("plugin %q: entrypoint %s is a symlink", e.Name(), manifest.Entrypoint)
}
found = append(found, foundPlugin{
Manifest: manifest,
Dir: pluginDir,
WASMPath: wasmPath,
})
}
return found, nil
}
// rejectSymlinksUnder walks root and returns an error if any entry is a
// symlink. Defends against malicious plugin packages that ship symlinks to
// host filesystem paths.
func rejectSymlinksUnder(root string) error {
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("symlink not allowed: %s", path)
}
return nil
})
}
// serialize returns a canonical JSON encoding of the manifest, used as the
// manifest_json column value in the plugins table.
func (m *Manifest) serialize() (string, error) {
b, err := json.Marshal(m)
if err != nil {
return "", fmt.Errorf("manifest serialize: %w", err)
}
return string(b), nil
}