Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

feat(plugins): add private SQL storage (#5084)

Gabe Kangas6c963844b171
diff --git a/AGENTS.md b/AGENTS.md
index 207568e9c1..90bab4d896 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -71,7 +71,7 @@ Do not test against `http://localhost:8080`. That serves the web bundle embedded
- `db/`: sqlc-generated type-safe database code. Queries in `db/query.sql`; the schema comes from the migrations, there is no `schema.sql`. Run `make sqlc` after changes.
- `services/`: constructor-injected services (stream, chat, transcoder, storage, rtmp, activitypub, plugins, webhooks, notifications, geoip, cache, datastore, dispatcher).
- `services/activitypub/`: federation (controllers, inbox/outbox, HTTP signatures, WebFinger, NodeInfo, delivery queue).
-- `pluginhost/`: plugin host surface (auth gates, chat bots, plugin events) on top of `services/plugins/`.
+- `pluginhost/`: plugin host surface (auth gates, chat bots, plugin events, per-plugin SQLite storage in `sqlite.go`) on top of `services/plugins/`.
- `models/`: shared data models. `config/`: defaults and constants. `auth/`: IndieAuth and Fediverse chat auth. `yp/`: directory registration. `utils/`, `logging/`, `metrics/`, `notifications/`: supporting packages.
- `tools/`: separate `go.mod` for dev tool pins, installed to `./bin/`.
diff --git a/docs/plugins.md b/docs/plugins.md
index 72b1f2db35..2e85086280 100644
--- a/docs/plugins.md
+++ b/docs/plugins.md
@@ -20,8 +20,8 @@ Owncast logs and continues rather than aborting startup.
| Path | Responsibility |
|---|---|
-| `services/plugins/` | The plugin **runtime** — discovery/enable lifecycle (`manager.go`), event + filter fan-out (`dispatcher.go`), the HTTP handler for `/plugins/<name>/*` (`server.go`), the host functions and their types/permissions (`hostfns.go`), the KV store interface (`kv/`), and the SSE hub (`sse.go`). |
-| `pluginhost/` | The **Owncast integration layer** — builds the runtime's `HostEnv` from Owncast services, starts the manager, and exposes the HTTP handlers. This is the only package that knows about both the runtime and Owncast's internals. |
+| `services/plugins/` | The plugin **runtime** — discovery/enable lifecycle (`manager.go`), event + filter fan-out (`dispatcher.go`), the HTTP handler for `/plugins/<name>/*` (`server.go`), the host functions and their types/permissions (`hostfns.go`), the driver-agnostic SQL request validation and result limits (`sqlrunner.go`), the KV store interface (`kv/`), and the SSE hub (`sse.go`). |
+| `pluginhost/` | The **Owncast integration layer** — builds the runtime's `HostEnv` from Owncast services, starts the manager, exposes the HTTP handlers, and owns each plugin's SQLite database (`sqlite.go`). This is the only package that knows about both the runtime and Owncast's internals. |
`services/plugins/` is a **vendored copy** of the upstream plugin SDK's
`host-runtime/plugin` package (`github.com/owncast/plugin-sdk`). See
@@ -97,12 +97,40 @@ that decoupling, and it lives at the boundary on purpose.
- **Users** (`users.read` / `users.moderate`) — list/get users, set enabled,
ban IP.
- **Notifications** (`notifications.send`) — Discord, browser push, fediverse.
-- **Storage** — KV backed by Owncast's datastore (`newDatastoreKVStore`),
- `storage.upload` for browser-accessible plugin assets (written under
- `public/`), and `storage.fs` for a private, sandboxed filesystem
- (`data/plugin-data/<slug>/`) the plugin can read/write/list/delete within.
- The host rejects any `storage.fs` path that escapes the plugin's own
- directory, and the bytes are never served over HTTP.
+- **Storage** — everything a plugin persists lives under one directory,
+ `data/plugin-storage/<slug>/`, so an operator has a single place to look, back
+ up, or delete. Inside it, `files/` is the `storage.fs` sandbox and `db/` holds
+ the `storage.sql` database. KV is separate, backed by Owncast's datastore
+ (`newDatastoreKVStore`), and `storage.upload` publishes browser-accessible
+ assets under `public/`.
+ On the first startup after upgrading, existing `data/plugin-data/<slug>/`
+ directories are renamed into the new `files/` location before plugins load.
+ A conflicting destination stops plugin startup rather than hiding or
+ overwriting either copy.
+- **Filesystem** (`storage.fs`) — a private, sandboxed filesystem rooted at
+ `data/plugin-storage/<slug>/files/` the plugin can read/write/list/delete
+ within. The host rejects any path that escapes it, and the bytes are never
+ served over HTTP.
+- **SQL** (`storage.sql`) — one private SQLite database per plugin at
+ `data/plugin-storage/<slug>/db/plugin.db`. The sandbox handed to `storage.fs`
+ is `files/`, so `db/` is not a path the filesystem API refuses but one it
+ cannot express. That is load-bearing rather than tidiness: `max_page_count`
+ only refuses to grow a database, so a plugin able to write its own database
+ file would pre-seed one already over its quota. Reserving filenames in a shared
+ directory would be the fragile version, since it would have to track SQLite's
+ journal and WAL sidecar naming forever. The quota walk covers `files/` only, so
+ the two limits stay independent. A SQLite authorizer denies
+ `ATTACH`/`DETACH`, every `PRAGMA`, temp-schema DDL (by
+ schema name, since SQLite reports `CREATE TABLE temp.x` as ordinary DDL), and
+ `load_extension`, which is what makes the 128 MiB size cap a real quota rather
+ than a value the plugin can raise. Results are capped at 1 MiB and 10000 rows,
+ a call at 2 seconds, and each `exec` runs as one host-owned transaction.
+ Plugin databases are not part of Owncast's database backups.
+ `services/plugins/sqlrunner.go` holds the driver-agnostic request validation
+ and result limits, `services/plugins/sqldenied.go` refuses the same statements
+ the authorizer refuses so the SDK's hosts can agree with us without a cgo
+ driver, and `pluginhost/sqlite.go` owns the driver configuration, the
+ authorizer, per-plugin files, and the lifecycle.
- **HTTP** (`http.serve`, `http.sse`) — `req.authenticated` / `req.user` from
Owncast's auth middleware, plus the SSE hub for server-pushed events.
diff --git a/pluginhost/filesystem_test.go b/pluginhost/filesystem_test.go
index e812e4d08e..478086d61e 100644
--- a/pluginhost/filesystem_test.go
+++ b/pluginhost/filesystem_test.go
@@ -14,10 +14,14 @@ import (
// host functions: every plugin-supplied path must resolve to somewhere
// inside that plugin's own sandbox, no matter how the plugin tries to
// climb out. These tests pin that contract.
+//
+// The sandbox is the files/ subdirectory of the plugin's storage directory, not
+// the storage directory itself, which is what keeps the sibling db/ subtree
+// holding its SQLite database out of reach.
func TestResolvePluginSandboxPath_StaysInsideSandbox(t *testing.T) {
root := t.TempDir()
- sandbox := filepath.Join(root, "my-plugin")
+ sandbox := filepath.Join(root, "my-plugin", pluginFilesDirName)
cases := []struct {
name string
@@ -64,7 +68,7 @@ func TestResolvePluginSandboxPath_IsolatesPlugins(t *testing.T) {
if got == sibling || strings.HasPrefix(got, sibling+string(os.PathSeparator)) {
t.Fatalf("plugin-a resolved into plugin-b's sandbox: %q", got)
}
- if want := filepath.Join(root, "plugin-a", "plugin-b", "data.json"); got != want {
+ if want := filepath.Join(root, "plugin-a", pluginFilesDirName, "plugin-b", "data.json"); got != want {
t.Fatalf("got %q, want %q", got, want)
}
}
@@ -83,7 +87,7 @@ func TestFilesystemHostFns_RoundTrip(t *testing.T) {
}
// The bytes landed inside the plugin's sandbox, nowhere else.
- onDisk := filepath.Join(root, slug, "sub", "greeting.txt")
+ onDisk := filepath.Join(root, slug, pluginFilesDirName, "sub", "greeting.txt")
if data, err := os.ReadFile(onDisk); err != nil || string(data) != "hello" {
t.Fatalf("expected file at %q with %q, got data=%q err=%v", onDisk, "hello", data, err)
}
@@ -128,11 +132,95 @@ func TestFilesystemHostFns_RoundTrip(t *testing.T) {
if _, err := os.Stat(filepath.Join(root, "escape.txt")); !os.IsNotExist(err) {
t.Fatalf("traversal write leaked a file outside the sandbox")
}
- if _, err := os.Stat(filepath.Join(root, slug, "escape.txt")); err != nil {
+ if _, err := os.Stat(filepath.Join(root, slug, pluginFilesDirName, "escape.txt")); err != nil {
t.Fatalf("traversal write should have landed inside the sandbox: %v", err)
}
}
+func TestMigrateLegacyPluginFilesystemStorage(t *testing.T) {
+ t.Run("moves existing files beside the plugin database", func(t *testing.T) {
+ dataDir := t.TempDir()
+ legacyFile := filepath.Join(dataDir, legacyPluginDataRootDirName, "demo", "sub", "note.txt")
+ if err := os.MkdirAll(filepath.Dir(legacyFile), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(legacyFile, []byte("kept"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ databaseFile := filepath.Join(dataDir, pluginStorageRootDirName, "demo", pluginDatabaseDirName, pluginSQLFileName)
+ if err := os.MkdirAll(filepath.Dir(databaseFile), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(databaseFile, []byte("database"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := migrateLegacyPluginFilesystemStorage(dataDir); err != nil {
+ t.Fatal(err)
+ }
+ migratedFile := filepath.Join(dataDir, pluginStorageRootDirName, "demo", pluginFilesDirName, "sub", "note.txt")
+ if data, err := os.ReadFile(migratedFile); err != nil || string(data) != "kept" {
+ t.Fatalf("migrated file = %q, %v; want kept", data, err)
+ }
+ if data, err := os.ReadFile(databaseFile); err != nil || string(data) != "database" {
+ t.Fatalf("database sibling changed: %q, %v", data, err)
+ }
+ if _, err := os.Stat(filepath.Join(dataDir, legacyPluginDataRootDirName)); !os.IsNotExist(err) {
+ t.Fatalf("legacy root still exists after migration: %v", err)
+ }
+ })
+
+ t.Run("ignores stray files while migrating plugin directories", func(t *testing.T) {
+ dataDir := t.TempDir()
+ legacyRoot := filepath.Join(dataDir, legacyPluginDataRootDirName)
+ legacyFile := filepath.Join(legacyRoot, "demo", "note.txt")
+ if err := os.MkdirAll(filepath.Dir(legacyFile), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(legacyFile, []byte("kept"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ strayFile := filepath.Join(legacyRoot, ".DS_Store")
+ if err := os.WriteFile(strayFile, []byte("stray"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := migrateLegacyPluginFilesystemStorage(dataDir); err != nil {
+ t.Fatal(err)
+ }
+ migratedFile := filepath.Join(dataDir, pluginStorageRootDirName, "demo", pluginFilesDirName, "note.txt")
+ if data, err := os.ReadFile(migratedFile); err != nil || string(data) != "kept" {
+ t.Fatalf("migrated file = %q, %v; want kept", data, err)
+ }
+ if data, err := os.ReadFile(strayFile); err != nil || string(data) != "stray" {
+ t.Fatalf("stray file = %q, %v; want it left in place", data, err)
+ }
+ })
+
+ t.Run("refuses to overwrite a destination", func(t *testing.T) {
+ dataDir := t.TempDir()
+ legacyFile := filepath.Join(dataDir, legacyPluginDataRootDirName, "demo", "note.txt")
+ newFile := filepath.Join(dataDir, pluginStorageRootDirName, "demo", pluginFilesDirName, "note.txt")
+ for path, contents := range map[string]string{legacyFile: "old", newFile: "new"} {
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if err := migrateLegacyPluginFilesystemStorage(dataDir); err == nil {
+ t.Fatal("expected conflicting destination to stop migration")
+ }
+ for path, want := range map[string]string{legacyFile: "old", newFile: "new"} {
+ if data, err := os.ReadFile(path); err != nil || string(data) != want {
+ t.Fatalf("%s = %q, %v; want %q", path, data, err, want)
+ }
+ }
+ })
+}
+
func TestFilesystemHostFns_RejectsOversizedWrite(t *testing.T) {
root := t.TempDir()
env := &plugins.HostEnv{}
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.go
index 9123db3abc..83268d9c60 100644
--- a/pluginhost/pluginhost.go
+++ b/pluginhost/pluginhost.go
@@ -88,6 +88,7 @@ type Host struct {
manager *plugins.Manager
server *plugins.Server
sse *plugins.SSEHub
+ sqlStore *pluginSQLStore
configRepository configrepository.ConfigRepository
// requireAdminAuth is the host's admin Basic Auth middleware, plumbed
// in from main.go so the management API and the plugin static server
@@ -186,6 +187,11 @@ func (p *Host) Stop(ctx context.Context) {
p.tickCancel()
}
p.manager.Stop(ctx)
+ // Unload callbacks close databases for loaded plugins; closeAll also
+ // handles any database opened during a final in-flight call.
+ if p.sqlStore != nil {
+ p.sqlStore.closeAll()
+ }
}
// Actions returns every action-button currently contributed by loaded
@@ -618,9 +624,20 @@ func New(ctx context.Context, deps Deps) (*Host, error) {
return nil, fmt.Errorf("create plugins directory: %w", err)
}
+ if err := migrateLegacyPluginFilesystemStorage(config.DataDirectory); err != nil {
+ return nil, err
+ }
+
+ sqlStore, err := newPluginSQLStore(filepath.Join(config.DataDirectory, pluginStorageRootDirName))
+ if err != nil {
+ return nil, err
+ }
env := &plugins.HostEnv{KV: newDatastoreKVStore(deps.Datastore)}
wirePluginHostEnv(env, deps)
+ env.SQLExec = sqlStore.exec
+ env.SQLQuery = sqlStore.query
+ env.AcquireSQLLease = sqlStore.acquire
sseHub := plugins.NewSSEHub()
env.SSE = sseHub
@@ -671,8 +688,8 @@ func New(ctx context.Context, deps Deps) (*Host, error) {
})
env.Timer = timerHub
// On unload (disable/reload/uninstall/disk-removal) cancel the plugin's
- // pending timers AND close its open SSE streams, so neither lingers after
- // the plugin is gone.
+ // pending timers and close its open SSE streams. SQL is tied directly to
+ // Loaded.Close so failed loads and package preflights release it too.
manager.SetOnUnload(func(slug string) {
timerHub.CancelForPlugin(slug)
sseHub.CloseForPlugin(slug)
@@ -711,6 +728,7 @@ func New(ctx context.Context, deps Deps) (*Host, error) {
return &Host{
manager: manager,
+ sqlStore: sqlStore,
server: server,
sse: sseHub,
configRepository: deps.ConfigRepository,
@@ -1118,12 +1136,85 @@ func wirePluginHostEnv(env *plugins.HostEnv, deps Deps) {
wireFilesystemHostFns(env)
}
-// pluginDataRootDirName is the directory under config.DataDirectory that
-// holds each plugin's private, sandboxed filesystem (storage.fs). It is
+// pluginStorageRootDirName is the directory under config.DataDirectory that
+// holds everything a plugin stores on disk, one subdirectory per plugin. It is
// deliberately separate from the plugins install/scan directory
// (config.DataDirectory/plugins) so a plugin's writable data can never be
// mistaken for, or collide with, an installed package or its assets.
-const pluginDataRootDirName = "plugin-data"
+const pluginStorageRootDirName = "plugin-storage"
+
+// legacyPluginDataRootDirName is where storage.fs data lived before SQL storage
+// gave every plugin one parent directory for all of its on-disk data.
+const legacyPluginDataRootDirName = "plugin-data"
+
+// Inside a plugin's storage directory, its two kinds of storage get their own
+// subdirectory: plugin-storage/<slug>/files for storage.fs and
+// plugin-storage/<slug>/db for storage.sql.
+//
+// The split is what keeps a database out of reach of the filesystem API. The
+// storage.fs sandbox is rooted at files/, so db/ is not merely a path the
+// resolver refuses, it is outside the tree the plugin can name at all. That
+// matters: max_page_count only refuses to grow a database, so a plugin that
+// could write its own database file would simply pre-seed one larger than its
+// quota and the host would open it. Reserving filenames inside a shared
+// directory would be the fragile version of this, since it would have to keep
+// pace with SQLite's journal and WAL sidecar naming forever.
+//
+// Keeping the trees apart also keeps the two quotas independent, so the limit a
+// plugin hits never depends on which API it wrote with first.
+const (
+ pluginFilesDirName = "files"
+ pluginDatabaseDirName = "db"
+)
+
+// pluginStorageDir returns one plugin's storage subtree, the parent of both
+// files/ and db/.
+func pluginStorageDir(root, pluginName string) string {
+ return filepath.Join(root, pluginName)
+}
+
+// migrateLegacyPluginFilesystemStorage moves existing storage.fs data into the
+// files/ subtree before any plugin can access it. Rename keeps each plugin's
+// migration atomic on the data volume. A conflicting destination is refused
+// rather than hiding or overwriting either copy. Unrecognized files remain in
+// the legacy root and do not block well-formed plugin directories.
+func migrateLegacyPluginFilesystemStorage(dataDir string) error {
+ legacyRoot := filepath.Join(dataDir, legacyPluginDataRootDirName)
+ entries, err := os.ReadDir(legacyRoot)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("read legacy plugin storage: %w", err)
+ }
+
+ storageRoot := filepath.Join(dataDir, pluginStorageRootDirName)
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ log.Warnf("Skipping unexpected file in legacy plugin storage: %s", entry.Name())
+ continue
+ }
+ source := filepath.Join(legacyRoot, entry.Name())
+ destinationParent := pluginStorageDir(storageRoot, entry.Name())
+ destination := filepath.Join(destinationParent, pluginFilesDirName)
+ if _, err := os.Stat(destination); err == nil {
+ return fmt.Errorf("migrate legacy plugin storage for %q: destination already exists", entry.Name())
+ } else if !os.IsNotExist(err) {
+ return fmt.Errorf("inspect plugin storage destination for %q: %w", entry.Name(), err)
+ }
+ if err := os.MkdirAll(destinationParent, 0o700); err != nil {
+ return fmt.Errorf("create plugin storage directory for %q: %w", entry.Name(), err)
+ }
+ if err := os.Rename(source, destination); err != nil {
+ return fmt.Errorf("migrate legacy plugin storage for %q: %w", entry.Name(), err)
+ }
+ log.Infof("Migrated plugin filesystem storage for %s", entry.Name())
+ }
+ if err := os.Remove(legacyRoot); err != nil && !os.IsNotExist(err) {
+ log.Warnf("Unable to remove legacy plugin storage directory: %v", err)
+ }
+ return nil
+}
// maxPluginFileBytes caps a single storage.fs write. It bounds how much a
// misbehaving plugin can write in one call.
@@ -1162,16 +1253,33 @@ func dirSize(dir string) (int64, error) {
return total, err
}
-// resolvePluginSandboxPath maps a plugin-supplied relative path to an
-// absolute path inside that plugin's sandbox (root/<pluginName>), and
-// guarantees the result cannot escape it. rel is treated as rooted before
-// cleaning, so "../", absolute paths, and other traversal tricks all
-// collapse back inside the sandbox; a defensive prefix check rejects
-// anything that still lands outside. pluginName is the plugin slug, which
-// the manifest layer has already constrained to [a-z][a-z0-9-]*, so it
-// cannot itself contain separators or "..".
+// resolvePluginSandboxPath maps a plugin-supplied relative path to an absolute
+// path inside that plugin's storage.fs sandbox
+// (root/<pluginName>/files), and guarantees the result cannot escape it. rel is
+// treated as rooted before cleaning, so "../", absolute paths, and other
+// traversal tricks all collapse back inside the sandbox; a defensive prefix
+// check rejects anything that still lands outside. pluginName is the plugin
+// slug, which the manifest layer has already constrained to [a-z][a-z0-9-]*, so
+// it cannot itself contain separators or "..".
+//
+// Because the sandbox is files/ rather than the whole per-plugin directory, the
+// same containment check that stops a plugin reaching another plugin's data also
+// stops it reaching its own database.
func resolvePluginSandboxPath(root, pluginName, rel string) (string, error) {
- sandbox, err := filepath.Abs(filepath.Join(root, pluginName))
+ return resolveContainedPath(filepath.Join(pluginStorageDir(root, pluginName), pluginFilesDirName), rel)
+}
+
+// resolvePluginDatabasePath is the same containment guarantee for the host's own
+// use of the db/ subtree. A plugin never supplies one of these paths, so this
+// exists to keep the layout in one place rather than to defend a boundary.
+func resolvePluginDatabasePath(root, pluginName, rel string) (string, error) {
+ return resolveContainedPath(filepath.Join(pluginStorageDir(root, pluginName), pluginDatabaseDirName), rel)
+}
+
+// resolveContainedPath joins rel under sandbox and refuses any result that
+// lands outside it.
+func resolveContainedPath(sandbox, rel string) (string, error) {
+ sandbox, err := filepath.Abs(sandbox)
if err != nil {
return "", err
}
@@ -1189,8 +1297,11 @@ func resolvePluginSandboxPath(root, pluginName, rel string) (string, error) {
// aggregate quota. full is the absolute path being written; when it already
// exists it's excluded from the current total, since the write overwrites it
// in place rather than growing the footprint.
+//
+// It walks files/ only, so a plugin's database never consumes its filesystem
+// quota and the two limits stay independent.
func fsQuotaCheck(root, pluginName, full string, addBytes int) error {
- used, err := dirSize(filepath.Join(root, pluginName))
+ used, err := dirSize(filepath.Join(pluginStorageDir(root, pluginName), pluginFilesDirName))
if err != nil {
return err
}
@@ -1204,10 +1315,10 @@ func fsQuotaCheck(root, pluginName, full string, addBytes int) error {
return nil
}
-// wireFilesystemHostFns implements the storage.fs host functions against a
-// per-plugin sandbox directory under config.DataDirectory/plugin-data.
+// wireFilesystemHostFns implements the storage.fs host functions against each
+// plugin's files/ subdirectory under config.DataDirectory/plugin-storage.
func wireFilesystemHostFns(env *plugins.HostEnv) {
- wireFilesystemHostFnsWithRoot(env, filepath.Join(config.DataDirectory, pluginDataRootDirName))
+ wireFilesystemHostFnsWithRoot(env, filepath.Join(config.DataDirectory, pluginStorageRootDirName))
}
// wireFilesystemHostFnsWithRoot is wireFilesystemHostFns with the sandbox
diff --git a/pluginhost/sqlite.go b/pluginhost/sqlite.go
new file mode 100644
index 0000000000..3b24b10af6
--- /dev/null
+++ b/pluginhost/sqlite.go
@@ -0,0 +1,319 @@
+package pluginhost
+
+import (
+ "context"
+ "database/sql"
+ "database/sql/driver"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ sqlite3 "github.com/mattn/go-sqlite3"
+ "github.com/owncast/owncast/services/plugins"
+)
+
+const (
+ // pluginSQLiteDriver is a private driver registration: the connection hook
+ // below locks every plugin connection down, and Owncast's own datastore must
+ // keep using the stock "sqlite3" driver.
+ pluginSQLiteDriver = "owncast_plugin_sqlite"
+ // pluginSQLFileName is the database inside each plugin's SQL directory.
+ pluginSQLFileName = "plugin.db"
+ // pluginSQLitePageSize is the page size a freshly created plugin database
+ // gets. An existing database keeps whatever it was created with, so the
+ // page quota is always derived from the size actually in force.
+ pluginSQLitePageSize = 4096
+ // pluginSQLiteMaxBytes caps one plugin's database. It is deliberately
+ // independent of the storage.fs quota: the two live in separate directory
+ // trees, so neither can consume the other's headroom and the limit a plugin
+ // hits does not depend on the order it wrote its data.
+ pluginSQLiteMaxBytes = 128 << 20 // 128 MiB per plugin
+)
+
+var registerPluginSQLiteDriver sync.Once
+
+// deniedSQLiteOps are the authorizer actions a plugin may never perform. The
+// authorizer is the security boundary: Exec runs every statement in a batch, so
+// a check on statement text alone is bypassable, and a denied PRAGMA is what
+// makes max_page_count a quota rather than a suggestion.
+//
+// Denying PRAGMA also denies PRAGMA reads, so the connection hook reads
+// page_size before installing the authorizer.
+//
+// Temp-schema DDL is denied because a temp object lives outside the main
+// database's page quota and persists for the life of the pooled connection,
+// which is an unbounded side channel. Sorters, CTEs, subqueries, and json1 are
+// unaffected: they use internal ephemeral tables, not temp-schema DDL.
+var deniedSQLiteOps = map[int]bool{
+ sqlite3.SQLITE_ATTACH: true,
+ sqlite3.SQLITE_DETACH: true,
+ sqlite3.SQLITE_PRAGMA: true,
+ sqlite3.SQLITE_CREATE_TEMP_TABLE: true,
+ sqlite3.SQLITE_CREATE_TEMP_INDEX: true,
+ sqlite3.SQLITE_CREATE_TEMP_TRIGGER: true,
+ sqlite3.SQLITE_CREATE_TEMP_VIEW: true,
+ sqlite3.SQLITE_DROP_TEMP_TABLE: true,
+ sqlite3.SQLITE_DROP_TEMP_INDEX: true,
+ sqlite3.SQLITE_DROP_TEMP_TRIGGER: true,
+ sqlite3.SQLITE_DROP_TEMP_VIEW: true,
+}
+
+// temporarySchemaName is the schema a plugin must not reach. Denying the
+// SQLITE_*_TEMP_* actions is not enough on its own: SQLite reports
+// `CREATE TABLE temp.x` and `CREATE VIEW temp.v` as the ordinary CREATE actions
+// and puts "temp" in the authorizer's database-name argument instead, so those
+// statements slip past an op-only deny list and put an unquota'd table in the
+// temp schema. Denying the schema by name closes every spelling of it,
+// including the quoted and mixed-case ones.
+const temporarySchemaName = "temp"
+
+// pluginSQLStore owns one database file and one serialized connection per
+// plugin. root is the shared plugin-storage root, and each database lives in
+// that plugin's db/ subdirectory, which sits outside the storage.fs sandbox so
+// no plugin-facing API can reach it.
+type pluginSQLStore struct {
+ root string
+
+ mu sync.Mutex
+ dbs map[string]*pluginSQLDatabase
+ leases map[string]int
+ closing map[string]int
+}
+
+type pluginSQLDatabase struct {
+ db *sql.DB
+}
+
+func newPluginSQLStore(root string) (*pluginSQLStore, error) {
+ if err := os.MkdirAll(root, 0o700); err != nil {
+ return nil, fmt.Errorf("create plugin SQL root: %w", err)
+ }
+ registerPluginSQLiteDriver.Do(func() {
+ sql.Register(pluginSQLiteDriver, &sqlite3.SQLiteDriver{
+ ConnectHook: configurePluginSQLiteConnection,
+ })
+ })
+ return &pluginSQLStore{
+ root: root,
+ dbs: make(map[string]*pluginSQLDatabase),
+ leases: make(map[string]int),
+ closing: make(map[string]int),
+ }, nil
+}
+
+// configurePluginSQLiteConnection applies the sandbox to one connection. Order
+// matters: the PRAGMAs and the page-size read happen first, then the limits and
+// the authorizer lock the connection for the rest of its life.
+func configurePluginSQLiteConnection(conn *sqlite3.SQLiteConn) error {
+ for _, pragma := range []string{
+ fmt.Sprintf("PRAGMA page_size=%d", pluginSQLitePageSize),
+ // TRUNCATE rather than WAL: a rollback journal is truncated to zero on
+ // commit, so a plugin's on-disk footprint stays at its page quota
+ // instead of overshooting it by a WAL that is only reclaimed at
+ // checkpoint. With one connection there is no concurrency to gain.
+ "PRAGMA journal_mode=TRUNCATE",
+ // FULL, not NORMAL: a rollback journal only guarantees durability when
+ // the journal is synced, and plugin databases are not in Owncast's
+ // backup, so a torn write has nothing to restore from.
+ "PRAGMA synchronous=FULL",
+ "PRAGMA cache_size=-2000", // ~2 MiB, not the datastore's 10000 pages
+ "PRAGMA foreign_keys=ON",
+ "PRAGMA trusted_schema=OFF",
+ // Keep temp data off disk entirely; temp-schema DDL is denied below, so
+ // what remains is bounded sorter and CTE scratch space.
+ "PRAGMA temp_store=MEMORY",
+ } {
+ if _, err := conn.Exec(pragma, nil); err != nil {
+ return fmt.Errorf("%s: %w", pragma, err)
+ }
+ }
+
+ // An existing database keeps the page size it was created with, so read the
+ // size in force and derive the page cap from it. Assuming 4 KiB would turn
+ // the quota into 16x its intended size on a 64 KiB-page database.
+ pageSize, err := sqliteScalarInt(conn, "PRAGMA page_size")
+ if err != nil {
+ return fmt.Errorf("read plugin database page size: %w", err)
+ }
+ if pageSize <= 0 {
+ return fmt.Errorf("plugin database reports page size %d", pageSize)
+ }
+ maxPages := pluginSQLiteMaxBytes / pageSize
+ if _, err := conn.Exec(fmt.Sprintf("PRAGMA max_page_count=%d", maxPages), nil); err != nil {
+ return fmt.Errorf("set plugin database page cap: %w", err)
+ }
+
+ // SQLITE_LIMIT_LENGTH refuses an oversized string, blob, or row inside the
+ // engine, so a plugin cannot make the host allocate hundreds of megabytes
+ // with SELECT randomblob(...) only to have the result rejected afterwards.
+ conn.SetLimit(sqlite3.SQLITE_LIMIT_LENGTH, plugins.MaxSQLValueBytes)
+ conn.SetLimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH, plugins.MaxSQLStatementBytes)
+ conn.SetLimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, plugins.MaxSQLParams)
+ // Belt for the ATTACH denial: with zero attached databases permitted, an
+ // ATTACH cannot succeed even if the authorizer is ever relaxed.
+ conn.SetLimit(sqlite3.SQLITE_LIMIT_ATTACHED, 0)
+
+ // The fourth callback argument is SQLite's database-name argument, which
+ // carries the schema an action targets.
+ conn.RegisterAuthorizer(func(op int, arg1, arg2, schema string) int {
+ if strings.EqualFold(schema, temporarySchemaName) {
+ return sqlite3.SQLITE_DENY
+ }
+ if deniedSQLiteOps[op] {
+ return sqlite3.SQLITE_DENY
+ }
+ if op == sqlite3.SQLITE_FUNCTION &&
+ (strings.EqualFold(arg1, "load_extension") || strings.EqualFold(arg2, "load_extension")) {
+ return sqlite3.SQLITE_DENY
+ }
+ return sqlite3.SQLITE_OK
+ })
+ return nil
+}
+
+// sqliteScalarInt runs a single-value query on a raw connection. Used for the
+// page-size read that has to happen before the authorizer denies PRAGMA.
+func sqliteScalarInt(conn *sqlite3.SQLiteConn, query string) (int, error) {
+ rows, err := conn.Query(query, nil)
+ if err != nil {
+ return 0, err
+ }
+ defer rows.Close()
+ values := make([]driver.Value, 1)
+ if err := rows.Next(values); err != nil {
+ return 0, err
+ }
+ value, ok := values[0].(int64)
+ if !ok {
+ return 0, fmt.Errorf("expected an integer, got %T", values[0])
+ }
+ return int(value), nil
+}
+
+// acquire gives one loaded plugin instance a claim on its slug's database.
+// Multiple instances can briefly coexist during package preflight or reload,
+// so only the last release closes the shared handle.
+func (s *pluginSQLStore) acquire(pluginName string) func() {
+ s.mu.Lock()
+ s.leases[pluginName]++
+ s.mu.Unlock()
+
+ var once sync.Once
+ return func() {
+ once.Do(func() { s.release(pluginName) })
+ }
+}
+
+func (s *pluginSQLStore) release(pluginName string) {
+ s.mu.Lock()
+ if s.leases[pluginName] > 1 {
+ s.leases[pluginName]--
+ s.mu.Unlock()
+ return
+ }
+ delete(s.leases, pluginName)
+ s.closing[pluginName]++
+ entry := s.dbs[pluginName]
+ delete(s.dbs, pluginName)
+ s.mu.Unlock()
+
+ closeSQLDatabase(entry)
+
+ s.mu.Lock()
+ if s.closing[pluginName] > 1 {
+ s.closing[pluginName]--
+ s.mu.Unlock()
+ return
+ }
+ delete(s.closing, pluginName)
+ // A handle here would mean a host call bypassed the closing block. Sweep it
+ // rather than retain a resource with no loaded instance.
+ entry = s.dbs[pluginName]
+ delete(s.dbs, pluginName)
+ s.mu.Unlock()
+ closeSQLDatabase(entry)
+}
+
+// get returns the plugin's database, opening it on first use.
+func (s *pluginSQLStore) get(pluginName string) (*pluginSQLDatabase, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.closing[pluginName] > 0 {
+ return nil, fmt.Errorf("plugin %q is unloading; SQL storage is closed", pluginName)
+ }
+ if db := s.dbs[pluginName]; db != nil {
+ return db, nil
+ }
+
+ path, err := resolvePluginDatabasePath(s.root, pluginName, pluginSQLFileName)
+ if err != nil {
+ return nil, err
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ return nil, fmt.Errorf("create plugin SQL directory: %w", err)
+ }
+ db, err := sql.Open(pluginSQLiteDriver, "file:"+path+"?_busy_timeout=5000&_txlock=immediate")
+ if err != nil {
+ return nil, fmt.Errorf("open plugin SQL database: %w", err)
+ }
+ // One connection: plugin statements serialize against each other rather
+ // than contending for locks on the same file.
+ db.SetMaxOpenConns(1)
+ db.SetMaxIdleConns(1)
+ if err := db.Ping(); err != nil {
+ _ = db.Close()
+ return nil, fmt.Errorf("initialize plugin SQL database: %w", err)
+ }
+ entry := &pluginSQLDatabase{db: db}
+ s.dbs[pluginName] = entry
+ return entry, nil
+}
+
+// runner resolves the plugin's database and wraps it in the shared runner that
+// applies the host's statement, timeout, and result limits.
+func (s *pluginSQLStore) runner(pluginName string) (plugins.SQLRunner, error) {
+ entry, err := s.get(pluginName)
+ if err != nil {
+ return plugins.SQLRunner{}, err
+ }
+ return plugins.SQLRunner{DB: entry.db}, nil
+}
+
+func (s *pluginSQLStore) exec(ctx context.Context, pluginName string, req plugins.SQLRequest) plugins.SQLExecResult {
+ runner, err := s.runner(pluginName)
+ if err != nil {
+ return plugins.SQLExecResult{Error: err.Error()}
+ }
+ return runner.Exec(ctx, req)
+}
+
+func (s *pluginSQLStore) query(ctx context.Context, pluginName string, req plugins.SQLRequest) plugins.SQLQueryResult {
+ runner, err := s.runner(pluginName)
+ if err != nil {
+ return plugins.SQLQueryResult{Error: err.Error()}
+ }
+ return runner.Query(ctx, req)
+}
+
+// closeAll releases every open database. The final sweep on host shutdown.
+func (s *pluginSQLStore) closeAll() {
+ s.mu.Lock()
+ entries := s.dbs
+ s.dbs = make(map[string]*pluginSQLDatabase)
+ s.leases = make(map[string]int)
+ s.mu.Unlock()
+ for _, entry := range entries {
+ closeSQLDatabase(entry)
+ }
+}
+
+// closeSQLDatabase closes one plugin database. database/sql prevents new work
+// and waits for statements already using the connection.
+func closeSQLDatabase(entry *pluginSQLDatabase) {
+ if entry == nil {
+ return
+ }
+ _ = entry.db.Close()
+}
diff --git a/pluginhost/sqlite_test.go b/pluginhost/sqlite_test.go
new file mode 100644
index 0000000000..1f8bda920f
--- /dev/null
+++ b/pluginhost/sqlite_test.go
@@ -0,0 +1,354 @@
+package pluginhost
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/owncast/owncast/services/plugins"
+)
+
+func newTestSQLStore(t *testing.T) (*pluginSQLStore, string) {
+ t.Helper()
+ root := t.TempDir()
+ store, err := newPluginSQLStore(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(store.closeAll)
+ return store, root
+}
+
+func TestPluginSQLStoreIsolationAndRoundTrip(t *testing.T) {
+ store, _ := newTestSQLStore(t)
+ ctx := context.Background()
+
+ exec := func(plugin, statement string, params ...any) plugins.SQLExecResult {
+ return store.exec(ctx, plugin, plugins.SQLRequest{SQL: statement, Params: params})
+ }
+ if result := exec("first", "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)"); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ if result := exec("first", "INSERT INTO items (name) VALUES (?)", "one"); result.Error != "" || result.LastInsertID != 1 {
+ t.Fatalf("insert result: %+v", result)
+ }
+ query := store.query(ctx, "first", plugins.SQLRequest{SQL: "SELECT id, name FROM items"})
+ if query.Error != "" || len(query.Rows) != 1 || query.Rows[0][1] != "one" {
+ t.Fatalf("query result: %+v", query)
+ }
+ empty := store.query(ctx, "first", plugins.SQLRequest{SQL: "SELECT id FROM items WHERE id = ?", Params: []any{int64(99)}})
+ if empty.Error != "" || empty.Columns == nil || empty.Rows == nil || len(empty.Rows) != 0 {
+ t.Fatalf("empty query result: %+v", empty)
+ }
+ other := store.query(ctx, "second", plugins.SQLRequest{SQL: "SELECT name FROM items"})
+ if other.Error == "" {
+ t.Fatal("plugin databases are not isolated")
+ }
+}
+
+// A plugin must not be able to reach outside its own database, and must not be
+// able to lift the limits that bound it.
+//
+// The store calls SQLite directly, without the Go-level check ParseSQLRequest
+// applies at the host-function boundary, so this exercises the SQLite authorizer
+// on its own. That matters twice over: the authorizer is the actual security
+// boundary, and it has to refuse everything in the shared parity fixture, since
+// the SDK's hosts refuse that same list with the Go check. A statement a plugin
+// author sees refused in a scenario test is then refused on a real server too.
+func TestPluginSQLStoreDeniesEscapesAndLimitChanges(t *testing.T) {
+ store, root := newTestSQLStore(t)
+ ctx := context.Background()
+
+ for _, statement := range plugins.DeniedSQLStatementExamples {
+ if result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: statement}); result.Error == "" {
+ t.Errorf("the SQLite authorizer allowed %q", statement)
+ }
+ }
+
+ // Forms that need a real path on this machine, so they cannot live in the
+ // shared fixture.
+ for name, statement := range map[string]string{
+ "attach the host database": fmt.Sprintf("ATTACH DATABASE '%s' AS host", filepath.Join(root, "owncast.db")),
+ "vacuum into a file": fmt.Sprintf("VACUUM INTO '%s'", filepath.Join(root, "escape.db")),
+ } {
+ if result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: statement}); result.Error == "" {
+ t.Errorf("%s: the SQLite authorizer allowed %q", name, statement)
+ }
+ }
+ if _, err := os.Stat(filepath.Join(root, "escape.db")); err == nil {
+ t.Fatal("VACUUM INTO wrote a file outside the plugin's database")
+ }
+ // The refused statements left the connection usable.
+ if result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: "CREATE TABLE main.after (v TEXT)"}); result.Error != "" {
+ t.Fatalf("the connection should still be usable: %v", result.Error)
+ }
+ // The denials must not cost ordinary SQL anything: sorters, recursive CTEs,
+ // subqueries, views, triggers, and json1 all still work.
+ for _, statement := range []string{
+ "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, n INTEGER)",
+ "CREATE INDEX items_name ON items (name)",
+ "CREATE VIEW item_names AS SELECT name FROM items",
+ "CREATE TRIGGER touch AFTER INSERT ON items BEGIN UPDATE items SET n = n; END",
+ "INSERT INTO items (name, n) VALUES ('b', 2), ('a', 1)",
+ } {
+ if result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: statement}); result.Error != "" {
+ t.Fatalf("%q: %v", statement, result.Error)
+ }
+ }
+ for _, statement := range []string{
+ "SELECT name FROM items ORDER BY name",
+ "WITH RECURSIVE counter(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM counter WHERE i < 500) SELECT count(*) FROM counter",
+ "SELECT (SELECT count(*) FROM items) AS total",
+ "SELECT json_object('name', name) FROM items",
+ "SELECT name FROM item_names UNION SELECT name FROM items ORDER BY 1",
+ } {
+ if result := store.query(ctx, "plugin", plugins.SQLRequest{SQL: statement}); result.Error != "" {
+ t.Errorf("%q should be allowed: %v", statement, result.Error)
+ }
+ }
+}
+
+// The page quota is derived from the page size actually in force. A database
+// created with 64 KiB pages must still cap at pluginSQLiteMaxBytes, not at
+// sixteen times that. The SQL root is unreachable from storage.fs, so this is
+// defence in depth rather than the only barrier.
+func TestPluginSQLStoreDerivesPageQuotaFromPageSize(t *testing.T) {
+ store, root := newTestSQLStore(t)
+ path := filepath.Join(root, "plugin", pluginDatabaseDirName, pluginSQLFileName)
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ seed, err := sql.Open("sqlite3", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := seed.Exec("PRAGMA page_size=65536; VACUUM; CREATE TABLE big (v BLOB)"); err != nil {
+ t.Fatal(err)
+ }
+ if err := seed.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ ctx := context.Background()
+ payload := strings.Repeat("x", 900_000)
+ var lastErr string
+ inserted := 0
+ for i := 0; i < 400; i++ {
+ result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: "INSERT INTO big VALUES (?)", Params: []any{payload}})
+ if result.Error != "" {
+ lastErr = result.Error
+ break
+ }
+ inserted++
+ }
+ if lastErr == "" {
+ t.Fatal("expected the page quota to stop the inserts")
+ }
+ // Assert the quota is what stopped it: any other failure (a rejected
+ // connection hook, a missing table) would also end the loop early and would
+ // otherwise pass this test while proving nothing.
+ if !strings.Contains(lastErr, "database or disk is full") {
+ t.Fatalf("expected the page quota to stop the inserts, got %q after %d rows", lastErr, inserted)
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Size() < pluginSQLiteMaxBytes/2 {
+ t.Fatalf("database only reached %d bytes after %d rows; the quota tripped too early to prove anything", info.Size(), inserted)
+ }
+ if info.Size() > 2*pluginSQLiteMaxBytes {
+ t.Fatalf("database grew to %d bytes with 64 KiB pages; the %d-byte quota was derived from the wrong page size", info.Size(), pluginSQLiteMaxBytes)
+ }
+ t.Logf("64 KiB-page database capped at %d bytes after %d rows", info.Size(), inserted)
+}
+
+// An oversized value must be refused inside SQLite rather than materialized and
+// then rejected, so a plugin cannot make the host allocate its way to an OOM.
+func TestPluginSQLStoreRefusesOversizedValuesCheaply(t *testing.T) {
+ store, _ := newTestSQLStore(t)
+ ctx := context.Background()
+
+ start := time.Now()
+ result := store.query(ctx, "plugin", plugins.SQLRequest{SQL: "SELECT randomblob(100000000)"})
+ elapsed := time.Since(start)
+ if result.Error == "" {
+ t.Fatal("expected a 100 MB blob to be refused")
+ }
+ if elapsed > plugins.SQLCallTimeout {
+ t.Fatalf("refusing the blob took %s; it should fail before materializing", elapsed)
+ }
+ if result := store.query(ctx, "plugin", plugins.SQLRequest{SQL: "SELECT hex(randomblob(10000000))"}); result.Error == "" {
+ t.Fatal("expected a 20 MB hex string to be refused")
+ }
+ // A value inside the limit is unaffected.
+ if result := store.query(ctx, "plugin", plugins.SQLRequest{SQL: "SELECT length(randomblob(1000))"}); result.Error != "" {
+ t.Fatalf("a small blob should be allowed: %v", result.Error)
+ }
+}
+
+// The timeout starts before database/sql waits for the plugin's sole
+// connection. Two concurrent runaway calls must therefore expire together
+// rather than each getting a fresh timeout after the previous call finishes.
+func TestPluginSQLStoreTimeoutIncludesConnectionWait(t *testing.T) {
+ store, _ := newTestSQLStore(t)
+ const runaway = "WITH RECURSIVE c(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM c) SELECT sum(i) FROM c"
+
+ start := make(chan struct{})
+ results := make(chan plugins.SQLQueryResult, 2)
+ for range 2 {
+ go func() {
+ <-start
+ results <- store.query(context.Background(), "plugin", plugins.SQLRequest{SQL: runaway})
+ }()
+ }
+ started := time.Now()
+ close(start)
+ for range 2 {
+ if result := <-results; result.Error == "" {
+ t.Fatal("runaway query completed without a timeout")
+ }
+ }
+ if elapsed := time.Since(started); elapsed > plugins.SQLCallTimeout+time.Second {
+ t.Fatalf("serialized calls took %s; timeout did not include the connection wait", elapsed)
+ }
+}
+
+func TestPluginSQLStoreExecIsAtomic(t *testing.T) {
+ store, _ := newTestSQLStore(t)
+ ctx := context.Background()
+
+ result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: "CREATE TABLE items (name TEXT); INSERT INTO items VALUES ('ok'); INSERT INTO missing VALUES (1)"})
+ if result.Error == "" {
+ t.Fatal("expected the failing statement to roll back the batch")
+ }
+ query := store.query(ctx, "plugin", plugins.SQLRequest{SQL: "SELECT count(*) FROM items"})
+ if query.Error == "" || !strings.Contains(query.Error, "no such table") {
+ t.Fatalf("expected atomic rollback to remove the table, got %+v", query)
+ }
+ // A plugin cannot leave a transaction open across calls.
+ if result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: "BEGIN"}); result.Error == "" {
+ t.Fatal("expected BEGIN inside the host transaction to fail")
+ }
+ if result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: "CREATE TABLE after (v TEXT)"}); result.Error != "" {
+ t.Fatalf("the connection should still be usable: %v", result.Error)
+ }
+}
+
+// A package preflight can load a second instance with the same slug. Releasing
+// that throwaway instance must preserve the live instance's open handle; only
+// the final instance release closes it.
+func TestPluginSQLStoreLeasesPreserveLiveHandle(t *testing.T) {
+ store, _ := newTestSQLStore(t)
+ ctx := context.Background()
+
+ releaseLive := store.acquire("plugin")
+ if result := store.exec(ctx, "plugin", plugins.SQLRequest{SQL: "CREATE TABLE items (value TEXT); INSERT INTO items VALUES ('live')"}); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ store.mu.Lock()
+ liveDB := store.dbs["plugin"]
+ store.mu.Unlock()
+
+ releasePreflight := store.acquire("plugin")
+ releasePreflight()
+ store.mu.Lock()
+ afterPreflight := store.dbs["plugin"]
+ leases := store.leases["plugin"]
+ store.mu.Unlock()
+ if afterPreflight != liveDB || leases != 1 {
+ t.Fatalf("preflight release changed live SQL state: db=%p want %p, leases=%d want 1", afterPreflight, liveDB, leases)
+ }
+
+ releaseLive()
+ store.mu.Lock()
+ open := len(store.dbs)
+ leases = len(store.leases)
+ store.mu.Unlock()
+ if open != 0 || leases != 0 {
+ t.Fatalf("final release left %d handles and %d leases", open, leases)
+ }
+
+ releaseReload := store.acquire("plugin")
+ defer releaseReload()
+ query := store.query(ctx, "plugin", plugins.SQLRequest{SQL: "SELECT value FROM items"})
+ if query.Error != "" || len(query.Rows) != 1 || query.Rows[0][0] != "live" {
+ t.Fatalf("reload did not reopen the persisted database: %+v", query)
+ }
+}
+
+// A plugin's files and its database share one storage directory, which is what
+// an operator sees, but they are in separate subtrees. The storage.fs sandbox is
+// rooted at files/, so db/ is not a path the filesystem API refuses, it is a
+// path the filesystem API cannot express. That distinction is the whole point:
+// reserving filenames inside one shared directory would have to keep pace with
+// SQLite's sidecar naming, and a single missed operation would let a plugin
+// pre-seed a database larger than its quota, read its raw bytes, or delete it
+// while the host holds it open.
+func TestPluginDatabaseIsUnreachableFromFilesystemSandbox(t *testing.T) {
+ dataDir := t.TempDir()
+ root := filepath.Join(dataDir, pluginStorageRootDirName)
+
+ store, err := newPluginSQLStore(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(store.closeAll)
+ if result := store.exec(context.Background(), "plugin", plugins.SQLRequest{SQL: "CREATE TABLE items (v TEXT)"}); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+
+ dbPath := filepath.Join(root, "plugin", pluginDatabaseDirName, pluginSQLFileName)
+ if _, err := os.Stat(dbPath); err != nil {
+ t.Fatalf("expected the database at %s: %v", dbPath, err)
+ }
+ // Both live under one per-plugin directory, so an operator has a single
+ // place to look, back up, or delete.
+ storageDir := pluginStorageDir(root, "plugin")
+ if filepath.Dir(filepath.Dir(dbPath)) != storageDir {
+ t.Fatalf("database at %s is not inside the plugin's storage directory %s", dbPath, storageDir)
+ }
+
+ // Every storage.fs path, including traversal attempts and the database's own
+ // absolute path, resolves back inside files/ and can never name db/.
+ filesDir := filepath.Join(storageDir, pluginFilesDirName)
+ for _, rel := range []string{
+ pluginSQLFileName,
+ pluginDatabaseDirName + "/" + pluginSQLFileName,
+ "../" + pluginDatabaseDirName + "/" + pluginSQLFileName,
+ "../../plugin/" + pluginDatabaseDirName + "/" + pluginSQLFileName,
+ "../../../" + pluginStorageRootDirName + "/plugin/" + pluginDatabaseDirName + "/" + pluginSQLFileName,
+ dbPath,
+ dbPath + "-journal",
+ } {
+ resolved, err := resolvePluginSandboxPath(root, "plugin", rel)
+ if err != nil {
+ continue
+ }
+ if resolved == dbPath || strings.HasPrefix(resolved, filepath.Join(storageDir, pluginDatabaseDirName)+string(os.PathSeparator)) {
+ t.Errorf("storage.fs path %q reaches the database subtree (%s)", rel, resolved)
+ }
+ if !strings.HasPrefix(resolved, filesDir+string(os.PathSeparator)) && resolved != filesDir {
+ t.Errorf("storage.fs path %q resolved outside files/ (%s)", rel, resolved)
+ }
+ }
+
+ // The quota walk covers files/ only, so a database never consumes the
+ // filesystem quota and the two limits stay independent whichever API a
+ // plugin writes with first.
+ used, err := dirSize(filesDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if used != 0 {
+ t.Fatalf("the plugin database counted %d bytes against the storage.fs quota", used)
+ }
+ if err := fsQuotaCheck(root, "plugin", filepath.Join(filesDir, "note.txt"), maxPluginDataBytes); err != nil {
+ t.Fatalf("a write filling the whole filesystem quota should still be allowed: %v", err)
+ }
+}
diff --git a/services/plugins/engine_lifecycle_test.go b/services/plugins/engine_lifecycle_test.go
index 68cedd93c6..1b8bdd721f 100644
--- a/services/plugins/engine_lifecycle_test.go
+++ b/services/plugins/engine_lifecycle_test.go
@@ -81,6 +81,11 @@ func TestLoadFailureReleasesEngine(t *testing.T) {
t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
env, _, _ := captureEnv()
+ var acquired, released int
+ env.AcquireSQLLease = func(string) func() {
+ acquired++
+ return func() { released++ }
+ }
manifestBytes, _ := json.Marshal(map[string]any{
"api": "1",
"name": "boom",
@@ -95,6 +100,9 @@ func TestLoadFailureReleasesEngine(t *testing.T) {
if n, refs := engineCacheState(); n != 0 {
t.Fatalf("failed load leaked an engine reference: %d entries, %d refs", n, refs)
}
+ if acquired != 1 || released != 1 {
+ t.Fatalf("failed load acquired %d SQL leases and released %d, want 1 each", acquired, released)
+ }
}
// lifecycleManifest builds manifest bytes for the Install lifecycle tests:
@@ -411,3 +419,71 @@ module.exports = definePlugin({ onChatMessage(msg) {} });`)
}())
}
}
+
+// TestManager_UnloadHooksBracketTheInstanceClose defends the contract the
+// two-phase SQL teardown depends on: onUnload runs while the plugin can still
+// execute, and onUnloaded runs only once it cannot. A host resource an in-flight
+// call can still reach has to be released in the second hook, because releasing
+// it in the first lets that call reacquire it after the teardown is finished.
+func TestManager_UnloadHooksBracketTheInstanceClose(t *testing.T) {
+ ctx := context.Background()
+ compiledEngines.resetForTest(ctx)
+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })
+
+ env, sends, mu := captureEnv()
+ dir := t.TempDir()
+ mgr := NewManager(dir, env)
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ script := []byte(`
+const { definePlugin, owncast } = require("@owncast/plugin-sdk");
+module.exports = definePlugin({
+ onChatMessage(msg) { owncast.chat.send("ran: " + msg.body); }
+});`)
+ if _, err := mgr.Install(ctx, buildJSPackageBytes(t, lifecycleManifest(t, "0.1.0", []string{PermChatSend}), script)); err != nil {
+ t.Fatalf("install: %v", err)
+ }
+ if err := mgr.Enable(ctx, "lifecycle-bot"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ loaded := mgr.Snapshot()
+ if len(loaded) != 1 {
+ t.Fatalf("precondition: expected one loaded plugin, got %d", len(loaded))
+ }
+ instance := loaded[0]
+
+ // Dispatching straight to the instance is how an in-flight export call
+ // reaches the host while a teardown is underway.
+ dispatch := func(body string) {
+ NewDispatcher([]*Loaded{instance}).Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", body))
+ }
+ var order []string
+ mgr.SetOnUnload(func(slug string) {
+ order = append(order, "unload:"+slug)
+ dispatch("during unload")
+ })
+ mgr.SetOnUnloaded(func(slug string) {
+ order = append(order, "unloaded:"+slug)
+ dispatch("after unloaded")
+ })
+
+ if err := mgr.Disable(ctx, "lifecycle-bot"); err != nil {
+ t.Fatalf("disable: %v", err)
+ }
+
+ if len(order) != 2 || order[0] != "unload:lifecycle-bot" || order[1] != "unloaded:lifecycle-bot" {
+ t.Fatalf("unload hooks fired as %v, want onUnload then onUnloaded exactly once each", order)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ var ran []string
+ for _, send := range *sends {
+ ran = append(ran, send.Text)
+ }
+ if len(ran) != 1 || ran[0] != "ran: during unload" {
+ t.Fatalf("plugin calls observed during teardown: %v, want only the one from onUnload; a call reaching the plugin after onUnloaded means the hooks do not bracket Close", ran)
+ }
+}
diff --git a/services/plugins/engines/javascript/engine.wasm b/services/plugins/engines/javascript/engine.wasm
index aa082a9691..47736a9423 100644
Binary files a/services/plugins/engines/javascript/engine.wasm and b/services/plugins/engines/javascript/engine.wasm differ
diff --git a/services/plugins/engines/python/engine.wasm b/services/plugins/engines/python/engine.wasm
index 86ffde3a46..4eed378a15 100644
Binary files a/services/plugins/engines/python/engine.wasm and b/services/plugins/engines/python/engine.wasm differ
diff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.go
index ec1a74829a..23b9ca6538 100644
--- a/services/plugins/hostfns.go
+++ b/services/plugins/hostfns.go
@@ -21,12 +21,13 @@ const (
PermStorageKV = "storage.kv"
PermStorageUpload = "storage.upload"
// PermStorageFS grants a plugin a private, sandboxed area on disk
- // (data/plugin-data/<slug>/) it can read, write, list, and delete
+ // (data/plugin-storage/<slug>/files/) it can read, write, list, and delete
// within. Unlike storage.upload (which publishes browser-accessible
// files under public/), this storage is server-side only and never
// exposed over HTTP. A plugin cannot reach outside its own directory
// or read another plugin's files.
PermStorageFS = "storage.fs"
+ PermStorageSQL = "storage.sql"
PermChatSend = "chat.send"
PermChatHistory = "chat.history"
PermChatModerate = "chat.moderate"
@@ -268,6 +269,34 @@ type UploadResult struct {
URL string `json:"url"`
}
+// SQLRequest is a statement, its JSON-serializable bind parameters, and an
+// optional cap on how many rows a query should return. MaxRows of 0 means "no
+// caller-supplied limit", which the host bounds with MaxSQLRows.
+type SQLRequest struct {
+ SQL string `json:"sql"`
+ Params []any `json:"params,omitempty"`
+ MaxRows int `json:"maxRows,omitempty"`
+}
+
+// SQLExecResult reports the effect of one committed SQL statement batch.
+type SQLExecResult struct {
+ OK bool `json:"ok"`
+ Error string `json:"error,omitempty"`
+ RowsAffected int64 `json:"rowsAffected"`
+ LastInsertID int64 `json:"lastInsertId"`
+}
+
+// SQLQueryResult is a bounded set of rows returned by a plugin SQL query.
+// Rows use the same column order as Columns. Truncated reports that the query
+// matched more rows than the caller's MaxRows.
+type SQLQueryResult struct {
+ OK bool `json:"ok"`
+ Error string `json:"error,omitempty"`
+ Columns []string `json:"columns"`
+ Rows [][]any `json:"rows"`
+ Truncated bool `json:"truncated,omitempty"`
+}
+
// SSEConnectionEvent is the payload for the sse.connect / sse.disconnect
// events, fired when a browser opens or closes one of the plugin's
// Server-Sent-Events streams. ConnectionID is unique for the life of the host
@@ -338,16 +367,22 @@ type HostEnv struct {
BanIP func(pluginName, ip string) // users.moderate
UploadStorage func(pluginName, name string, data []byte) (string, error) // storage.upload
// Sandboxed per-plugin filesystem (storage.fs). Each plugin sees only
- // its own directory under data/plugin-data/<slug>/; the host rejects any
- // path that escapes it. Paths are relative to that root.
- FSRead func(pluginName, path string) ([]byte, error) // storage.fs
- FSWrite func(pluginName, path string, data []byte) error
- FSList func(pluginName, dir string) ([]string, error)
- FSDelete func(pluginName, path string) error
- FSExists func(pluginName, path string) (bool, error)
- Socials func() []SocialHandle // server.read
- Emotes func() []Emote // server.read
- Federation func() FederationInfo // server.read
+ // its own directory under data/plugin-storage/<slug>/files/, and the host
+ // rejects any path that escapes it. Paths are relative to that root.
+ FSRead func(pluginName, path string) ([]byte, error) // storage.fs
+ FSWrite func(pluginName, path string, data []byte) error
+ FSList func(pluginName, dir string) ([]string, error)
+ FSDelete func(pluginName, path string) error
+ FSExists func(pluginName, path string) (bool, error)
+ SQLExec func(ctx context.Context, pluginName string, req SQLRequest) SQLExecResult
+ SQLQuery func(ctx context.Context, pluginName string, req SQLRequest) SQLQueryResult
+ // AcquireSQLLease ties a plugin instance to its shared per-slug database.
+ // The returned release runs after the instance is fully closed. Optional;
+ // hosts without persistent SQL leave it nil.
+ AcquireSQLLease func(pluginName string) func()
+ Socials func() []SocialHandle // server.read
+ Emotes func() []Emote // server.read
+ Federation func() FederationInfo // server.read
// ConfigValue resolves an admin-set override for one of the plugin's
// manifest-declared config keys (owncast.config.get). Returns the override
// value and true when the admin has set one; false to fall back to the
@@ -466,9 +501,9 @@ func BuildHostFunctions(env *HostEnv) []extism.HostFunction {
return fns
}
-// storageHostFunctions returns the storage.upload / storage.fs host functions
-// a plugin is granted. Split out of BuildHostFunctions to keep that function's
-// cyclomatic complexity in check.
+// storageHostFunctions returns the storage.upload / storage.fs / storage.sql
+// host functions a plugin is granted. Split out of BuildHostFunctions to keep
+// that function's cyclomatic complexity in check.
func storageHostFunctions(env *HostEnv) []extism.HostFunction {
return []extism.HostFunction{
hostStorageUpload(env),
@@ -477,9 +512,79 @@ func storageHostFunctions(env *HostEnv) []extism.HostFunction {
hostFSList(env),
hostFSDelete(env),
hostFSExists(env),
+ hostSQLExec(env),
+ hostSQLQuery(env),
}
}
+// readSQLRequest pulls the plugin's JSON SQL request out of guest memory and
+// hands it to the shared validator.
+func readSQLRequest(p *extism.CurrentPlugin, ptr uint64) (SQLRequest, error) {
+ raw, err := p.ReadString(ptr)
+ if err != nil {
+ return SQLRequest{}, err
+ }
+ return ParseSQLRequest(raw)
+}
+
+func hostSQLExec(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_sql_exec",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ id, ok := resolveCaller(ctx, "owncast_sql_exec", PermStorageSQL)
+ if !ok {
+ stack[0] = 0
+ return
+ }
+ result := SQLExecResult{}
+ req, err := readSQLRequest(p, stack[0])
+ switch {
+ case err != nil:
+ result.Error = err.Error()
+ case env.SQLExec == nil:
+ result.Error = sqlStorageUnavailable
+ default:
+ result = env.SQLExec(ctx, id.slug, req)
+ }
+ result.OK = result.Error == ""
+ stack[0] = writeJSON(p, result)
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostSQLQuery(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_sql_query",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ id, ok := resolveCaller(ctx, "owncast_sql_query", PermStorageSQL)
+ if !ok {
+ stack[0] = 0
+ return
+ }
+ result := SQLQueryResult{}
+ req, err := readSQLRequest(p, stack[0])
+ switch {
+ case err != nil:
+ result.Error = err.Error()
+ case env.SQLQuery == nil:
+ result.Error = sqlStorageUnavailable
+ default:
+ result = env.SQLQuery(ctx, id.slug, req)
+ }
+ result.OK = result.Error == ""
+ stack[0] = writeJSON(p, result)
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
// videoConfigHostFunctions returns the videoconfig.read / videoconfig.write
// host functions a plugin is granted. Split out of BuildHostFunctions to keep
// that function's cyclomatic complexity in check.
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
index 712c4243d9..402da49252 100644
--- a/services/plugins/manager.go
+++ b/services/plugins/manager.go
@@ -58,7 +58,10 @@ type Loaded struct {
// releaseEngine drops this instance's reference on its shared compiled
// engine (nil for self-contained wasm). Called exactly once by Close,
// after the instance itself is closed.
- releaseEngine func()
+ releaseEngine func()
+ // releaseSQL drops this instance's claim on its per-slug database after
+ // plugin code can no longer call host functions.
+ releaseSQL func()
mu sync.Mutex
failureMu sync.Mutex
filterFails int
@@ -278,6 +281,8 @@ func (l *Loaded) Close(ctx context.Context) {
l.plugin = nil
release := l.releaseEngine
l.releaseEngine = nil
+ releaseSQL := l.releaseSQL
+ l.releaseSQL = nil
l.mu.Unlock()
if pl != nil {
// Closes this instance only; the shared compiled engine is
@@ -289,6 +294,9 @@ func (l *Loaded) Close(ctx context.Context) {
if release != nil {
release()
}
+ if releaseSQL != nil {
+ releaseSQL()
+ }
// Drop the call-time identity so any in-flight or stale host call from this
// plugin resolves to "not found" and fails cleanly rather than acting on a
// torn-down plugin.
@@ -334,16 +342,40 @@ type Manager struct {
// host subsystems can release per-plugin resources. Timers use it to
// cancel a plugin's pending callbacks.
onUnload func(slug string)
+
+ // onUnloaded, if set, is called with the same slug once the instance is
+ // fully closed. Resources that an in-flight export call can still reach
+ // (a plugin's SQL database) release here: onUnload fires while a call may
+ // be mid-flight, and freeing them there lets the call reacquire them
+ // after the teardown believed it was done.
+ onUnloaded func(slug string)
}
// SetOnUnload registers a callback invoked with a plugin's slug right before
// its instance is closed. Used to cancel per-plugin host resources (timers).
func (m *Manager) SetOnUnload(fn func(slug string)) { m.onUnload = fn }
-// notifyUnload fires the onUnload hook for a plugin about to be closed.
-func (m *Manager) notifyUnload(l *Loaded) {
- if m.onUnload != nil && l != nil && l.Manifest != nil {
- m.onUnload(l.Manifest.Slug)
+// SetOnUnloaded registers a callback invoked with a plugin's slug once its
+// instance is closed and no further plugin code can run.
+func (m *Manager) SetOnUnloaded(fn func(slug string)) { m.onUnloaded = fn }
+
+// unload closes one plugin instance, bracketing it with the unload hooks so
+// every teardown path (disable, uninstall, reload, disk-removal, host stop)
+// releases per-plugin host resources the same way.
+func (m *Manager) unload(ctx context.Context, l *Loaded) {
+ if l == nil {
+ return
+ }
+ slug := ""
+ if l.Manifest != nil {
+ slug = l.Manifest.Slug
+ }
+ if m.onUnload != nil && slug != "" {
+ m.onUnload(slug)
+ }
+ l.Close(ctx)
+ if m.onUnloaded != nil && slug != "" {
+ m.onUnloaded(slug)
}
}
@@ -533,8 +565,7 @@ func (m *Manager) Stop(ctx context.Context) {
m.mu.Lock()
defer m.mu.Unlock()
for _, l := range m.loaded {
- m.notifyUnload(l)
- l.Close(ctx)
+ m.unload(ctx, l)
}
m.loaded = map[string]*Loaded{}
}
@@ -670,8 +701,7 @@ func (m *Manager) Enable(ctx context.Context, name string) error {
delete(m.loaded, name)
m.mu.Unlock()
if old != nil {
- m.notifyUnload(old)
- old.Close(ctx)
+ m.unload(ctx, old)
}
return m.loadInternal(ctx, name)
}
@@ -948,8 +978,7 @@ func (m *Manager) Disable(ctx context.Context, name string) error {
fmt.Fprintf(os.Stderr, "persist enabled set: %v\n", err)
}
if loaded != nil {
- m.notifyUnload(loaded)
- loaded.Close(ctx)
+ m.unload(ctx, loaded)
}
// Hand freed pages back to the OS promptly so an operator watching
// process memory sees the disable take effect (the Go scavenger would
@@ -980,8 +1009,7 @@ func (m *Manager) Uninstall(ctx context.Context, name string) error {
m.mu.Unlock()
if loaded != nil {
- m.notifyUnload(loaded)
- loaded.Close(ctx)
+ m.unload(ctx, loaded)
debug.FreeOSMemory()
}
@@ -1042,8 +1070,7 @@ func (m *Manager) Reload(ctx context.Context, name string) error {
delete(m.loaded, name)
m.mu.Unlock()
if loaded != nil {
- m.notifyUnload(loaded)
- loaded.Close(ctx)
+ m.unload(ctx, loaded)
}
// Re-read the manifest from disk so any author-side edits (new admin
@@ -1222,8 +1249,7 @@ func (m *Manager) scan(ctx context.Context) error {
delete(m.loaded, name)
m.mu.Unlock()
if loaded != nil {
- m.notifyUnload(loaded)
- loaded.Close(ctx)
+ m.unload(ctx, loaded)
}
}
return nil
@@ -1495,25 +1521,30 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
return nil, err
}
- // fail tears down the just-created instance (and its engine reference) on
- // any load-path error below.
+ // Register before register() because engine bootstrap evaluates author
+ // top-level code there, and that code may call host functions.
+ globalPluginRegistry.put(buildIdentity(env, manifest, assetsFS))
+ var releaseSQL func()
+ if env.AcquireSQLLease != nil {
+ releaseSQL = env.AcquireSQLLease(manifest.Slug)
+ }
+ loaded := &Loaded{
+ Manifest: manifest,
+ plugin: p,
+ releaseEngine: releaseEngine,
+ releaseSQL: releaseSQL,
+ AssetsFS: assetsFS,
+ }
+
+ // Any load error closes the instance and releases every acquired host
+ // resource, including SQL opened by top-level code during register().
fail := func(err error) error {
- _ = p.Close(ctx)
- if releaseEngine != nil {
- releaseEngine()
- }
+ loaded.Close(ctx)
return err
}
-
- // Register the plugin's identity so shared host functions can resolve it at
- // call time (by the slug stashed in the instance's Extism config). Done
- // before register() because the engine bootstrap evals author top-level
- // code during register(), which may call host functions. On any failure
- // below, drop the identity again.
- globalPluginRegistry.put(buildIdentity(env, manifest, assetsFS))
- loaded := false
+ succeeded := false
defer func() {
- if !loaded {
+ if !succeeded {
globalPluginRegistry.remove(manifest.Slug)
}
}()
@@ -1562,8 +1593,10 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
adminPaths = append(adminPaths, lowered)
}
- loaded = true
- return &Loaded{Manifest: manifest, plugin: p, releaseEngine: releaseEngine, adminGlobs: adminGlobs, adminPaths: adminPaths, AssetsFS: assetsFS}, nil
+ loaded.adminGlobs = adminGlobs
+ loaded.adminPaths = adminPaths
+ succeeded = true
+ return loaded, nil
}
// instantiate creates the extism plugin instance for a manifest: a per-plugin
diff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.json
index 6e738005c1..e8abb59aae 100644
--- a/services/plugins/plugin-contract.json
+++ b/services/plugins/plugin-contract.json
@@ -15,6 +15,7 @@
"PermServerRead": "server.read",
"PermStorageFS": "storage.fs",
"PermStorageKV": "storage.kv",
+ "PermStorageSQL": "storage.sql",
"PermStorageUpload": "storage.upload",
"PermUIModify": "ui.modify",
"PermUsersModerate": "users.moderate",
@@ -56,6 +57,8 @@
"owncast_server_info",
"owncast_server_socials",
"owncast_server_tags",
+ "owncast_sql_exec",
+ "owncast_sql_query",
"owncast_sse_send",
"owncast_storage_upload",
"owncast_stream_broadcaster",
@@ -138,6 +141,24 @@
"previousNames": "[]string",
"scopes": "[]string"
},
+ "SQLExecResult": {
+ "error": "string",
+ "lastInsertId": "int64",
+ "ok": "bool",
+ "rowsAffected": "int64"
+ },
+ "SQLQueryResult": {
+ "columns": "[]string",
+ "error": "string",
+ "ok": "bool",
+ "rows": "[][]any",
+ "truncated": "bool"
+ },
+ "SQLRequest": {
+ "maxRows": "int",
+ "params": "[]any",
+ "sql": "string"
+ },
"SSEConnectionEvent": {
"channel": "string",
"connectionId": "uint64",
diff --git a/services/plugins/sqldenied.go b/services/plugins/sqldenied.go
new file mode 100644
index 0000000000..c15f64e109
--- /dev/null
+++ b/services/plugins/sqldenied.go
@@ -0,0 +1,335 @@
+package plugins
+
+import "strings"
+
+// Owncast refuses a handful of SQL operations for every plugin, and refuses them
+// twice over.
+//
+// The authoritative refusal is the SQLite authorizer pluginhost installs on each
+// connection. It is the security boundary, because it sees the compiled
+// statement rather than its text.
+//
+// This file is the second refusal, and it exists for a different reason: every
+// host that runs plugins has to reject the same statements, or a plugin's own
+// scenario tests are worthless. The SDK's test runner and dev server use a
+// pure-Go SQLite driver that has no authorizer API, so without this check a
+// plugin could exercise `CREATE TEMP TABLE` locally, watch its tests pass, and
+// then fail on a real server. Refusing in Go, above the driver, makes every host
+// agree.
+//
+// A text check is not a boundary and is not treated as one. It runs in front of
+// the authorizer, never instead of it.
+
+// DeniedSQLStatementExamples is the cross-host parity fixture: every statement
+// here must be refused by Owncast and by the SDK's hosts alike. Both repositories
+// assert against this list, so a form discovered later gets fixed everywhere at
+// once instead of drifting.
+var DeniedSQLStatementExamples = []string{
+ // Reaching another database file.
+ "ATTACH DATABASE 'other.db' AS other",
+ "attach database 'other.db' as other",
+ "DETACH DATABASE other",
+ "VACUUM",
+ "VACUUM INTO 'copy.db'",
+ // Reading or changing connection configuration, which is what keeps the
+ // page cap a cap.
+ "PRAGMA max_page_count=100000000",
+ "PRAGMA page_size",
+ "pragma journal_mode = delete",
+ "/* comment */ PRAGMA page_size",
+ "-- comment\nPRAGMA page_size",
+ "SELECT 1; PRAGMA page_size",
+ "EXPLAIN PRAGMA page_size",
+ "EXPLAIN QUERY PLAN ATTACH DATABASE 'other.db' AS other",
+ // Temp-schema objects, which live outside the page cap. The keyword forms
+ // and the schema-qualified forms both have to go: SQLite reports the latter
+ // as ordinary DDL with "temp" in the authorizer's database-name argument.
+ "CREATE TEMP TABLE scratch (v TEXT)",
+ "CREATE TEMPORARY TABLE scratch (v TEXT)",
+ "CREATE TEMP VIEW scratch AS SELECT 1",
+ "DROP TEMP TABLE scratch",
+ "CREATE TABLE temp.scratch (v TEXT)",
+ `CREATE TABLE "temp".scratch (v TEXT)`,
+ "CREATE TABLE TeMp.scratch (v TEXT)",
+ "CREATE TABLE [temp].scratch (v TEXT)",
+ "CREATE VIEW temp.scratch AS SELECT 1",
+ "CREATE INDEX temp.i ON scratch (v)",
+ "SELECT load_extension/* comment */('evil.so')",
+ "CREATE TABLE temp/* comment */.scratch (v TEXT)",
+ "SELECT load_extension\f('evil.so')",
+ "CREATE TABLE temp\f.scratch (v TEXT)",
+ "INSERT INTO temp.scratch VALUES ('x')",
+ "SELECT * FROM temp.scratch",
+ "SELECT * FROM sqlite_temp_master",
+ "SELECT * FROM sqlite_temp_schema",
+ // Loading native code.
+ "SELECT load_extension('evil.so')",
+ "SELECT LOAD_EXTENSION('evil.so')",
+}
+
+const deniedTransactionControl = "transaction control is not available to plugins"
+
+// deniedStatementHeads are keywords a plugin's top-level statement may not
+// begin with. Transaction controls are also refused so the host owns every
+// call's commit or rollback; CREATE TRIGGER bodies are tracked separately
+// because their terminating END follows an internal semicolon.
+var deniedStatementHeads = map[string]string{
+ "pragma": "PRAGMA is not available to plugins",
+ "attach": "ATTACH is not available to plugins",
+ "detach": "DETACH is not available to plugins",
+ "vacuum": "VACUUM is not available to plugins",
+ "begin": deniedTransactionControl,
+ "commit": deniedTransactionControl,
+ "end": deniedTransactionControl,
+ "rollback": deniedTransactionControl,
+ "savepoint": deniedTransactionControl,
+ "release": deniedTransactionControl,
+}
+
+// deniedIdentifiers name the temp schema without the TEMP keyword.
+var deniedIdentifiers = map[string]string{
+ "sqlite_temp_master": "the temp schema is not available to plugins",
+ "sqlite_temp_schema": "the temp schema is not available to plugins",
+}
+
+// deniedFunctions may not be called. Unlike the statement heads these appear
+// mid-expression, so they are matched as a name followed by an open parenthesis.
+var deniedFunctions = map[string]string{
+ "load_extension": "load_extension is not available to plugins",
+}
+
+const deniedTempSchema = "temporary tables, indexes, views, and triggers are not available to plugins"
+
+// DeniedSQLReason reports why a plugin's SQL may not run, or an empty string
+// when nothing in it is refused. The message is what the plugin sees, so it says
+// what is unavailable rather than which check tripped.
+func DeniedSQLReason(statement string) string {
+ var previous string
+ explainPrefix := 0
+ atStatementStart := true
+ var trigger sqlTriggerState
+ for _, token := range scanSQLTokens(statement) {
+ switch {
+ case token.terminator:
+ if !trigger.endStatement() {
+ continue
+ }
+ atStatementStart = true
+ previous = ""
+ explainPrefix = 0
+ continue
+ case atStatementStart:
+ if consumeSQLExplainPrefix(token.text, &explainPrefix) {
+ continue
+ }
+ if reason, ok := deniedStatementHeads[token.text]; ok {
+ return reason
+ }
+ atStatementStart = false
+ explainPrefix = 0
+ }
+ trigger.observe(previous, token)
+ if reason := deniedSQLTokenReason(previous, token); reason != "" {
+ return reason
+ }
+ previous = token.text
+ }
+ return ""
+}
+
+func deniedSQLTokenReason(previous string, token sqlToken) string {
+ if reason, ok := deniedIdentifiers[token.text]; ok {
+ return reason
+ }
+ if token.call {
+ if reason, ok := deniedFunctions[token.text]; ok {
+ return reason
+ }
+ }
+ // A schema qualifier is an identifier followed by a dot.
+ if token.qualifier && token.text == "temp" {
+ return deniedTempSchema
+ }
+ if (previous == "create" || previous == "drop") && (token.text == "temp" || token.text == "temporary") {
+ return deniedTempSchema
+ }
+ return ""
+}
+
+// sqlTriggerState distinguishes semicolons inside a CREATE TRIGGER body from
+// top-level statement boundaries. CASE has its own END token, so its nesting
+// must reach zero before END can close the trigger body.
+type sqlTriggerState struct {
+ inTrigger bool
+ body bool
+ ended bool
+ caseDepth int
+}
+
+func (s *sqlTriggerState) observe(previous string, token sqlToken) {
+ if token.quoted {
+ return
+ }
+ if previous == "create" && token.text == "trigger" {
+ s.inTrigger = true
+ }
+ if !s.inTrigger {
+ return
+ }
+ switch token.text {
+ case "begin":
+ s.body = true
+ case "case":
+ if s.body {
+ s.caseDepth++
+ }
+ case "end":
+ if s.caseDepth > 0 {
+ s.caseDepth--
+ } else if s.body {
+ s.ended = true
+ }
+ }
+}
+
+func (s *sqlTriggerState) endStatement() bool {
+ if s.inTrigger && !s.ended {
+ return false
+ }
+ *s = sqlTriggerState{}
+ return true
+}
+
+// consumeSQLExplainPrefix keeps the following statement head visible to the
+// denial rules while skipping SQLite's optional EXPLAIN QUERY PLAN prefix.
+func consumeSQLExplainPrefix(token string, state *int) bool {
+ switch {
+ case *state == 0 && token == "explain":
+ *state = 1
+ case *state == 1 && token == "query":
+ *state = 2
+ case *state == 2 && token == "plan":
+ *state = 3
+ default:
+ return false
+ }
+ return true
+}
+
+// sqlToken is one lexical item of interest: a lower-cased keyword or identifier,
+// a statement terminator, or an identifier used as a schema qualifier.
+type sqlToken struct {
+ text string
+ terminator bool
+ qualifier bool
+ call bool
+ quoted bool
+}
+
+// scanSQLTokens reduces SQL to the tokens DeniedSQLReason needs to see. It skips
+// string literals and comments so their contents cannot trip a rule, and
+// unquotes delimited identifiers so `"temp"` and `[temp]` read the same as
+// `temp`. It is not a SQL parser and does not try to be: it recognizes
+// statement boundaries, keywords, identifiers, and schema qualifiers, and
+// ignores everything else.
+func scanSQLTokens(statement string) []sqlToken {
+ var tokens []sqlToken
+ runes := []rune(statement)
+ for i := 0; i < len(runes); {
+ switch c := runes[i]; {
+ case c == '-' && i+1 < len(runes) && runes[i+1] == '-':
+ i = skipSQLLineComment(runes, i)
+ case c == '/' && i+1 < len(runes) && runes[i+1] == '*':
+ i = skipSQLBlockComment(runes, i)
+ case c == '\'':
+ i = skipSQLDelimited(runes, i, '\'')
+ case c == '"', c == '[', c == '`':
+ end := skipSQLDelimited(runes, i, sqlIdentifierCloser(c))
+ // Read the identifier without its delimiters, so `"temp"` and
+ // `[temp]` are the same token as `temp`.
+ text := strings.ToLower(strings.TrimSpace(string(runes[i+1 : max(end-1, i+1)])))
+ tokens = append(tokens, newSQLToken(text, runes, end, true))
+ i = end
+ case c == ';':
+ tokens = append(tokens, sqlToken{terminator: true})
+ i++
+ case isSQLWordRune(c):
+ start := i
+ for i < len(runes) && isSQLWordRune(runes[i]) {
+ i++
+ }
+ tokens = append(tokens, newSQLToken(strings.ToLower(string(runes[start:i])), runes, i, false))
+ default:
+ i++
+ }
+ }
+ return tokens
+}
+
+func sqlIdentifierCloser(opener rune) rune {
+ if opener == '[' {
+ return ']'
+ }
+ return opener
+}
+
+func skipSQLLineComment(runes []rune, i int) int {
+ for ; i < len(runes) && runes[i] != '\n'; i++ {
+ }
+ return i
+}
+
+func skipSQLBlockComment(runes []rune, i int) int {
+ for i += 2; i+1 < len(runes); i++ {
+ if runes[i] == '*' && runes[i+1] == '/' {
+ return i + 2
+ }
+ }
+ return len(runes)
+}
+
+// skipSQLDelimited returns the index just past the delimited run beginning at
+// start, treating a doubled closer as an escape the way SQLite does.
+func skipSQLDelimited(runes []rune, start int, closer rune) int {
+ for i := start + 1; i < len(runes); i++ {
+ if runes[i] != closer {
+ continue
+ }
+ if i+1 < len(runes) && runes[i+1] == closer {
+ i++
+ continue
+ }
+ return i + 1
+ }
+ return len(runes)
+}
+
+// newSQLToken records what follows a word: a dot makes it a schema or table
+// qualifier, an open parenthesis makes it a function call.
+func newSQLToken(text string, runes []rune, end int, quoted bool) sqlToken {
+ next := nextSQLRune(runes, end)
+ return sqlToken{text: text, qualifier: next == '.', call: next == '(', quoted: quoted}
+}
+
+// nextSQLRune returns the next rune that is not whitespace or part of a
+// comment, or 0 at the end. SQLite treats comments as whitespace, including
+// between a function name and its parenthesis or a schema and its dot.
+func nextSQLRune(runes []rune, i int) rune {
+ for i < len(runes) {
+ switch {
+ case runes[i] == '-' && i+1 < len(runes) && runes[i+1] == '-':
+ i = skipSQLLineComment(runes, i)
+ case runes[i] == '/' && i+1 < len(runes) && runes[i+1] == '*':
+ i = skipSQLBlockComment(runes, i)
+ case strings.ContainsRune(" \t\n\r\f", runes[i]):
+ i++
+ default:
+ return runes[i]
+ }
+ }
+ return 0
+}
+
+func isSQLWordRune(c rune) bool {
+ return c == '_' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
+}
diff --git a/services/plugins/sqldenied_test.go b/services/plugins/sqldenied_test.go
new file mode 100644
index 0000000000..d0de515da0
--- /dev/null
+++ b/services/plugins/sqldenied_test.go
@@ -0,0 +1,115 @@
+package plugins
+
+import (
+ "strings"
+ "testing"
+)
+
+// Every statement in the shared parity fixture must be refused before it reaches
+// a driver, so a plugin gets the same answer from Owncast and from the SDK's
+// hosts. pluginhost has the matching test against the real authorizer.
+func TestDeniedSQLReasonRefusesEveryParityExample(t *testing.T) {
+ for _, statement := range DeniedSQLStatementExamples {
+ if reason := DeniedSQLReason(statement); reason == "" {
+ t.Errorf("statement is not refused: %q", statement)
+ }
+ }
+}
+
+// ParseSQLRequest is the single entry point both hosts use, so the refusal has to
+// happen there and not only in the helper.
+func TestParseSQLRequestRefusesDeniedStatements(t *testing.T) {
+ for _, statement := range []string{
+ "PRAGMA page_size",
+ "CREATE TEMP TABLE t (v)",
+ "CREATE TABLE temp.t (v)",
+ "BEGIN IMMEDIATE",
+ "COMMIT",
+ "END",
+ "ROLLBACK",
+ "SAVEPOINT plugin",
+ "RELEASE plugin",
+ "CREATE TRIGGER touch AFTER INSERT ON items BEGIN SELECT CASE WHEN 1 THEN 1 END; END; COMMIT",
+ `CREATE TRIGGER quoted AFTER INSERT ON items BEGIN UPDATE items SET name = "case"; END; PRAGMA page_size`,
+ } {
+ raw := `{"sql":` + quoteJSON(statement) + `}`
+ if _, err := ParseSQLRequest(raw); err == nil {
+ t.Errorf("ParseSQLRequest accepted %q", statement)
+ }
+ }
+}
+
+// The check must not cost ordinary SQL anything. These are the shapes a real
+// plugin writes, including ones that mention the denied words inside string
+// literals, comments, column names, and identifiers that merely start with
+// "temp".
+func TestDeniedSQLReasonAllowsOrdinarySQL(t *testing.T) {
+ for _, statement := range []string{
+ "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)",
+ "CREATE TABLE main.items (id INTEGER PRIMARY KEY)",
+ "CREATE INDEX items_name ON items (name)",
+ "CREATE VIEW item_names AS SELECT name FROM items",
+ "CREATE TRIGGER touch AFTER INSERT ON items BEGIN UPDATE items SET name = name; END",
+ "CREATE TRIGGER choose AFTER INSERT ON items BEGIN UPDATE items SET name = CASE WHEN name = '' THEN 'empty' ELSE name END; END",
+ `CREATE TRIGGER quoted AFTER INSERT ON items BEGIN UPDATE items SET "end" = "case"; END`,
+ "INSERT INTO items (name) VALUES (?)",
+ "SELECT name FROM items ORDER BY name",
+ "EXPLAIN SELECT name FROM items",
+ "EXPLAIN QUERY PLAN SELECT name FROM items",
+ "WITH RECURSIVE c(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM c WHERE i < 10) SELECT count(*) FROM c",
+ "SELECT json_object('name', name) FROM items",
+ "UPDATE items SET name = 'PRAGMA page_size' WHERE id = 1",
+ "INSERT INTO items (name) VALUES ('CREATE TEMP TABLE x')",
+ "INSERT INTO items (name) VALUES ('attach database ''x'' as y')",
+ "SELECT 'temp.scratch' AS label FROM items",
+ "-- PRAGMA page_size\nSELECT 1",
+ "/* ATTACH DATABASE */ SELECT 1",
+ "CREATE TABLE temperature (celsius REAL)",
+ "SELECT temperature FROM temperature",
+ "CREATE TABLE templates (body TEXT)",
+ "SELECT items.name FROM items",
+ "SELECT main.items.name FROM main.items",
+ "CREATE TABLE t (temp INTEGER)",
+ "SELECT temp FROM t",
+ } {
+ if reason := DeniedSQLReason(statement); reason != "" {
+ t.Errorf("ordinary SQL was refused: %q (%s)", statement, reason)
+ }
+ }
+}
+
+// The message reaches the plugin author, so it should name the capability rather
+// than the internals.
+func TestDeniedSQLReasonExplainsWhatIsUnavailable(t *testing.T) {
+ for statement, want := range map[string]string{
+ "PRAGMA page_size": "PRAGMA",
+ "ATTACH DATABASE 'x' AS y": "ATTACH",
+ "CREATE TEMP TABLE t (v)": "temporary tables",
+ "CREATE TABLE temp.t (v)": "temporary tables",
+ "SELECT * FROM sqlite_temp_master": "temp schema",
+ } {
+ reason := DeniedSQLReason(statement)
+ if !strings.Contains(reason, want) {
+ t.Errorf("%q produced %q, want it to mention %q", statement, reason, want)
+ }
+ }
+}
+
+func quoteJSON(s string) string {
+ var b strings.Builder
+ b.WriteByte('"')
+ for _, r := range s {
+ switch r {
+ case '"':
+ b.WriteString(`\"`)
+ case '\\':
+ b.WriteString(`\\`)
+ case '\n':
+ b.WriteString(`\n`)
+ default:
+ b.WriteRune(r)
+ }
+ }
+ b.WriteByte('"')
+ return b.String()
+}
diff --git a/services/plugins/sqlrunner.go b/services/plugins/sqlrunner.go
new file mode 100644
index 0000000000..29a54986d3
--- /dev/null
+++ b/services/plugins/sqlrunner.go
@@ -0,0 +1,334 @@
+package plugins
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+ "time"
+ "unicode/utf8"
+)
+
+// Limits applied to plugin SQL in Go rather than by the SQLite driver, so they
+// hold whatever driver a host wires up. pluginhost additionally pins the
+// matching SQLite-level limits (SQLITE_LIMIT_LENGTH, SQLITE_LIMIT_VARIABLE_NUMBER,
+// …) so an oversized value is refused inside the engine before it is ever
+// materialized; these checks are the driver-independent floor under that.
+const (
+ // MaxSQLStatementBytes caps the JSON request a plugin passes to the host,
+ // which bounds the statement text along with it.
+ MaxSQLStatementBytes = 64 << 10
+ // MaxSQLParams caps bound parameters per statement.
+ MaxSQLParams = 64
+ // MaxSQLValueBytes caps a single returned column value.
+ MaxSQLValueBytes = 1 << 20
+ // MaxSQLResultBytes caps the encoded size of a whole query result.
+ MaxSQLResultBytes = 1 << 20
+ // MaxSQLRows caps rows returned when the plugin does not ask for fewer.
+ // Overrunning it is an error, not a silent truncation: a plugin that reads
+ // an unbounded table must say so with a LIMIT.
+ MaxSQLRows = 10000
+ // SQLCallTimeout bounds one exec or query, including time spent waiting on
+ // the plugin's serialized connection.
+ SQLCallTimeout = 2 * time.Second
+)
+
+// sqlStorageUnavailable is what a plugin sees when the host it is running in
+// wires no SQL backend at all.
+const sqlStorageUnavailable = "SQL storage unavailable"
+
+// errSQLResultTooLarge is the shared "narrow your query" error. Plugins see the
+// text, so it names the fix rather than the internal limit that tripped.
+func errSQLResultTooLarge(what string, limit int) error {
+ return fmt.Errorf("SQL %s exceeds %d bytes; add a LIMIT or select fewer columns", what, limit)
+}
+
+// ParseSQLRequest decodes and validates the JSON request a plugin passes to
+// owncast_sql_exec / owncast_sql_query.
+//
+// Numbers are decoded with json.Number so an integral parameter binds as an
+// int64: plain interface{} decoding would turn every number into a float64 and
+// silently round anything past 2^53 before it reached SQLite, or store it with
+// REAL affinity.
+func ParseSQLRequest(raw string) (SQLRequest, error) {
+ if len(raw) > MaxSQLStatementBytes {
+ return SQLRequest{}, fmt.Errorf("SQL request exceeds %d bytes", MaxSQLStatementBytes)
+ }
+ decoder := json.NewDecoder(strings.NewReader(raw))
+ decoder.UseNumber()
+ var req SQLRequest
+ if err := decoder.Decode(&req); err != nil {
+ return SQLRequest{}, fmt.Errorf("invalid SQL request: %w", err)
+ }
+ if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
+ return SQLRequest{}, errors.New("invalid SQL request: trailing data")
+ }
+ req.SQL = strings.TrimSpace(req.SQL)
+ if req.SQL == "" {
+ return SQLRequest{}, errors.New("SQL statement is empty")
+ }
+ if reason := DeniedSQLReason(req.SQL); reason != "" {
+ return SQLRequest{}, errors.New(reason)
+ }
+ if req.MaxRows < 0 || req.MaxRows > MaxSQLRows {
+ return SQLRequest{}, fmt.Errorf("SQL maxRows must be between 0 and %d", MaxSQLRows)
+ }
+ if len(req.Params) > MaxSQLParams {
+ return SQLRequest{}, fmt.Errorf("SQL request has more than %d parameters", MaxSQLParams)
+ }
+ for i, param := range req.Params {
+ value, err := sqlParamValue(param)
+ if err != nil {
+ return SQLRequest{}, err
+ }
+ req.Params[i] = value
+ }
+ return req, nil
+}
+
+// sqlParamValue narrows one decoded JSON value to a type SQLite can bind.
+func sqlParamValue(param any) (any, error) {
+ switch v := param.(type) {
+ case nil, bool, string:
+ return v, nil
+ case json.Number:
+ if i, err := v.Int64(); err == nil {
+ return i, nil
+ }
+ f, err := v.Float64()
+ if err != nil {
+ return nil, fmt.Errorf("SQL parameter %q is not a representable number", v.String())
+ }
+ return f, nil
+ default:
+ return nil, errors.New("SQL parameters must be null, boolean, number, or string")
+ }
+}
+
+// SQLRunner executes plugin SQL requests against one plugin's database with the
+// host's limits applied. It holds the policy that does not depend on the SQLite
+// driver: request validation, parameter typing, the call timeout, transaction
+// semantics, and the row, value, and result caps. pluginhost owns the rest, the
+// parts that need the driver itself (the authorizer, the SQLite-level limits,
+// the per-plugin file, and the connection lifecycle).
+//
+// The split keeps this half testable without a database file and keeps the
+// driver-specific half small enough to audit.
+type SQLRunner struct {
+ DB *sql.DB
+}
+
+// Exec runs the request as one transaction: a multi-statement batch either
+// commits whole or leaves the database untouched, and a plugin cannot leave a
+// transaction open across calls.
+func (r SQLRunner) Exec(ctx context.Context, req SQLRequest) SQLExecResult {
+ if r.DB == nil {
+ return SQLExecResult{Error: sqlStorageUnavailable}
+ }
+ ctx, cancel := context.WithTimeout(ctx, SQLCallTimeout)
+ defer cancel()
+
+ tx, err := r.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return SQLExecResult{Error: err.Error()}
+ }
+ result, err := tx.ExecContext(ctx, req.SQL, req.Params...)
+ if err != nil {
+ _ = tx.Rollback()
+ return SQLExecResult{Error: err.Error()}
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ _ = tx.Rollback()
+ return SQLExecResult{Error: err.Error()}
+ }
+ lastInsertID, err := result.LastInsertId()
+ if err != nil {
+ _ = tx.Rollback()
+ return SQLExecResult{Error: err.Error()}
+ }
+ if err := tx.Commit(); err != nil {
+ return SQLExecResult{Error: err.Error()}
+ }
+ return SQLExecResult{OK: true, RowsAffected: rowsAffected, LastInsertID: lastInsertID}
+}
+
+// Query runs the request and returns a bounded result set.
+//
+// MaxRows expresses intent: a plugin that asks for N rows gets at most N and
+// learns from Truncated that more matched, which is how queryRow reads one row
+// out of a large table without pulling it into the host. A plugin that asks for
+// no limit gets an error rather than a silently short answer once the result
+// passes MaxSQLRows or MaxSQLResultBytes.
+func (r SQLRunner) Query(ctx context.Context, req SQLRequest) SQLQueryResult {
+ if r.DB == nil {
+ return SQLQueryResult{Error: sqlStorageUnavailable}
+ }
+ ctx, cancel := context.WithTimeout(ctx, SQLCallTimeout)
+ defer cancel()
+
+ tx, err := r.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+ defer func() { _ = tx.Rollback() }()
+ rows, err := tx.QueryContext(ctx, req.SQL, req.Params...)
+ if err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+ defer rows.Close()
+
+ columns, err := rows.Columns()
+ if err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+ bounded := req.MaxRows > 0
+ rowBudget := MaxSQLRows
+ if bounded {
+ rowBudget = req.MaxRows
+ }
+ builder, err := newSQLResultBuilder(columns, rowBudget)
+ if err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+
+ for rows.Next() {
+ if builder.full() {
+ if bounded {
+ builder.result.Truncated = true
+ break
+ }
+ return SQLQueryResult{Error: fmt.Sprintf("SQL result exceeds %d rows; add a LIMIT", MaxSQLRows)}
+ }
+ values, err := scanSQLRow(rows, len(columns))
+ if err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+ if err := builder.add(values); err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+ if err := rows.Close(); err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+ if err := tx.Commit(); err != nil {
+ return SQLQueryResult{Error: err.Error()}
+ }
+ return builder.result
+}
+
+// scanSQLRow reads one row into freshly allocated values. The values become the
+// result's own row, so they cannot be reused across iterations.
+func scanSQLRow(rows *sql.Rows, columns int) ([]any, error) {
+ values := make([]any, columns)
+ pointers := make([]any, columns)
+ for i := range values {
+ pointers[i] = &values[i]
+ }
+ if err := rows.Scan(pointers...); err != nil {
+ return nil, err
+ }
+ return values, nil
+}
+
+// sqlResultBuilder accumulates rows while keeping the JSON the plugin will
+// receive inside the host's value, byte, and row budgets.
+type sqlResultBuilder struct {
+ result SQLQueryResult
+ used int
+ rowBudget int
+}
+
+func newSQLResultBuilder(columns []string, rowBudget int) (*sqlResultBuilder, error) {
+ encodedColumns, err := json.Marshal(columns)
+ if err != nil {
+ return nil, err
+ }
+ return &sqlResultBuilder{
+ result: SQLQueryResult{OK: true, Columns: columns, Rows: make([][]any, 0, min(rowBudget, 64))},
+ // The envelope's fixed keys, column names, and optional truncation marker
+ // count against the budget so every encoded result stays within the cap.
+ used: len(encodedColumns) + len(`{"ok":true,"columns":,"rows":[]}`) + len(`,"truncated":true`),
+ rowBudget: rowBudget,
+ }, nil
+}
+
+func (b *sqlResultBuilder) full() bool { return len(b.result.Rows) == b.rowBudget }
+
+// add appends one row, or reports why it does not fit.
+func (b *sqlResultBuilder) add(values []any) error {
+ // Size the values before encoding them: a driver that cannot pin
+ // SQLITE_LIMIT_LENGTH could otherwise hand back a single value whose JSON
+ // encoding dwarfs the entire result budget.
+ estimate := len(`[],`)
+ for _, value := range values {
+ size := sqlValueSize(value)
+ if size > MaxSQLValueBytes {
+ return errSQLResultTooLarge("value", MaxSQLValueBytes)
+ }
+ estimate += size + 1
+ }
+ if b.used+estimate > MaxSQLResultBytes {
+ return errSQLResultTooLarge("result", MaxSQLResultBytes)
+ }
+ encodedRow, err := json.Marshal(values)
+ if err != nil {
+ return err
+ }
+ b.used += len(encodedRow) + 1
+ if b.used > MaxSQLResultBytes {
+ return errSQLResultTooLarge("result", MaxSQLResultBytes)
+ }
+ b.result.Rows = append(b.result.Rows, values)
+ return nil
+}
+
+// sqlValueSize returns the JSON-encoded size of one scanned column value
+// without allocating. Strings and blobs dominate; everything else is short.
+func sqlValueSize(value any) int {
+ switch v := value.(type) {
+ case nil:
+ return len("null")
+ case bool:
+ return len("false")
+ case string:
+ if len(v) > MaxSQLValueBytes {
+ return len(v) + 2
+ }
+ size := 2 // quotes
+ for i := 0; i < len(v); {
+ r, width := utf8.DecodeRuneInString(v[i:])
+ i += width
+ if r == utf8.RuneError && width == 1 {
+ size += 6
+ continue
+ }
+ switch r {
+ case '\\', '"', '\b', '\f', '\n', '\r', '\t':
+ size += 2
+ case '<', '>', '&', '\u2028', '\u2029':
+ size += 6
+ default:
+ if r < 0x20 {
+ size += 6
+ } else {
+ size += width
+ }
+ }
+ }
+ return size
+ case []byte:
+ // database/sql hands blobs back as []byte, which encoding/json emits as
+ // base64: four characters per three bytes, plus quotes.
+ return (len(v)+2)/3*4 + 2
+ default:
+ // Numbers and time values encode to short literals.
+ return 32
+ }
+}
diff --git a/services/plugins/sqlrunner_test.go b/services/plugins/sqlrunner_test.go
new file mode 100644
index 0000000000..f62401b740
--- /dev/null
+++ b/services/plugins/sqlrunner_test.go
@@ -0,0 +1,268 @@
+package plugins
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+
+ _ "github.com/mattn/go-sqlite3"
+)
+
+func newRunner(t *testing.T) SQLRunner {
+ t.Helper()
+ db, err := sql.Open("sqlite3", ":memory:")
+ if err != nil {
+ t.Fatal(err)
+ }
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { _ = db.Close() })
+ return SQLRunner{DB: db}
+}
+
+// An integral JSON parameter must reach SQLite as an int64. Decoding into
+// interface{} yields float64, which rounds past 2^53 and can bind with REAL
+// affinity, silently corrupting what the plugin stored.
+func TestParseSQLRequestKeepsIntegerParametersExact(t *testing.T) {
+ req, err := ParseSQLRequest(`{"sql":"SELECT ?, ?, ?, ?, ?","params":[1152921504606846977,-5,1.5,"x",null]}`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := req.Params[0], int64(1152921504606846977); got != want {
+ t.Fatalf("large integer decoded as %#v (%T), want %d", got, got, want)
+ }
+ if got, want := req.Params[1], int64(-5); got != want {
+ t.Fatalf("negative integer decoded as %#v, want %d", got, want)
+ }
+ if got, want := req.Params[2], 1.5; got != want {
+ t.Fatalf("fractional number decoded as %#v, want %v", got, want)
+ }
+ if req.Params[3] != "x" || req.Params[4] != nil {
+ t.Fatalf("string/null parameters decoded as %#v, %#v", req.Params[3], req.Params[4])
+ }
+}
+
+func TestSQLRunnerStoresLargeIntegersAsIntegers(t *testing.T) {
+ runner := newRunner(t)
+ ctx := context.Background()
+ if result := runner.Exec(ctx, SQLRequest{SQL: "CREATE TABLE t (v)"}); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ req, err := ParseSQLRequest(`{"sql":"INSERT INTO t VALUES (?)","params":[1152921504606846977]}`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result := runner.Exec(ctx, req); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ // A column with no affinity keeps whatever type was bound, so this fails if
+ // the parameter arrived as a float.
+ result := runner.Query(ctx, SQLRequest{SQL: "SELECT typeof(v), v FROM t"})
+ if result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ if got := result.Rows[0][0]; got != "integer" {
+ t.Fatalf("stored value has type %v, want integer", got)
+ }
+ if got, want := result.Rows[0][1], int64(1152921504606846977); got != want {
+ t.Fatalf("stored value is %v, want %d", got, want)
+ }
+}
+
+func TestParseSQLRequestRejectsBadRequests(t *testing.T) {
+ for name, raw := range map[string]string{
+ "empty statement": `{"sql":" "}`,
+ "whitespace only": `{"sql":"\n\t"}`,
+ "not json": `{"sql":`,
+ "trailing object": `{"sql":"SELECT 1"}{"sql":"SELECT 2"}`,
+ "trailing junk": `{"sql":"SELECT 1"}junk`,
+ "array parameter": `{"sql":"SELECT ?","params":[[1,2]]}`,
+ "object parameter": `{"sql":"SELECT ?","params":[{"a":1}]}`,
+ "too many parameters": fmt.Sprintf(`{"sql":"SELECT 1","params":[%s]}`, strings.TrimSuffix(strings.Repeat("1,", MaxSQLParams+1), ",")),
+ "oversized statement": fmt.Sprintf(`{"sql":"SELECT '%s'"}`, strings.Repeat("x", MaxSQLStatementBytes)),
+ "unrepresentable size": `{"sql":"SELECT ?","params":[1e999]}`,
+ "negative max rows": `{"sql":"SELECT 1","maxRows":-1}`,
+ "too many max rows": fmt.Sprintf(`{"sql":"SELECT 1","maxRows":%d}`, MaxSQLRows+1),
+ } {
+ if _, err := ParseSQLRequest(raw); err == nil {
+ t.Errorf("%s: expected a validation error", name)
+ }
+ }
+ if _, err := ParseSQLRequest(`{"sql":"SELECT 1"}`); err != nil {
+ t.Fatalf("a valid request was rejected: %v", err)
+ }
+}
+
+// An unbounded query that overruns the row cap is an error, not a short answer:
+// a plugin must not silently act on a truncated view of its own table.
+func TestSQLRunnerRowCapIsAnErrorWhenUnbounded(t *testing.T) {
+ runner := newRunner(t)
+ ctx := context.Background()
+ seed(t, runner, MaxSQLRows+1)
+
+ result := runner.Query(ctx, SQLRequest{SQL: "SELECT n FROM t"})
+ if result.Error == "" || !strings.Contains(result.Error, "add a LIMIT") {
+ t.Fatalf("expected a row-cap error, got %d rows and error %q", len(result.Rows), result.Error)
+ }
+ if result.OK {
+ t.Fatal("a failed query must not report ok")
+ }
+}
+
+// A caller-supplied MaxRows is intent, so the host stops there and says it
+// truncated. This is what lets queryRow read one row out of a large table.
+func TestSQLRunnerMaxRowsTruncatesInsteadOfFailing(t *testing.T) {
+ runner := newRunner(t)
+ ctx := context.Background()
+ seed(t, runner, MaxSQLRows+50)
+
+ result := runner.Query(ctx, SQLRequest{SQL: "SELECT n FROM t ORDER BY n", MaxRows: 1})
+ if result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ if len(result.Rows) != 1 {
+ t.Fatalf("asked for 1 row, got %d", len(result.Rows))
+ }
+ if !result.Truncated {
+ t.Fatal("expected truncated to report that more rows matched")
+ }
+ if got, want := result.Rows[0][0], int64(0); got != want {
+ t.Fatalf("first row is %v, want %v", got, want)
+ }
+
+ exact := runner.Query(ctx, SQLRequest{SQL: "SELECT n FROM t WHERE n < 3 ORDER BY n", MaxRows: 3})
+ if exact.Error != "" || len(exact.Rows) != 3 {
+ t.Fatalf("expected 3 rows, got %+v", exact)
+ }
+ if exact.Truncated {
+ t.Fatal("a result that fit must not report truncation")
+ }
+}
+
+// The runner is the portable floor under SQLITE_LIMIT_LENGTH: a driver that
+// cannot pin that limit must still not be able to hand a huge value through.
+func TestSQLRunnerBoundsValueAndResultSize(t *testing.T) {
+ runner := newRunner(t)
+ ctx := context.Background()
+
+ oversized := runner.Query(ctx, SQLRequest{SQL: fmt.Sprintf("SELECT hex(zeroblob(%d))", MaxSQLValueBytes)})
+ if oversized.Error == "" || !strings.Contains(oversized.Error, "value exceeds") {
+ t.Fatalf("expected a per-value limit error, got %q", oversized.Error)
+ }
+
+ escaped := runner.Query(ctx, SQLRequest{
+ SQL: "SELECT ?",
+ Params: []any{strings.Repeat("<", MaxSQLValueBytes/6+1)},
+ })
+ if escaped.Error == "" || !strings.Contains(escaped.Error, "value exceeds") {
+ t.Fatalf("expected JSON escaping to count against the per-value limit, got %q", escaped.Error)
+ }
+
+ if result := runner.Exec(ctx, SQLRequest{SQL: "CREATE TABLE t (n INTEGER, pad TEXT)"}); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ pad := strings.Repeat("x", 4096)
+ for i := 0; i < 400; i++ {
+ if result := runner.Exec(ctx, SQLRequest{SQL: "INSERT INTO t VALUES (?, ?)", Params: []any{int64(i), pad}}); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ }
+ result := runner.Query(ctx, SQLRequest{SQL: "SELECT n, pad FROM t"})
+ if result.Error == "" || !strings.Contains(result.Error, "add a LIMIT") {
+ t.Fatalf("expected a result-size error well under the row cap, got %d rows and error %q", len(result.Rows), result.Error)
+ }
+ // The same query with a caller limit small enough to fit still works.
+ bounded := runner.Query(ctx, SQLRequest{SQL: "SELECT n, pad FROM t", MaxRows: 10})
+ if bounded.Error != "" || len(bounded.Rows) != 10 {
+ t.Fatalf("a bounded read of the same table should succeed, got %+v", bounded.Error)
+ }
+}
+
+func TestSQLValueSizeAccountsForJSONEscaping(t *testing.T) {
+ for _, value := range []string{
+ "plain",
+ "\"\\\b\f\n\r\t",
+ "\x00\x1f",
+ "<>&",
+ "\u2028\u2029",
+ string([]byte{0xff}),
+ } {
+ encoded, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := sqlValueSize(value); got != len(encoded) {
+ t.Errorf("size of %q is %d, want %d", value, got, len(encoded))
+ }
+ }
+}
+
+// Whatever the runner returns has to survive the trip to the plugin as JSON,
+// and it must stay inside the advertised budget.
+func TestSQLRunnerResultEncodesWithinBudget(t *testing.T) {
+ runner := newRunner(t)
+ ctx := context.Background()
+ seed(t, runner, 500)
+
+ result := runner.Query(ctx, SQLRequest{SQL: "SELECT n FROM t ORDER BY n", MaxRows: 500})
+ if result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ encoded, err := json.Marshal(result)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(encoded) > MaxSQLResultBytes {
+ t.Fatalf("encoded result is %d bytes, over the %d-byte budget", len(encoded), MaxSQLResultBytes)
+ }
+ // The optional truncation marker is part of the same byte budget. This
+ // value would fit if the builder forgot to count `,"truncated":true`, but
+ // the final JSON would be one byte over the advertised cap.
+ probe, err := json.Marshal(SQLQueryResult{
+ OK: true,
+ Columns: []string{"v"},
+ Rows: [][]any{{""}},
+ Truncated: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ value := strings.Repeat("x", MaxSQLResultBytes-len(probe)+1)
+ overflow := runner.Query(ctx, SQLRequest{
+ SQL: "SELECT ? AS v UNION ALL SELECT 'overflow'",
+ Params: []any{value},
+ MaxRows: 1,
+ })
+ if overflow.Error == "" {
+ encoded, err := json.Marshal(overflow)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Fatalf("truncated result encoded to %d bytes without a limit error", len(encoded))
+ }
+}
+
+func TestSQLRunnerWithoutDatabaseReportsUnavailable(t *testing.T) {
+ var runner SQLRunner
+ ctx := context.Background()
+ if result := runner.Exec(ctx, SQLRequest{SQL: "SELECT 1"}); result.Error == "" || result.OK {
+ t.Fatalf("expected exec to report the store unavailable, got %+v", result)
+ }
+ if result := runner.Query(ctx, SQLRequest{SQL: "SELECT 1"}); result.Error == "" || result.OK {
+ t.Fatalf("expected query to report the store unavailable, got %+v", result)
+ }
+}
+
+func seed(t *testing.T, runner SQLRunner, rows int) {
+ t.Helper()
+ ctx := context.Background()
+ if result := runner.Exec(ctx, SQLRequest{SQL: "CREATE TABLE t (n INTEGER)"}); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+ statement := fmt.Sprintf("WITH RECURSIVE c(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM c WHERE i < %d) INSERT INTO t SELECT i FROM c", rows-1)
+ if result := runner.Exec(ctx, SQLRequest{SQL: statement}); result.Error != "" {
+ t.Fatal(result.Error)
+ }
+}
diff --git a/web/components/admin/plugins/permissionDescriptions.ts b/web/components/admin/plugins/permissionDescriptions.ts
index 22d46a5e43..e1ca802174 100644
--- a/web/components/admin/plugins/permissionDescriptions.ts
+++ b/web/components/admin/plugins/permissionDescriptions.ts
@@ -11,6 +11,7 @@ export const permissionDescriptionKey: Record<string, string> = {
[PluginPermission.StorageKV]: Localization.Admin.Plugins.Permissions.storageKv,
[PluginPermission.StorageUpload]: Localization.Admin.Plugins.Permissions.storageUpload,
[PluginPermission.StorageFS]: Localization.Admin.Plugins.Permissions.storageFs,
+ [PluginPermission.StorageSQL]: Localization.Admin.Plugins.Permissions.storageSql,
[PluginPermission.ChatSend]: Localization.Admin.Plugins.Permissions.chatSend,
[PluginPermission.ChatHistory]: Localization.Admin.Plugins.Permissions.chatHistory,
[PluginPermission.ChatModerate]: Localization.Admin.Plugins.Permissions.chatModerate,
@@ -40,6 +41,7 @@ export const permissionNameKey: Record<string, string> = {
[PluginPermission.StorageKV]: Localization.Admin.Plugins.PermissionNames.storageKv,
[PluginPermission.StorageUpload]: Localization.Admin.Plugins.PermissionNames.storageUpload,
[PluginPermission.StorageFS]: Localization.Admin.Plugins.PermissionNames.storageFs,
+ [PluginPermission.StorageSQL]: Localization.Admin.Plugins.PermissionNames.storageSql,
[PluginPermission.ChatSend]: Localization.Admin.Plugins.PermissionNames.chatSend,
[PluginPermission.ChatHistory]: Localization.Admin.Plugins.PermissionNames.chatHistory,
[PluginPermission.ChatModerate]: Localization.Admin.Plugins.PermissionNames.chatModerate,
diff --git a/web/i18n/en/translation.json b/web/i18n/en/translation.json
index ac50c8a528..ce697a4f1e 100644
--- a/web/i18n/en/translation.json
+++ b/web/i18n/en/translation.json
@@ -221,6 +221,7 @@
"serverRead": "Read server state",
"storageFs": "Read and write files",
"storageKv": "Store data",
+ "storageSql": "SQL database",
"storageUpload": "Upload files",
"uiModify": "Add UI elements",
"usersModerate": "Moderate users",
@@ -245,6 +246,7 @@
"serverRead": "Read Owncast configuration and current server state.",
"storageFs": "Read and write files in a private, server-side directory only this plugin can access.",
"storageKv": "Read and write a per-plugin key-value store that persists across reloads.",
+ "storageSql": "Read and write a private per-plugin SQLite database with bounded size and results. It is not included in Owncast backups.",
"storageUpload": "Upload files to Owncast’s public files area for browser-accessible URLs.",
"uiModify": "Make changes to the Owncast user interface.",
"usersModerate": "Disable or re-enable chat users.",
diff --git a/web/interfaces/plugin.ts b/web/interfaces/plugin.ts
index e230ac4b93..265c52e841 100644
--- a/web/interfaces/plugin.ts
+++ b/web/interfaces/plugin.ts
@@ -10,6 +10,7 @@ export const PluginPermission = {
StorageKV: 'storage.kv',
StorageUpload: 'storage.upload',
StorageFS: 'storage.fs',
+ StorageSQL: 'storage.sql',
ChatSend: 'chat.send',
ChatHistory: 'chat.history',
ChatModerate: 'chat.moderate',
diff --git a/web/types/localization.ts b/web/types/localization.ts
index cb806aae30..48bb67fcd9 100644
--- a/web/types/localization.ts
+++ b/web/types/localization.ts
@@ -581,6 +581,7 @@ export const Localization = {
storageKv: 'Admin.Plugins.Permissions.storageKv',
storageUpload: 'Admin.Plugins.Permissions.storageUpload',
storageFs: 'Admin.Plugins.Permissions.storageFs',
+ storageSql: 'Admin.Plugins.Permissions.storageSql',
chatSend: 'Admin.Plugins.Permissions.chatSend',
chatHistory: 'Admin.Plugins.Permissions.chatHistory',
chatModerate: 'Admin.Plugins.Permissions.chatModerate',
@@ -608,6 +609,7 @@ export const Localization = {
storageKv: 'Admin.Plugins.PermissionNames.storageKv',
storageUpload: 'Admin.Plugins.PermissionNames.storageUpload',
storageFs: 'Admin.Plugins.PermissionNames.storageFs',
+ storageSql: 'Admin.Plugins.PermissionNames.storageSql',
chatSend: 'Admin.Plugins.PermissionNames.chatSend',
chatHistory: 'Admin.Plugins.PermissionNames.chatHistory',
chatModerate: 'Admin.Plugins.PermissionNames.chatModerate',