You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by mi...@apache.org on 2026/07/21 19:24:03 UTC
(superset) branch master updated: feat(extensions): add a Storage API for extensions (#39171)
This is an automated email from the ASF dual-hosted git repository.
michael-s-molina pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 34ebe3d22ad feat(extensions): add a Storage API for extensions (#39171)
34ebe3d22ad is described below
commit 34ebe3d22ad71f475824d9b3e7046f316af8226c
Author: Michael S. Molina <70...@users.noreply.github.com>
AuthorDate: Tue Jul 21 16:23:56 2026 -0300
feat(extensions): add a Storage API for extensions (#39171)
Co-authored-by: Claude Opus 4.6 <no...@anthropic.com>
Co-authored-by: Evan Rusackas <ev...@preset.io>
Co-authored-by: Amin Ghadersohi <am...@gmail.com>
Co-authored-by: Benyovszky Máté <be...@outlook.com>
Co-authored-by: Cursor <cu...@cursor.com>
---
docs/developer_docs/extensions/architecture.md | 36 +-
docs/developer_docs/extensions/overview.md | 21 +-
docs/developer_docs/extensions/quick-start.md | 13 +-
docs/developer_docs/extensions/storage.md | 465 ++++++++
docs/sidebarTutorials.js | 2 +
.../src/superset_core/extensions/context.py | 119 ++
.../superset_core/extensions/storage/__init__.py | 79 ++
.../src/superset_core/extensions/storage/dao.py | 70 ++
.../superset_core/extensions/storage/ephemeral.py | 162 +++
.../src/superset_core/extensions/storage/models.py | 74 ++
.../superset_core/extensions/storage/persistent.py | 243 +++++
.../src/superset_core/extensions/types.py | 12 +-
.../src/superset_extensions_cli/cli.py | 4 -
.../templates/frontend/webpack.config.js.j2 | 8 +-
superset-frontend/packages/superset-core/README.md | 1 +
.../packages/superset-core/package.json | 4 +
.../packages/superset-core/src/common/index.ts | 2 -
.../packages/superset-core/src/extensions/index.ts | 71 ++
.../packages/superset-core/src/index.ts | 1 +
.../packages/superset-core/src/storage/index.ts | 218 ++++
.../src/components/PanelToolbar/index.tsx | 2 +-
.../core/extensions/{index.ts => index.test.ts} | 17 +-
superset-frontend/src/core/extensions/index.ts | 12 +-
superset-frontend/src/core/index.ts | 1 +
.../src/core/storage/binaryCodec.test.ts | 109 ++
superset-frontend/src/core/storage/binaryCodec.ts | 65 ++
.../src/core/storage/ephemeralState.test.ts | 170 +++
.../src/core/storage/ephemeralState.ts | 100 ++
.../src/core/{extensions => storage}/index.ts | 18 +-
.../src/core/storage/localState.test.ts | 96 ++
superset-frontend/src/core/storage/localState.ts | 67 ++
.../src/core/storage/persistentState.test.ts | 261 +++++
.../src/core/storage/persistentState.ts | 143 +++
.../src/extensions/ExtensionContext.test.ts | 60 +
.../src/extensions/ExtensionContext.ts | 78 ++
.../src/extensions/ExtensionsLoader.test.ts | 267 ++++-
.../src/extensions/ExtensionsLoader.ts | 123 ++-
.../src/extensions/webpackFederation.d.ts | 63 ++
superset-frontend/webpack.config.js | 4 +
superset/config.py | 36 +
superset/core/api/core_api_injection.py | 56 +-
superset/core/mcp/core_mcp_injection.py | 6 +-
superset/extensions/context.py | 136 ++-
superset/extensions/storage/__init__.py | 28 +
superset/extensions/storage/api.py | 744 +++++++++++++
superset/extensions/storage/codecs.py | 68 ++
superset/extensions/storage/ephemeral.py | 141 +++
superset/extensions/storage/ephemeral_dao.py | 161 +++
superset/extensions/storage/filters.py | 45 +
superset/extensions/storage/persistent.py | 244 +++++
superset/extensions/storage/persistent_dao.py | 655 +++++++++++
superset/extensions/storage/persistent_model.py | 139 +++
superset/extensions/storage/utils.py | 112 ++
superset/initialization/__init__.py | 2 +
superset/key_value/types.py | 17 +
...-00_e5f6a7b8c9d0_add_extension_storage_table.py | 109 ++
superset/tasks/decorators.py | 4 +-
superset/utils/cache_manager.py | 28 +-
superset/utils/encrypt.py | 87 ++
tests/unit_tests/extensions/storage/__init__.py | 16 +
tests/unit_tests/extensions/storage/conftest.py | 64 ++
tests/unit_tests/extensions/storage/test_api.py | 1146 ++++++++++++++++++++
tests/unit_tests/extensions/storage/test_codecs.py | 94 ++
.../unit_tests/extensions/storage/test_context.py | 124 +++
.../extensions/storage/test_ephemeral.py | 276 +++++
.../extensions/storage/test_ephemeral_dao.py | 323 ++++++
.../unit_tests/extensions/storage/test_filters.py | 78 ++
.../extensions/storage/test_persistent.py | 318 ++++++
.../extensions/storage/test_persistent_dao.py | 957 ++++++++++++++++
tests/unit_tests/extensions/storage/test_utils.py | 219 ++++
tests/unit_tests/key_value/codec_test.py | 14 +
.../unit_tests/semantic_layers/decorators_test.py | 4 +-
72 files changed, 9551 insertions(+), 161 deletions(-)
diff --git a/docs/developer_docs/extensions/architecture.md b/docs/developer_docs/extensions/architecture.md
index 4a445703129..d665f436332 100644
--- a/docs/developer_docs/extensions/architecture.md
+++ b/docs/developer_docs/extensions/architecture.md
@@ -163,10 +163,6 @@ The architecture leverages Webpack's Module Federation to enable dynamic loading
Extensions configure Webpack to expose their entry points:
```javascript
-externalsType: 'window',
-externals: {
- '@apache-superset/core': 'superset',
-},
plugins: [
new ModuleFederationPlugin({
name: 'my_extension',
@@ -178,6 +174,7 @@ plugins: [
react: { singleton: true, import: false },
'react-dom': { singleton: true, import: false },
antd: { singleton: true, import: false },
+ '@apache-superset/core': { singleton: true, import: false },
},
}),
]
@@ -187,9 +184,7 @@ This configuration does several important things:
**`exposes`** - Declares which modules are available to the host application. Superset always loads extensions by requesting the `./index` module from the remote container — this is a fixed convention, not a configurable value. Extensions must expose exactly `'./index': './src/index.tsx'` and place all API registrations (views, commands, menus, editors, event listeners) in that file. The module is executed as a side effect when the extension loads, so any call to `views.registerView`, `c [...]
-**`externals` and `externalsType`** - Tell Webpack that when the extension imports `@apache-superset/core`, it should use `window.superset` at runtime instead of bundling its own copy. This ensures extensions use the host's implementation of shared packages.
-
-**`shared`** - Prevents duplication of common libraries like React and Ant Design. The `singleton: true` setting ensures only one instance of each library exists, avoiding version conflicts and reducing bundle size.
+**`shared`** - Prevents duplication of common libraries like React and Ant Design, and, for `@apache-superset/core`, is the mechanism that gives each extension an isolated context (see below). The `singleton: true` setting ensures only one *logical* instance of each library exists — for `react`/`react-dom`/`antd` that means the host's actual instance is reused; for `@apache-superset/core` it means the extension's container defers to whatever module the host's loader supplies for it at in [...]
### Runtime Resolution
@@ -200,25 +195,30 @@ The following diagram illustrates the module loading process:
Here's what happens at runtime:
1. **Extension Registration**: When an extension is registered, Superset stores its remote entry URL
-2. **Dynamic Loading**: When the extension is activated, the host fetches the remote entry file
-3. **Module Resolution**: The extension imports `@apache-superset/core`, which resolves to `window.superset`
-4. **Execution**: The extension code runs with access to the host's APIs and shared dependencies
+2. **Dynamic Loading**: When the extension is activated, the host fetches the remote entry file, then initializes Module Federation sharing (`__webpack_init_sharing__`) and looks up the extension's container on `window`
+3. **Per-Extension Scope Injection**: Before calling `container.init()`, the loader builds a **per-container copy** of the webpack share scope in which the `@apache-superset/core` entry is replaced with a synthetic module — a copy of the host's own `window.superset` implementations with `extensions.getContext` bound to that one extension's isolated context object. Because Module Federation caches the resolved module per container, every import of `@apache-superset/core` inside that exten [...]
+4. **Execution**: The extension code runs with access to the host's APIs (via its per-extension `@apache-superset/core` instance) and shared dependencies (`react`, `react-dom`, `antd`)
### Host API Setup
-On the Superset side, the APIs are mapped to `window.superset` during application bootstrap:
+On the Superset side, the real implementations backing `@apache-superset/core` (`commands`, `views`, `menus`, `extensions`, etc.) are assigned onto `window.superset` during application bootstrap, once the current user is known:
```typescript
+// eslint-disable-next-line no-restricted-syntax
import * as supersetCore from '@apache-superset/core';
-
-export default function setupExtensionsAPI() {
- window.superset = {
- ...supersetCore,
- };
-}
+import { commands, views, menus, extensions /* ... */ } from 'src/core';
+
+window.superset = {
+ ...supersetCore,
+ commands,
+ views,
+ menus,
+ extensions,
+ // ...
+};
```
-This function runs before any extensions are loaded, ensuring the APIs are available when extensions import from `@apache-superset/core`.
+This runs before any extensions are loaded. `window.superset` is not itself what an extension's `@apache-superset/core` import resolves to — it is the source object the loader reads from when building each extension's per-container scoped instance (see [Runtime Resolution](#runtime-resolution)), so every extension ends up sharing the same underlying `commands`/`views`/`menus` singletons but with its own `extensions.getContext()`.
### Benefits
diff --git a/docs/developer_docs/extensions/overview.md b/docs/developer_docs/extensions/overview.md
index faee8c4c487..08e4be75d44 100644
--- a/docs/developer_docs/extensions/overview.md
+++ b/docs/developer_docs/extensions/overview.md
@@ -47,13 +47,14 @@ Extension developers have access to pre-built UI components via `@apache-superse
## Next Steps
-- **[Quick Start](./quick-start.md)** - Build your first extension with a complete walkthrough
-- **[Architecture](./architecture.md)** - Design principles and system overview
-- **[Dependencies](./dependencies.md)** - Managing dependencies and understanding API stability
-- **[Contribution Types](./contribution-types.md)** - Available extension points
-- **[Development](./development.md)** - Project structure, APIs, and development workflow
-- **[Deployment](./deployment.md)** - Packaging and deploying extensions
-- **[MCP Integration](./mcp.md)** - Adding AI agent capabilities using extensions
-- **[Security](./security.md)** - Security considerations and best practices
-- **[Tasks](./tasks.md)** - Framework for creating and managing long running tasks
-- **[Community Extensions](./registry.md)** - Browse extensions shared by the community
+- **[Quick Start](./quick-start)** - Build your first extension with a complete walkthrough
+- **[Architecture](./architecture)** - Design principles and system overview
+- **[Dependencies](./dependencies)** - Managing dependencies and understanding API stability
+- **[Contribution Types](./contribution-types)** - Available extension points
+- **[Development](./development)** - Project structure, APIs, and development workflow
+- **[Deployment](./deployment)** - Packaging and deploying extensions
+- **[MCP Integration](./mcp)** - Adding AI agent capabilities using extensions
+- **[Security](./security)** - Security considerations and best practices
+- **[Storage](./storage)** - Managed storage API for persisting extension data
+- **[Tasks](./tasks)** - Framework for creating and managing long running tasks
+- **[Community Extensions](./registry)** - Browse extensions shared by the community
diff --git a/docs/developer_docs/extensions/quick-start.md b/docs/developer_docs/extensions/quick-start.md
index 1ef35833397..4febd894be8 100644
--- a/docs/developer_docs/extensions/quick-start.md
+++ b/docs/developer_docs/extensions/quick-start.md
@@ -223,7 +223,7 @@ The `@apache-superset/core` package must be listed in both `peerDependencies` (t
**`frontend/webpack.config.js`**
-The webpack configuration requires specific settings for Module Federation. Key settings include `externalsType: "window"` and `externals` to map `@apache-superset/core` to `window.superset` at runtime, `import: false` for shared modules to use the host's React instead of bundling a separate copy, and `remoteEntry.[contenthash].js` for cache busting.
+The webpack configuration requires specific settings for Module Federation. `@apache-superset/core` is declared as a `shared` singleton alongside `react`/`react-dom`/`antd` — Superset injects a per-extension instance of the package into the container's share scope at load time, so the extension's own webpack config only needs to mark it `shared` with `singleton: true`, not resolve it itself. `import: false` on each shared entry means the extension doesn't bundle its own copy and instead [...]
**Convention**: Superset always loads extensions by requesting the `./index` module from the Module Federation container. The `exposes` entry must be exactly `'./index': './src/index.tsx'` — do not rename or add additional entries. All API registrations must be reachable from that file. See [Architecture](./architecture.md#module-federation) for a full explanation.
@@ -255,11 +255,6 @@ module.exports = (env, argv) => {
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
- // Map @apache-superset/core imports to window.superset at runtime
- externalsType: 'window',
- externals: {
- '@apache-superset/core': 'superset',
- },
module: {
rules: [
{
@@ -292,6 +287,10 @@ module.exports = (env, argv) => {
requiredVersion: packageConfig.peerDependencies['antd'],
import: false,
},
+ '@apache-superset/core': {
+ singleton: true,
+ import: false, // Resolved to a per-extension instance by the loader
+ },
},
}),
],
@@ -498,7 +497,7 @@ Here's what happens when your extension loads:
1. **Superset starts**: Reads `manifest.json` from the `.supx` bundle and loads the backend entrypoint
2. **Backend registration**: `entrypoint.py` imports your API class, triggering the [`@api`](https://github.com/apache/superset/blob/master/superset-core/src/superset_core/rest_api/decorators.py) decorator to register it automatically
3. **Frontend loads**: When SQL Lab opens, Superset fetches the remote entry file
-4. **Module Federation**: Webpack loads your extension module and resolves `@apache-superset/core` to `window.superset`
+4. **Module Federation**: Webpack loads your extension module; the extension's `@apache-superset/core` import resolves to a per-extension instance injected into its container's share scope by the loader
5. **Registration**: The module executes at load time, calling `views.registerView` to register your panel
6. **Rendering**: When the user opens your panel, React renders `<HelloWorldPanel />`
7. **API call**: The component fetches data from `/extensions/my-org/hello-world/message`
diff --git a/docs/developer_docs/extensions/storage.md b/docs/developer_docs/extensions/storage.md
new file mode 100644
index 00000000000..fdd70160c4d
--- /dev/null
+++ b/docs/developer_docs/extensions/storage.md
@@ -0,0 +1,465 @@
+---
+title: Storage
+sidebar_position: 8
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+# Storage
+
+Superset Extensions have access to a managed storage API for persisting data. The storage system provides multiple tiers with different persistence characteristics, allowing extensions to choose the right storage for their needs.
+
+Each extension receives its own isolated storage namespace. When Superset loads your extension, it binds storage to your extension's unique identifier, ensuring data privacy—two extensions using the same key will never collide, and extensions cannot access each other's data.
+
+Storage is always accessed through the extension context via `getContext()`. This binding to the context is what ties every operation to the current extension's namespace.
+
+## Storage Tiers
+
+| Tier | Storage Type | Context Property | Use Case |
+| ---- | ----------------- | ------------------------------------------ | -------------------------------------- |
+| 1 | Browser storage | `ctx.storage.local`, `ctx.storage.session` | UI state, wizard progress, draft forms |
+| 2 | Server-side cache | `ctx.storage.ephemeral` | Job progress, temporary results |
+| 3 | Database | `ctx.storage.persistent` | Saved artifacts, durable config |
+
+## Tier 1: Local State
+
+Browser-based storage that persists on the user's device. Use this for UI state and settings that don't need to sync across devices.
+
+### Why Use the API Instead of localStorage Directly?
+
+You might wonder why extensions should use `ctx.storage.local` instead of directly accessing `window.localStorage`. The managed API provides several benefits:
+
+- **Automatic namespacing**: Each extension's data is isolated. Two extensions using the same key name won't collide.
+- **User isolation**: By default, data is scoped to the current user, preventing data leakage between users on shared devices.
+- **Clean uninstall**: When an extension is uninstalled, all its data can be cleanly removed using prefix-based deletion.
+- **Future sandboxing**: The async API is designed for a future sandboxed execution model where extensions run in isolated contexts without direct DOM access.
+- **Consistent patterns**: The same API shape works across all storage tiers, making it easy to switch between them.
+
+### localState
+
+Data persists across browser sessions until explicitly deleted or the user clears browser storage.
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+// Save sidebar state
+await ctx.storage.local.set('sidebar_collapsed', true);
+
+// Retrieve it later
+const isCollapsed = await ctx.storage.local.get('sidebar_collapsed');
+
+// Remove it
+await ctx.storage.local.remove('sidebar_collapsed');
+```
+
+### sessionState
+
+Data is cleared when the browser tab is closed. Use for transient state within a single session.
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+// Save wizard progress (lost when tab closes)
+await ctx.storage.session.set('wizard_step', 3);
+await ctx.storage.session.set('unsaved_form', { name: 'Draft' });
+
+// Retrieve on page reload within same tab
+const step = await ctx.storage.session.get('wizard_step');
+```
+
+Tier 1 has no `shared` accessor. Browser storage is per-device, so a "shared" value would only be visible to other users of that same browser, not to other users of the extension generally — see `.shared` on [Tier 2](#tier-2-ephemeral-state) or [Tier 3](#tier-3-persistent-state) for storage that's actually shared across users.
+
+### When to Use Tier 1
+
+- UI state (sidebar collapsed, panel sizes)
+- Recently used items
+- Draft form values
+- Any data acceptable to lose if user clears browser
+
+### Limitations
+
+- Per-browser, per-device (not shared across devices)
+- Subject to browser storage quotas (~5-10 MB)
+- Not accessible from backend code
+
+## Tier 2: Ephemeral State
+
+Server-side cache storage with automatic TTL expiration. Use for temporary data that needs to be shared between frontend and backend, or persist across page reloads.
+
+TTL is required for every `set` call. The maximum allowed TTL is controlled by `MAX_TTL` in the server configuration.
+
+### Frontend Usage
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+// Store with a 5-minute TTL
+await ctx.storage.ephemeral.set('job_progress', { pct: 42, status: 'running' }, { ttl: 300 });
+
+// Retrieve
+const progress = await ctx.storage.ephemeral.get('job_progress');
+
+// Remove
+await ctx.storage.ephemeral.remove('job_progress');
+```
+
+### Backend Usage
+
+```python
+from superset_core.extensions.context import get_context
+from superset_core.extensions.storage.ephemeral import EphemeralSetOptions
+
+ctx = get_context()
+
+# Store job progress with a 5-minute TTL
+ctx.storage.ephemeral.set(
+ 'job_progress', {'pct': 42, 'status': 'running'}, EphemeralSetOptions(ttl=300)
+)
+
+# Retrieve
+progress = ctx.storage.ephemeral.get('job_progress')
+
+# Remove
+ctx.storage.ephemeral.remove('job_progress')
+```
+
+### Shared State
+
+For data that needs to be visible to all users:
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+await ctx.storage.ephemeral.shared.set('shared_result', { data: [1, 2, 3] }, { ttl: 3600 });
+const result = await ctx.storage.ephemeral.shared.get('shared_result');
+```
+
+```python
+from superset_core.extensions.context import get_context
+from superset_core.extensions.storage.ephemeral import EphemeralSetOptions
+
+ctx = get_context()
+
+ctx.storage.ephemeral.shared.set(
+ 'shared_result', {'data': [1, 2, 3]}, EphemeralSetOptions(ttl=3600)
+)
+result = ctx.storage.ephemeral.shared.get('shared_result')
+```
+
+### When to Use Tier 2
+
+- Background job progress indicators
+- Cross-request intermediate state
+- Query result previews
+- Temporary computation results
+- Any data that can be recomputed if lost
+
+### Limitations
+
+- Not guaranteed to survive server restarts
+- Subject to cache eviction under memory pressure
+- TTL-based expiration (data disappears after timeout)
+- TTL is required on every `set` call
+
+## Tier 3: Persistent State
+
+Database-backed storage that survives server restarts, cache evictions, and browser clears. Use for any data that must not be lost.
+
+### Frontend Usage
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+// Store a saved SQL snippet
+await ctx.storage.persistent.set('snippet:top_customers', { sql: 'SELECT ...' });
+
+// Retrieve
+const snippet = await ctx.storage.persistent.get('snippet:top_customers');
+
+// Remove
+await ctx.storage.persistent.remove('snippet:top_customers');
+```
+
+### Backend Usage
+
+```python
+from superset_core.extensions.context import get_context
+
+ctx = get_context()
+
+# Store a saved SQL snippet
+ctx.storage.persistent.set('snippet:top_customers', {'sql': 'SELECT ...'})
+
+# Retrieve
+snippet = ctx.storage.persistent.get('snippet:top_customers')
+
+# Remove
+ctx.storage.persistent.remove('snippet:top_customers')
+```
+
+### Shared State
+
+For data that should be visible to all users of the extension:
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+await ctx.storage.persistent.shared.set('global_config', { version: 2 });
+const config = await ctx.storage.persistent.shared.get('global_config');
+```
+
+```python
+from superset_core.extensions.context import get_context
+
+ctx = get_context()
+
+ctx.storage.persistent.shared.set('global_config', {'version': 2})
+config = ctx.storage.persistent.shared.get('global_config')
+```
+
+### Listing Entries
+
+Both the frontend and backend accessors support listing entries in the caller's scope, without needing to know every key in advance. `page` and `pageSize`/`page_size` are required on every call — `list()` always returns one page of results, never the whole result set, so there's no default that could make that fact easy to miss. Check the returned `count` (total entries matching the scope/filters, across all pages) against `pageSize`/`page_size` to know whether more pages exist.
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+// Filter by resource
+const result = await ctx.storage.persistent.list({
+ resourceType: 'dashboard',
+ resourceUuid: '1234-uuid',
+ page: 0,
+ pageSize: 25,
+});
+result.entries.forEach(entry => {
+ console.log(entry.key, entry.value, entry.codec);
+});
+console.log(result.count); // total matching entries across all pages
+
+// Shared (global) scope
+const shared = await ctx.storage.persistent.shared.list({ page: 0, pageSize: 10 });
+```
+
+```python
+from superset_core.extensions.context import get_context
+from superset_core.extensions.storage.persistent import PersistentListOptions
+
+ctx = get_context()
+
+# Filter by resource
+result = ctx.storage.persistent.list(
+ PersistentListOptions(
+ resource_type="dashboard",
+ resource_uuid="1234-uuid",
+ page=0,
+ page_size=25,
+ )
+)
+for entry in result.entries:
+ print(entry.key, entry.value, entry.codec)
+print(result.count) # total matching entries across all pages
+
+# Shared (global) scope
+shared = ctx.storage.persistent.shared.list(PersistentListOptions(page=0, page_size=10))
+```
+
+`resource_type`/`resource_uuid` filter to entries linked to one resource — since a single resource can have several keyed entries (e.g. `"layout"`, `"notes"`), this is how an extension enumerates all of them without tracking key names itself.
+
+There is no fixed limit on `page_size`, but the combined size of a requested page's values is checked against `MAX_LIST_PAYLOAD_SIZE` (see [Quotas](#quotas)) before any row's value is read from the database — a page that would exceed it is rejected rather than silently truncated, so reduce `page_size` and retry if that happens.
+
+Backend `list()` decodes every entry's value unconditionally. The REST API backing the frontend's `list()` call is more restrictive: an entry written with a codec that isn't safe to decode over the wire (e.g. `pickle`) comes back with `value: null` (its `codec` is still reported) rather than being decoded.
+
+### Enumerating and Managing Storage from the Backend
+
+`ctx.storage.persistent.list()` covers the common case of listing an extension's own entries. Backend extension code that needs lower-level bulk operations — for example, a cleanup routine that removes storage linked to resources that no longer exist, using filters `list()` doesn't expose — can use `superset_core.extensions.storage.dao.ExtensionStorageDAO` instead:
+
+```python
+from superset_core.extensions.storage.dao import ExtensionStorageDAO
+
+# All entries this extension has linked to a given resource type
+entries = ExtensionStorageDAO.filter_by(resource_type="my-resource-type")
+
+# Bulk-delete rows for resources that no longer exist
+orphaned = [e for e in entries if e.resource_uuid not in my_extension_live_resource_ids()]
+ExtensionStorageDAO.delete(orphaned)
+```
+
+`ExtensionStorageDAO` is automatically scoped to the calling extension's own rows — `extension_id` is never a parameter you pass, so there is no way to reach another extension's storage through this API. It supports the standard DAO operations `find_all`, `find_one_or_none`, `filter_by`, `query`, `update`, and `delete`. `create()` is not supported — it's a raw insert with no upsert dedup, quota check, or locking against the key `.set()` writes to, so use `ctx.storage.persistent.set()` to [...]
+
+### When to Use Tier 3
+
+- Extension configuration that must survive restarts
+- User-specific saved artifacts that need to roam across devices and browsers (e.g. saved SQL snippets, annotations)
+- Any data where loss is unacceptable
+
+### Limitations
+
+- Higher latency than Tiers 1–2 (database round-trip per operation)
+- Subject to the per-value size limit configured via `EXTENSIONS_PERSISTENT_STORAGE.MAX_VALUE_SIZE` (see [Quotas](#quotas))
+- Subject to the per-extension quota configured via `EXTENSIONS_PERSISTENT_STORAGE.QUOTA_PER_EXTENSION` (see [Quotas](#quotas))
+- Requires a database migration when first deployed
+
+## Working with Binary Data
+
+Tiers 2 and 3 accept a `codec` option describing how `value` is encoded — `"json"` (the default) for JSON-native values, or `"binary"` for raw bytes. `list()` and `get()` report which codec an entry was written with via `entry.codec`.
+
+### Backend
+
+Backend code talks to the storage DAO directly and works with real Python `bytes` — no extra flag is needed:
+
+```python
+from superset_core.extensions.context import get_context
+from superset_core.extensions.storage.persistent import PersistentSetOptions
+
+ctx = get_context()
+
+with open('logo.png', 'rb') as f:
+ png_bytes = f.read()
+
+ctx.storage.persistent.set('logo', png_bytes, PersistentSetOptions(codec='binary'))
+
+stored = ctx.storage.persistent.get('logo') # raw bytes back, unchanged
+```
+
+### Frontend
+
+The frontend SDK talks to the backend over a JSON REST API, which has no byte type — a binary value must be base64-encoded to travel in a JSON request body. There is no way for the SDK to infer this from a JS value's type, so it is never detected automatically: set `isBinary: true` explicitly whenever `value` is binary.
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+const pngBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47 /* ... */]);
+await ctx.storage.persistent.set('logo', pngBytes, { isBinary: true });
+```
+
+`get()` returns a binary entry's value exactly as stored on the wire — a base64 string, not a `Uint8Array` — so decode it yourself:
+
+```typescript
+const base64 = await ctx.storage.persistent.get<string>('logo');
+const bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
+```
+
+`list()` entries report `isBinary` alongside `codec`, so you know which entries need decoding before you read `value`:
+
+```typescript
+const result = await ctx.storage.persistent.list({ page: 0, pageSize: 10 });
+result.entries.forEach(entry => {
+ const value = entry.isBinary
+ ? Uint8Array.from(atob(entry.value as string), c => c.charCodeAt(0))
+ : entry.value;
+});
+```
+
+## Key Patterns
+
+All storage keys are automatically namespaced:
+
+| Scope | Key Pattern |
+| ---------------------- | -------------------------------------------------- |
+| User-scoped | `superset-ext:{extension_id}:user:{user_id}:{key}` |
+| Shared (Tiers 2 and 3) | `superset-ext:{extension_id}:shared:{key}` |
+
+This ensures:
+
+- Extensions cannot accidentally access each other's data
+- Users cannot see other users' data (by default)
+- Clean prefix-based deletion on uninstall
+
+## Configuration
+
+### Tier 2: Ephemeral Storage
+
+Administrators can configure the server-side cache backend in `superset_config.py`:
+
+```python
+EXTENSIONS_EPHEMERAL_STORAGE = {
+ # Use Redis for better performance in production
+ "CACHE_TYPE": "RedisCache",
+ "CACHE_REDIS_URL": "redis://localhost:6379/2",
+ "MAX_TTL": 604800, # 7 days maximum TTL
+ "MAX_VALUE_SIZE": 100 * 1024, # 100 KB maximum per stored value
+}
+```
+
+For development, the default `SupersetMetastoreCache` stores data in the metadata database.
+
+### Tier 3: Persistent Storage
+
+Tier 3 values are stored in the `extension_storage` database table. Values are stored unencrypted by default; encryption is opt-in per write, available via a `PersistentSetOptions`-shaped `encrypt` option:
+
+```typescript
+import { extensions } from '@apache-superset/core';
+
+const ctx = extensions.getContext();
+
+await ctx.storage.persistent.set('api_token', 'sk-...', { encrypt: true });
+const token = await ctx.storage.persistent.get('api_token');
+```
+
+```python
+from superset_core.extensions.context import get_context
+from superset_core.extensions.storage.persistent import PersistentSetOptions
+
+ctx = get_context()
+
+ctx.storage.persistent.set('api_token', 'sk-...', PersistentSetOptions(encrypt=True))
+token = ctx.storage.persistent.get('api_token')
+```
+
+Encryption reuses Superset's existing `EncryptedType` (from `sqlalchemy-utils`) rather than a separate mechanism — the same infrastructure used for database connection credentials. The key is not configured directly: user-scoped values are encrypted with a key derived per-user via HMAC-SHA256 from the deployment's `SECRET_KEY`, so ciphertext for one user cannot be decrypted as another's; shared/global values (written via `.shared`) use `SECRET_KEY` directly. The encryption engine (AES-CB [...]
+
+### Quotas
+
+Persistent storage is subject to per-value, per-list-page, and per-extension size limits, configured in `superset_config.py`:
+
+```python
+EXTENSIONS_PERSISTENT_STORAGE = {
+ # Maximum total bytes an extension may store across all of its rows
+ # (global, every user's, and shared). Defaults to 100 MB.
+ "QUOTA_PER_EXTENSION": 100 * 1024 * 1024,
+ # Maximum size (in bytes) of a single stored value. Defaults to 1 MB.
+ "MAX_VALUE_SIZE": 1024 * 1024,
+ # Maximum combined value size (in bytes) that a single list() page may
+ # return. Defaults to 10 MB.
+ "MAX_LIST_PAYLOAD_SIZE": 10 * 1024 * 1024,
+}
+```
+
+A write that would push the extension's total stored size over `QUOTA_PER_EXTENSION` is rejected — the frontend SDK's `set()` call rejects with an HTTP 413 response, and backend code calling `ctx.storage.persistent.set()` sees the corresponding exception raised. Overwriting an existing key nets out that key's own current size against usage first, so replacing a value with one of the same or smaller size never spuriously fails even when the extension is already near its quota.
+
+A write whose encoded value exceeds `MAX_VALUE_SIZE` is rejected outright, independently of the total quota.
+
+A `list()` call whose requested page would return more than `MAX_LIST_PAYLOAD_SIZE` combined bytes of value data is rejected — reduce `page`/`pageSize` and retry. This check runs against the page's stored sizes before any value is read from the database, so an oversized request fails fast. Because `list()`'s response is consumed as JSON in the browser, raising `MAX_LIST_PAYLOAD_SIZE` substantially above the default risks client-side memory and parse-time issues — treat the default as alr [...]
diff --git a/docs/sidebarTutorials.js b/docs/sidebarTutorials.js
index 807b1976091..de50d00c7c6 100644
--- a/docs/sidebarTutorials.js
+++ b/docs/sidebarTutorials.js
@@ -82,12 +82,14 @@ const sidebars = {
items: [
'extensions/extension-points/sqllab',
'extensions/extension-points/editors',
+ 'extensions/extension-points/chat',
],
},
'extensions/development',
'extensions/deployment',
'extensions/mcp',
'extensions/security',
+ 'extensions/storage',
'extensions/tasks',
'extensions/registry',
],
diff --git a/superset-core/src/superset_core/extensions/context.py b/superset-core/src/superset_core/extensions/context.py
new file mode 100644
index 00000000000..63c8ea35e78
--- /dev/null
+++ b/superset-core/src/superset_core/extensions/context.py
@@ -0,0 +1,119 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Extension Context API for superset-core extensions.
+
+Provides access to the current extension's context, including metadata
+and scoped resources like storage. Extensions call `get_context()` to
+access their context during execution.
+
+The context is set by the host (Superset) during extension loading and
+is only available within extension code.
+
+Usage:
+ from superset_core.extensions.context import get_context
+
+ def setup():
+ ctx = get_context()
+
+ # Access extension metadata
+ print(f"Running {ctx.extension.displayName} v{ctx.extension.version}")
+
+ # Access extension-scoped storage
+ ctx.storage.ephemeral.set("lastRun", time.time(), EphemeralSetOptions(ttl=3600))
+ data = ctx.storage.ephemeral.get("cachedData")
+"""
+
+from __future__ import annotations
+
+from typing import Protocol, TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from superset_core.extensions.storage.ephemeral import EphemeralStateAccessor
+ from superset_core.extensions.storage.persistent import PersistentStateAccessor
+ from superset_core.extensions.types import BaseExtension
+
+
+class ExtensionStorage(Protocol):
+ """Extension-scoped storage accessor for all available tiers."""
+
+ @property
+ def ephemeral(self) -> "EphemeralStateAccessor":
+ """Server-side cache (Redis/Memcached) with TTL."""
+ ...
+
+ @property
+ def persistent(self) -> "PersistentStateAccessor":
+ """Database-backed persistent storage."""
+ ...
+
+
+class ExtensionContext(Protocol):
+ """
+ Context object providing extension-specific resources.
+
+ This context is only available during extension execution.
+ Calling `get_context()` outside of an extension will raise an error.
+ """
+
+ @property
+ def extension(self) -> "BaseExtension":
+ """Metadata about the current extension."""
+ ...
+
+ @property
+ def storage(self) -> ExtensionStorage:
+ """Extension-scoped storage across all available tiers."""
+ ...
+
+
+def get_context() -> ExtensionContext:
+ """
+ Get the current extension's context.
+
+ This function returns the context for the currently executing extension,
+ providing access to extension metadata and scoped resources like storage.
+
+ Host implementations will replace this function during initialization
+ with a concrete implementation providing actual functionality.
+
+ :returns: The current extension's context.
+ :raises RuntimeError: If called outside of an extension context.
+
+ Example:
+ from superset_core.extensions.context import get_context
+
+ ctx = get_context()
+
+ # Access extension metadata
+ print(f"Extension: {ctx.extension.id}")
+ print(f"Version: {ctx.extension.version}")
+
+ # Access extension-scoped storage
+ ctx.storage.ephemeral.set("tempData", data, EphemeralSetOptions(ttl=3600))
+ value = ctx.storage.ephemeral.get("tempData")
+
+ # Access shared (cross-user) storage
+ ctx.storage.ephemeral.shared.set(
+ "globalCounter", count, EphemeralSetOptions(ttl=3600)
+ )
+ """
+ raise NotImplementedError(
+ "get_context() must be called within an extension context. "
+ "This function is replaced by the host during extension loading."
+ )
diff --git a/superset-core/src/superset_core/extensions/storage/__init__.py b/superset-core/src/superset_core/extensions/storage/__init__.py
new file mode 100644
index 00000000000..095b1b9c9cb
--- /dev/null
+++ b/superset-core/src/superset_core/extensions/storage/__init__.py
@@ -0,0 +1,79 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Storage API for superset-core extensions.
+
+Provides storage tiers for extensions with different persistence characteristics.
+Storage is accessed via `ctx.storage` from `get_context()`.
+
+Tier 1 - Local State (Frontend Only):
+ - local: Browser localStorage - persists across sessions
+ - session: Browser sessionStorage - cleared on tab close
+ These are frontend-only and cannot be imported in backend code.
+
+Tier 2 - Ephemeral State (Server Cache):
+ - ephemeral: Short-lived KV storage backed by server-side cache
+ - Supports TTL, not guaranteed to survive server restarts
+ - Use for temporary state like job progress or intermediate results
+
+Tier 3 - Persistent State (Database):
+ - persistent: Durable KV storage backed by database table
+ - Survives server restarts, supports encryption and resource linking
+ - Use for user preferences, extension config, per-resource settings
+
+All tiers follow the same API pattern:
+ - User-scoped by default (private to current user)
+ - `shared` accessor for data visible to all users
+
+For backend code that needs to query, enumerate, or bulk-manage its own
+Tier 3 rows rather than get/set a single key at a time (for example, a
+cleanup job pruning rows linked to resources that no longer exist), see
+`superset_core.extensions.storage.dao.ExtensionStorageDAO`.
+
+Usage:
+ from superset_core.extensions.context import get_context
+ from superset_core.extensions.storage.ephemeral import EphemeralSetOptions
+
+ ctx = get_context()
+
+ # Tier 2: Ephemeral state
+ ctx.storage.ephemeral.get('preference')
+ ctx.storage.ephemeral.set('preference', 'compact', EphemeralSetOptions(ttl=3600))
+
+ # Tier 2: Shared ephemeral state
+ ctx.storage.ephemeral.shared.get('job_progress')
+ ctx.storage.ephemeral.shared.set(
+ 'job_progress', {'pct': 42}, EphemeralSetOptions(ttl=3600)
+ )
+
+ # Tier 3: Persistent state
+ ctx.storage.persistent.get('config')
+ ctx.storage.persistent.set('config', {'version': 2})
+
+ # Tier 3: DAO-style access to this extension's own rows
+ from superset_core.extensions.storage.dao import ExtensionStorageDAO
+
+ entries = ExtensionStorageDAO.filter_by(resource_type='my-resource-type')
+"""
+
+from superset_core.extensions.storage import (
+ dao, # noqa: F401
+ ephemeral, # noqa: F401
+ models, # noqa: F401
+ persistent, # noqa: F401
+)
diff --git a/superset-core/src/superset_core/extensions/storage/dao.py b/superset-core/src/superset_core/extensions/storage/dao.py
new file mode 100644
index 00000000000..1cd0b9f1253
--- /dev/null
+++ b/superset-core/src/superset_core/extensions/storage/dao.py
@@ -0,0 +1,70 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Persistent storage DAO API for superset-core extensions (Tier 3 Storage).
+
+Provides direct DAO-style access to an extension's own Tier 3 persistent
+storage rows, for backend code that needs to query, enumerate, or bulk-manage
+entries rather than get/set a single key at a time (see
+`superset_core.extensions.storage.persistent` for that simpler shape).
+
+Every query and mutation made through this DAO is automatically scoped to
+the extension currently executing — `extension_id` is never a parameter the
+caller supplies, so an extension cannot read or modify another extension's
+storage through this DAO. The scoping is resolved from the ambient
+extension context (the same context `get_context()` reads from), so this DAO
+can only be used from within extension backend code, not host code.
+
+Usage:
+ from superset_core.extensions.storage.dao import ExtensionStorageDAO
+
+ # All entries linked to a specific resource this extension created
+ entries = ExtensionStorageDAO.filter_by(
+ resource_type="my-resource-type",
+ resource_uuid=resource_uuid,
+ )
+
+ # Bulk-delete rows for a resource that no longer exists
+ ExtensionStorageDAO.delete(entries)
+"""
+
+from superset_core.common.daos import BaseDAO
+from superset_core.extensions.storage.models import ExtensionStorageEntry
+
+
+class ExtensionStorageDAO(BaseDAO[ExtensionStorageEntry]):
+ """
+ Abstract DAO for an extension's own Tier 3 persistent storage rows.
+
+ Host implementations will replace this class during initialization
+ with a concrete implementation providing actual functionality.
+
+ Inherits `find_all`, `find_one_or_none`, `filter_by`, `query`, `update`,
+ and `delete` from `BaseDAO`, every one restricted to the calling
+ extension's own rows. `create()` is overridden by the host
+ implementation to always raise: it is a raw insert with no upsert
+ dedup, quota check, or locking against the key
+ `superset_core.extensions.storage.persistent`'s `set()` writes to, so
+ use that (or the ambient `ctx.storage.persistent.set()` accessor) to
+ write a value instead.
+ """
+
+ # Class variables that will be set by host implementation
+ model_cls = None
+ base_filter = None
+ id_column_name = "id"
diff --git a/superset-core/src/superset_core/extensions/storage/ephemeral.py b/superset-core/src/superset_core/extensions/storage/ephemeral.py
new file mode 100644
index 00000000000..4537ed8aa6e
--- /dev/null
+++ b/superset-core/src/superset_core/extensions/storage/ephemeral.py
@@ -0,0 +1,162 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Ephemeral State API for superset-core extensions (Tier 2 Storage).
+
+Provides short-lived KV storage backed by the configured server-side cache
+backend (Redis, Memcached, or filesystem). Automatically expires based on TTL.
+Not guaranteed to survive server restarts.
+
+Host implementations will replace the EphemeralState class during initialization
+with a concrete implementation providing actual functionality.
+
+Cache keys are namespaced automatically:
+- User-scoped (default): superset-ext:{extension_id}:user:{user_id}:{key}
+- Shared (global): superset-ext:{extension_id}:shared:{key}
+
+Usage (via extension context - preferred):
+ from superset_core.extensions.context import get_context
+
+ ctx = get_context()
+
+ # User-scoped state (default - private to current user)
+ ctx.storage.ephemeral.get('preference')
+ ctx.storage.ephemeral.set('preference', 'compact', EphemeralSetOptions(ttl=3600))
+ ctx.storage.ephemeral.remove('preference')
+
+ # Shared state (explicit opt-in - visible to all users)
+ ctx.storage.ephemeral.shared.get('job_progress')
+ ctx.storage.ephemeral.shared.set(
+ 'job_progress', {'pct': 42}, EphemeralSetOptions(ttl=3600)
+ )
+ ctx.storage.ephemeral.shared.remove('job_progress')
+"""
+
+from dataclasses import dataclass
+from typing import Any, ClassVar, Protocol
+
+
+@dataclass(frozen=True)
+class EphemeralSetOptions:
+ """
+ Options for an ephemeral state `set` call.
+
+ `ttl` is required (no default): every write must have an explicit
+ expiration, matching the frontend `EphemeralSetOptions` and the REST API.
+ """
+
+ ttl: int
+ #: Name of the codec used to encode `value`, e.g. "json" (default).
+ codec: str = "json"
+
+
+class EphemeralStateAccessor(Protocol):
+ """Protocol for scoped ephemeral state access."""
+
+ def get(self, key: str) -> Any:
+ """Get a value from ephemeral state."""
+ ...
+
+ def set(self, key: str, value: Any, options: EphemeralSetOptions) -> None:
+ """Set a value in ephemeral state with TTL."""
+ ...
+
+ def remove(self, key: str) -> None:
+ """Remove a value from ephemeral state."""
+ ...
+
+
+class _UnconfiguredEphemeralStateAccessor:
+ """Placeholder for `.shared` before host replacement.
+
+ Raises the same `NotImplementedError` as the other stub methods, rather
+ than a bare `AttributeError`, if accessed before the host wires up the
+ concrete implementation.
+ """
+
+ def get(self, key: str) -> Any:
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ def set(self, key: str, value: Any, options: EphemeralSetOptions) -> None:
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ def remove(self, key: str) -> None:
+ raise NotImplementedError("Class will be replaced during initialization")
+
+
+class EphemeralState:
+ """
+ Tier 2 ephemeral state storage for extensions.
+
+ Backed by the configured server-side cache (Redis, Memcached, or filesystem).
+ Data expires based on TTL and is not guaranteed to survive server restarts.
+
+ Host implementations will replace this class during initialization
+ with a concrete implementation providing actual functionality.
+
+ All operations are user-scoped by default (private to the current user).
+ Use `.shared` to access state that is visible to all users.
+ """
+
+ @staticmethod
+ def get(key: str) -> Any:
+ """
+ Get a value from user-scoped ephemeral state.
+
+ Data is automatically scoped to the current authenticated user.
+ Other users cannot see or modify this data.
+
+ :param key: The key to retrieve.
+ :returns: The stored value, or None if not found or expired.
+ """
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ @staticmethod
+ def set(key: str, value: Any, options: EphemeralSetOptions) -> None:
+ """
+ Set a value in user-scoped ephemeral state with TTL.
+
+ Data is automatically scoped to the current authenticated user.
+ Other users cannot see or modify this data.
+
+ :param key: The key to store.
+ :param value: The value to store, encoded with `options.codec`
+ (default "json"). The encoded value must not exceed
+ MAX_VALUE_SIZE from config.
+ :param options: `EphemeralSetOptions`, e.g. `ttl=3600`. Required —
+ `ttl` must not exceed MAX_TTL from config. `codec="pickle"`
+ stores a value that isn't JSON-serializable.
+ """
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ @staticmethod
+ def remove(key: str) -> None:
+ """
+ Remove a value from user-scoped ephemeral state.
+
+ Data is automatically scoped to the current authenticated user.
+
+ :param key: The key to remove.
+ """
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ #: Shared (global) ephemeral state accessor.
+ #: Data stored via this accessor is visible to all users of the extension.
+ #: WARNING: Do not store user-specific or sensitive data here.
+ #: Host implementations will replace this during initialization.
+ shared: ClassVar[EphemeralStateAccessor] = _UnconfiguredEphemeralStateAccessor()
diff --git a/superset-core/src/superset_core/extensions/storage/models.py b/superset-core/src/superset_core/extensions/storage/models.py
new file mode 100644
index 00000000000..847052ed021
--- /dev/null
+++ b/superset-core/src/superset_core/extensions/storage/models.py
@@ -0,0 +1,74 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Persistent storage model API for superset-core extensions (Tier 3 Storage).
+
+Provides the model class backing `superset_core.extensions.storage.dao.
+ExtensionStorageDAO`, for extension backend code that needs to enumerate or
+bulk-manage its own persistent storage rows (for example, a periodic cleanup
+job pruning rows linked to resources that no longer exist), rather than the
+single-key get/set/remove shape of `persistent`.
+
+Usage:
+ from superset_core.extensions.storage.models import ExtensionStorageEntry
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+from superset_core.common.models import CoreModel
+
+if TYPE_CHECKING:
+ from datetime import datetime
+
+
+class ExtensionStorageEntry(CoreModel):
+ """
+ Abstract model interface for a single Tier 3 persistent storage row.
+
+ Host implementations will replace this class during initialization
+ with a concrete implementation providing actual functionality.
+
+ `value` is the raw stored payload (encrypted at rest when `is_encrypted`
+ is set), encoded with the codec named by `codec`; decoding/decryption is
+ handled by `superset_core.extensions.storage.dao.ExtensionStorageDAO`,
+ not by reading this field directly.
+ """
+
+ __abstract__ = True
+
+ # Type hints for expected column attributes
+ id: int
+ uuid: UUID
+ extension_id: str
+ user_fk: int | None
+ resource_type: str | None
+ resource_uuid: str | None
+ key: str
+ value: bytes
+ value_size: int
+ codec: str
+ is_encrypted: bool
+
+ # Audit fields
+ created_on: "datetime | None"
+ changed_on: "datetime | None"
+ created_by_fk: int | None
+ changed_by_fk: int | None
diff --git a/superset-core/src/superset_core/extensions/storage/persistent.py b/superset-core/src/superset_core/extensions/storage/persistent.py
new file mode 100644
index 00000000000..fa2b7e5ad31
--- /dev/null
+++ b/superset-core/src/superset_core/extensions/storage/persistent.py
@@ -0,0 +1,243 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Persistent State API for superset-core extensions (Tier 3 Storage).
+
+Provides durable KV storage backed by a dedicated database table.
+Data survives server restarts, cache evictions, and browser clears.
+Suitable for user preferences, saved state, and any data that must not be lost.
+
+Host implementations will replace the PersistentState class during initialization
+with a concrete implementation providing actual functionality.
+
+Database keys are namespaced automatically:
+- User-scoped (default): (extension_id, user_id, key)
+- Shared (global): (extension_id, null, key)
+
+Usage (via extension context - preferred):
+ from superset_core.extensions.context import get_context
+
+ ctx = get_context()
+
+ # User-scoped state (default - private to current user)
+ ctx.storage.persistent.get('preferences')
+ ctx.storage.persistent.set('preferences', {'theme': 'dark'})
+ ctx.storage.persistent.remove('preferences')
+
+ # Shared state (explicit opt-in - visible to all users)
+ ctx.storage.persistent.shared.get('global_config')
+ ctx.storage.persistent.shared.set('global_config', {'version': 2})
+ ctx.storage.persistent.shared.remove('global_config')
+
+ # Encrypted at rest
+ ctx.storage.persistent.set(
+ 'api_token', 'sk-...', PersistentSetOptions(encrypt=True)
+ )
+
+ # Listing entries (page and page_size are required)
+ result = ctx.storage.persistent.list(PersistentListOptions(page=0, page_size=10))
+ for entry in result.entries:
+ print(entry.key, entry.value)
+"""
+
+from dataclasses import dataclass, field
+from typing import Any, ClassVar, Protocol
+
+
+@dataclass(frozen=True)
+class PersistentSetOptions:
+ """
+ Options for a persistent state `set` call.
+
+ NOTE: This is intentionally minimal for the initial implementation.
+ Additional options can be added here later without changing the `set`
+ signature on `PersistentStateAccessor`/`PersistentState`.
+ """
+
+ encrypt: bool = False
+ #: Name of the codec used to encode `value`, e.g. "json" (default).
+ codec: str = "json"
+
+
+@dataclass(frozen=True)
+class PersistentListOptions:
+ """Options for a persistent state `list` call.
+
+ `page` and `page_size` are required (no default): `list` returns one
+ page of a caller's entries, not the whole result set, and a default
+ would let that fact go unnoticed at the call site. Check the returned
+ `PersistentListResult.count` against `page_size` to know whether more
+ pages exist.
+
+ `resource_type`/`resource_uuid` are optional filters; omitting them
+ lists every entry in the caller's scope (global or user-scoped,
+ depending on whether `list` is called via `.shared` or directly).
+ """
+
+ #: Zero-indexed page number.
+ page: int
+ #: Entries per page. There is no fixed ceiling on this value, but a
+ #: page whose combined value size exceeds MAX_LIST_PAYLOAD_SIZE from
+ #: config is rejected — reduce page_size and retry if that happens.
+ page_size: int
+ resource_type: str | None = None
+ resource_uuid: str | None = None
+
+
+@dataclass(frozen=True)
+class PersistentListEntry:
+ """A single entry returned by a persistent state `list` call."""
+
+ key: str
+ value: Any
+ #: Name of the codec `value` was encoded with, e.g. "json" or "pickle".
+ codec: str
+
+
+@dataclass(frozen=True)
+class PersistentListResult:
+ """Result of a persistent state `list` call."""
+
+ entries: list[PersistentListEntry] = field(default_factory=list)
+ #: Total number of entries matching the given scope/filters, across all
+ #: pages — not just the number returned in `entries`.
+ count: int = 0
+
+
+class PersistentStateAccessor(Protocol):
+ """Protocol for scoped persistent state access."""
+
+ def get(self, key: str) -> Any:
+ """Get a value from persistent state."""
+ ...
+
+ def set(
+ self, key: str, value: Any, options: PersistentSetOptions | None = None
+ ) -> None:
+ """Set a value in persistent state."""
+ ...
+
+ def list(self, options: PersistentListOptions) -> PersistentListResult:
+ """List entries in persistent state."""
+ ...
+
+ def remove(self, key: str) -> None:
+ """Remove a value from persistent state."""
+ ...
+
+
+class _UnconfiguredPersistentStateAccessor:
+ """Placeholder for `.shared` before host replacement.
+
+ Raises the same `NotImplementedError` as the other stub methods, rather
+ than a bare `AttributeError`, if accessed before the host wires up the
+ concrete implementation.
+ """
+
+ def get(self, key: str) -> Any:
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ def set(
+ self, key: str, value: Any, options: PersistentSetOptions | None = None
+ ) -> None:
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ def list(self, options: PersistentListOptions) -> PersistentListResult:
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ def remove(self, key: str) -> None:
+ raise NotImplementedError("Class will be replaced during initialization")
+
+
+class PersistentState:
+ """
+ Tier 3 persistent state storage for extensions.
+
+ Backed by a dedicated database table. Data survives server restarts,
+ cache evictions, and browser clears.
+
+ Host implementations will replace this class during initialization
+ with a concrete implementation providing actual functionality.
+
+ All operations are user-scoped by default (private to the current user).
+ Use `.shared` to access state that is visible to all users.
+ """
+
+ @staticmethod
+ def get(key: str) -> Any:
+ """
+ Get a value from user-scoped persistent state.
+
+ Data is automatically scoped to the current authenticated user.
+ Other users cannot see or modify this data.
+
+ :param key: The key to retrieve.
+ :returns: The stored value, or None if not found.
+ """
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ @staticmethod
+ def set(key: str, value: Any, options: PersistentSetOptions | None = None) -> None:
+ """
+ Set a value in user-scoped persistent state.
+
+ Data is automatically scoped to the current authenticated user.
+ Other users cannot see or modify this data.
+ Data persists indefinitely until explicitly removed.
+
+ :param key: The key to store.
+ :param value: The value to store, encoded with `options.codec`
+ (default "json"). The encoded value must not exceed
+ MAX_VALUE_SIZE from config.
+ :param options: Optional `PersistentSetOptions`, e.g. `encrypt=True`
+ to store the value encrypted at rest, or `codec="pickle"` to
+ store a value that isn't JSON-serializable.
+ """
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ @staticmethod
+ def list(options: PersistentListOptions) -> PersistentListResult:
+ """
+ List entries in user-scoped persistent state.
+
+ Data is automatically scoped to the current authenticated user.
+ Other users' entries are never returned.
+
+ :param options: `PersistentListOptions`, e.g.
+ `PersistentListOptions(page=0, page_size=10)`.
+ :returns: `PersistentListResult` with the page's entries and the
+ total count across all pages.
+ """
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ @staticmethod
+ def remove(key: str) -> None:
+ """
+ Remove a value from user-scoped persistent state.
+
+ Data is automatically scoped to the current authenticated user.
+
+ :param key: The key to remove.
+ """
+ raise NotImplementedError("Class will be replaced during initialization")
+
+ #: Shared (global) persistent state accessor.
+ #: Data stored via this accessor is visible to all users of the extension.
+ #: WARNING: Do not store user-specific or sensitive data here.
+ #: Host implementations will replace this during initialization.
+ shared: ClassVar[PersistentStateAccessor] = _UnconfiguredPersistentStateAccessor()
diff --git a/superset-core/src/superset_core/extensions/types.py b/superset-core/src/superset_core/extensions/types.py
index bfaeba5a43c..1a067b52d44 100644
--- a/superset-core/src/superset_core/extensions/types.py
+++ b/superset-core/src/superset_core/extensions/types.py
@@ -25,7 +25,7 @@ Two distinct schemas:
from __future__ import annotations
-from pydantic import BaseModel, Field # noqa: I001
+from pydantic import BaseModel, computed_field, Field # noqa: I001
from superset_core.extensions.constants import (
DISPLAY_NAME_PATTERN,
@@ -78,6 +78,11 @@ class BaseExtension(BaseModel):
description="Permissions required by this extension",
)
+ @computed_field(description="Composite extension ID (publisher.name)") # type: ignore[prop-decorator]
+ @property
+ def id(self) -> str:
+ return f"{self.publisher}.{self.name}"
+
# =============================================================================
# ExtensionConfig (extension.json)
@@ -137,11 +142,6 @@ class Manifest(BaseExtension):
This file is generated by the build tool from extension.json.
"""
- id: str = Field(
- ...,
- description="Composite extension ID (publisher.name)",
- min_length=1,
- )
frontend: ManifestFrontend | None = Field(
default=None,
description="Frontend manifest",
diff --git a/superset-extensions-cli/src/superset_extensions_cli/cli.py b/superset-extensions-cli/src/superset_extensions_cli/cli.py
index c2adb5ea1e0..fc85c2dcf10 100644
--- a/superset-extensions-cli/src/superset_extensions_cli/cli.py
+++ b/superset-extensions-cli/src/superset_extensions_cli/cli.py
@@ -151,9 +151,6 @@ def build_manifest(cwd: Path, remote_entry: str | None) -> Manifest:
extension = ExtensionConfig.model_validate(extension_data)
- # Generate composite ID from publisher and name
- composite_id = f"{extension.publisher}.{extension.name}"
-
frontend: ManifestFrontend | None = None
if remote_entry:
frontend = ManifestFrontend(
@@ -173,7 +170,6 @@ def build_manifest(cwd: Path, remote_entry: str | None) -> Manifest:
backend = ManifestBackend(entrypoint=entrypoint)
return Manifest(
- id=composite_id,
publisher=extension.publisher,
name=extension.name,
displayName=extension.displayName,
diff --git a/superset-extensions-cli/src/superset_extensions_cli/templates/frontend/webpack.config.js.j2 b/superset-extensions-cli/src/superset_extensions_cli/templates/frontend/webpack.config.js.j2
index 93fc61459fb..01ed5514f0a 100644
--- a/superset-extensions-cli/src/superset_extensions_cli/templates/frontend/webpack.config.js.j2
+++ b/superset-extensions-cli/src/superset_extensions_cli/templates/frontend/webpack.config.js.j2
@@ -25,10 +25,6 @@ module.exports = (env, argv) => {
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"],
},
- externalsType: "window",
- externals: {
- "@apache-superset/core": "superset",
- },
module: {
rules: [
{
@@ -61,6 +57,10 @@ module.exports = (env, argv) => {
requiredVersion: packageConfig.peerDependencies["antd"],
import: false,
},
+ "@apache-superset/core": {
+ singleton: true,
+ import: false,
+ },
},
}),
],
diff --git a/superset-frontend/packages/superset-core/README.md b/superset-frontend/packages/superset-core/README.md
index d9f835dab98..ed55c7ddf30 100644
--- a/superset-frontend/packages/superset-core/README.md
+++ b/superset-frontend/packages/superset-core/README.md
@@ -45,6 +45,7 @@ src/
├── extensions/
├── menus/
├── sqlLab/
+├── storage/
├── theme/
├── translation/
├── utils/
diff --git a/superset-frontend/packages/superset-core/package.json b/superset-frontend/packages/superset-core/package.json
index 992c938fee7..e06f9b7ac56 100644
--- a/superset-frontend/packages/superset-core/package.json
+++ b/superset-frontend/packages/superset-core/package.json
@@ -73,6 +73,10 @@
"./testing": {
"types": "./lib/testing.d.ts",
"default": "./lib/testing.js"
+ },
+ "./storage": {
+ "types": "./lib/storage/index.d.ts",
+ "default": "./lib/storage/index.js"
}
},
"files": [
diff --git a/superset-frontend/packages/superset-core/src/common/index.ts b/superset-frontend/packages/superset-core/src/common/index.ts
index 7f28aba584b..4519a1e154b 100644
--- a/superset-frontend/packages/superset-core/src/common/index.ts
+++ b/superset-frontend/packages/superset-core/src/common/index.ts
@@ -227,8 +227,6 @@ export interface Extension {
id: string;
/** Human-readable name of the extension */
name: string;
- /** URL or path to the extension's remote entry point */
- remoteEntry: string;
/** Version of the extension */
version: string;
}
diff --git a/superset-frontend/packages/superset-core/src/extensions/index.ts b/superset-frontend/packages/superset-core/src/extensions/index.ts
index 2a21f45e91f..d02538bb71d 100644
--- a/superset-frontend/packages/superset-core/src/extensions/index.ts
+++ b/superset-frontend/packages/superset-core/src/extensions/index.ts
@@ -24,9 +24,80 @@
* including querying extension metadata and monitoring extension lifecycle events.
* Extensions can use this API to discover other extensions and react to changes
* in the extension ecosystem.
+ *
+ * Extensions can access their own context via `getContext()`, which provides:
+ * - Extension metadata (id, name, version, etc.)
+ * - Extension-scoped storage (localStorage, sessionStorage, ephemeral cache)
+ *
+ * @example
+ * ```typescript
+ * import { extensions } from '@apache-superset/core';
+ *
+ * // Get the current extension's context
+ * const ctx = extensions.getContext();
+ *
+ * // Access extension metadata
+ * console.log(`Running ${ctx.extension.name} v${ctx.extension.version}`);
+ *
+ * // Access extension-scoped storage
+ * await ctx.storage.local.set('preference', { theme: 'dark' });
+ * await ctx.storage.ephemeral.set('cache', data, { ttl: 300 });
+ * ```
*/
import { Extension } from '../common';
+import { ExtensionStorage } from '../storage';
+
+/**
+ * Context object providing extension-specific resources.
+ *
+ * This context is only available during extension execution.
+ * Calling `getContext()` outside of an extension will throw an error.
+ */
+export interface ExtensionContext {
+ /**
+ * Metadata about the current extension.
+ */
+ extension: Extension;
+
+ /**
+ * Extension-scoped storage across all tiers.
+ * All keys are automatically namespaced to prevent collisions.
+ */
+ storage: ExtensionStorage;
+}
+
+/**
+ * Get the current extension's context.
+ *
+ * This function returns the context for the currently executing extension,
+ * providing access to extension metadata and scoped resources like storage.
+ *
+ * @returns The current extension's context.
+ * @throws Error if called outside of an extension context.
+ *
+ * @example
+ * ```typescript
+ * import { extensions } from '@apache-superset/core';
+ *
+ * const ctx = extensions.getContext();
+ *
+ * // Access extension metadata
+ * console.log(`Extension: ${ctx.extension.id}`);
+ * console.log(`Version: ${ctx.extension.version}`);
+ *
+ * // Access extension-scoped storage
+ * await ctx.storage.local.set('userPref', { sidebar: 'collapsed' });
+ * const pref = await ctx.storage.local.get('userPref');
+ *
+ * // Use ephemeral storage with TTL
+ * await ctx.storage.ephemeral.set('tempData', data, { ttl: 3600 });
+ *
+ * // Access shared (cross-user) storage
+ * await ctx.storage.ephemeral.shared.set('globalCounter', count, { ttl: 3600 });
+ * ```
+ */
+export declare function getContext(): ExtensionContext;
/**
* Get an extension by its full identifier in the form of: `publisher.name`.
diff --git a/superset-frontend/packages/superset-core/src/index.ts b/superset-frontend/packages/superset-core/src/index.ts
index be41ac88a19..6d6a0aa4653 100644
--- a/superset-frontend/packages/superset-core/src/index.ts
+++ b/superset-frontend/packages/superset-core/src/index.ts
@@ -30,4 +30,5 @@ export * as contributions from './contributions';
export * as theme from './theme';
export * as translation from './translation';
export * as components from './components';
+export * as storage from './storage';
export * as utils from './utils';
diff --git a/superset-frontend/packages/superset-core/src/storage/index.ts b/superset-frontend/packages/superset-core/src/storage/index.ts
new file mode 100644
index 00000000000..ecba890454d
--- /dev/null
+++ b/superset-frontend/packages/superset-core/src/storage/index.ts
@@ -0,0 +1,218 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * @fileoverview Shared types for extension storage APIs.
+ *
+ * These types are shared across all storage tiers (local, session, ephemeral,
+ * persistent) to ensure a consistent API pattern.
+ */
+
+/**
+ * JSON-compatible value type.
+ * These are the only values that can be safely serialized/deserialized via JSON.
+ */
+export type JsonValue =
+ string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
+
+/**
+ * Base interface for a storage accessor.
+ * All storage tiers implement this interface for both user-scoped and shared access.
+ */
+export interface StorageAccessor {
+ /**
+ * Get a value from storage.
+ *
+ * @param key The key to retrieve.
+ * @returns The stored value, or null if not found.
+ */
+ get<T = JsonValue>(key: string): Promise<T | null>;
+
+ /**
+ * Set a value in storage.
+ *
+ * @param key The key to store.
+ * @param value The value to store (must be JSON-serializable).
+ */
+ set<T = JsonValue>(key: string, value: T): Promise<void>;
+
+ /**
+ * Remove a value from storage.
+ *
+ * @param key The key to remove.
+ */
+ remove(key: string): Promise<void>;
+}
+
+/**
+ * Options required when setting ephemeral (server-cached) state.
+ */
+export interface EphemeralSetOptions {
+ ttl: number;
+ /** Name of the codec used to encode the value, e.g. "json" (default). */
+ codec?: string;
+ /** Whether `value` is binary data. */
+ isBinary?: boolean;
+}
+
+/**
+ * Options available when setting persistent (database-backed) state.
+ */
+export interface PersistentSetOptions {
+ encrypt?: boolean;
+ /** Name of the codec used to encode the value, e.g. "json" (default). */
+ codec?: string;
+ /** Whether `value` is binary data. */
+ isBinary?: boolean;
+}
+
+/**
+ * Options for listing persistent (database-backed) state entries.
+ *
+ * `page` and `pageSize` are required (no default): `list` returns one page
+ * of a caller's entries, not the whole result set, and a default would let
+ * that fact go unnoticed at the call site. Check the returned
+ * `PersistentListResult.count` against `pageSize` to know whether more
+ * pages exist.
+ *
+ * `resourceType`/`resourceUuid` are optional filters; omitting them lists
+ * every entry in the caller's scope (global or user-scoped, depending on
+ * whether `list` is called via `.shared` or directly).
+ */
+export interface PersistentListOptions {
+ /** Zero-indexed page number. */
+ page: number;
+ /**
+ * Entries per page. There is no fixed ceiling on this value, but a page
+ * whose combined value size exceeds MAX_LIST_PAYLOAD_SIZE from config is
+ * rejected — reduce pageSize and retry if that happens.
+ */
+ pageSize: number;
+ resourceType?: string;
+ resourceUuid?: string;
+}
+
+/**
+ * A single entry returned by a persistent state `list` call.
+ */
+export interface PersistentListEntry<T = JsonValue> {
+ key: string;
+ /**
+ * The stored value. When `isBinary` is true, this is a base64 string
+ * that must be decoded to get the actual value.
+ */
+ value: T | null;
+ /** Name of the codec `value` was encoded with, e.g. "json" or "binary". */
+ codec: string;
+ /** Whether the stored value is binary data. */
+ isBinary: boolean;
+}
+
+/**
+ * Result of a persistent state `list` call.
+ */
+export interface PersistentListResult<T = JsonValue> {
+ entries: PersistentListEntry<T>[];
+ /**
+ * Total number of entries matching the given scope/filters, across all
+ * pages — not just the number returned in `entries`.
+ */
+ count: number;
+}
+
+/**
+ * Storage accessor for ephemeral state, requiring TTL on every set.
+ */
+export interface EphemeralStorageAccessor {
+ get<T = JsonValue>(key: string): Promise<T | null>;
+ set<T = JsonValue>(
+ key: string,
+ value: T,
+ options: EphemeralSetOptions,
+ ): Promise<void>;
+ remove(key: string): Promise<void>;
+}
+
+/**
+ * Storage tier for ephemeral state with TTL-required set operations.
+ */
+export interface EphemeralStorageTier extends EphemeralStorageAccessor {
+ shared: EphemeralStorageAccessor;
+}
+
+/**
+ * Storage accessor for persistent state, supporting optional encryption.
+ */
+export interface PersistentStorageAccessor {
+ get<T = JsonValue>(key: string): Promise<T | null>;
+ set<T = JsonValue>(
+ key: string,
+ value: T,
+ options?: PersistentSetOptions,
+ ): Promise<void>;
+ list<T = JsonValue>(
+ options: PersistentListOptions,
+ ): Promise<PersistentListResult<T>>;
+ remove(key: string): Promise<void>;
+}
+
+/**
+ * Storage tier for persistent (database-backed) state.
+ */
+export interface PersistentStorageTier extends PersistentStorageAccessor {
+ shared: PersistentStorageAccessor;
+}
+
+/**
+ * Extension-scoped storage accessor for all available tiers.
+ *
+ * All storage tiers are automatically namespaced to the current extension,
+ * preventing key collisions between extensions.
+ */
+export interface ExtensionStorage {
+ /**
+ * Browser localStorage - persists across browser sessions.
+ * Data is scoped to the current extension and user. There is no
+ * `.shared` accessor for this tier: browser storage is per-device, so a
+ * "shared" value would only be visible to other users of the same
+ * browser, not to other users of the extension generally.
+ */
+ local: StorageAccessor;
+
+ /**
+ * Browser sessionStorage - cleared when the tab closes.
+ * Data is scoped to the current extension and user. There is no
+ * `.shared` accessor for this tier; see `local` above.
+ */
+ session: StorageAccessor;
+
+ /**
+ * Server-side cache (Redis/Memcached) with TTL.
+ * Data is scoped to the current extension and user.
+ * Use `.shared` for data visible to all users.
+ */
+ ephemeral: EphemeralStorageTier;
+
+ /**
+ * Durable database-backed storage (Tier 3).
+ * Data survives server restarts and cache evictions.
+ * Use `.shared` for data visible to all users.
+ */
+ persistent: PersistentStorageTier;
+}
diff --git a/superset-frontend/src/components/PanelToolbar/index.tsx b/superset-frontend/src/components/PanelToolbar/index.tsx
index 8d5e9bb39fb..cabd7a92862 100644
--- a/superset-frontend/src/components/PanelToolbar/index.tsx
+++ b/superset-frontend/src/components/PanelToolbar/index.tsx
@@ -55,7 +55,7 @@ const PanelToolbar = ({
return (
<Button
- key={item.view}
+ key={item.command}
onClick={() => commands.executeCommand(command?.id)}
tooltip={command?.description ?? command?.title}
icon={<Icon iconSize="m" />}
diff --git a/superset-frontend/src/core/extensions/index.ts b/superset-frontend/src/core/extensions/index.test.ts
similarity index 64%
copy from superset-frontend/src/core/extensions/index.ts
copy to superset-frontend/src/core/extensions/index.test.ts
index ae49a135aed..e0974ca189c 100644
--- a/superset-frontend/src/core/extensions/index.ts
+++ b/superset-frontend/src/core/extensions/index.test.ts
@@ -16,16 +16,11 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { extensions as extensionsApi } from '@apache-superset/core';
-import ExtensionsLoader from 'src/extensions/ExtensionsLoader';
-const getExtension: typeof extensionsApi.getExtension = id =>
- ExtensionsLoader.getInstance().getExtension(id);
+import { extensions as extensionsImpl } from './index';
-const getAllExtensions: typeof extensionsApi.getAllExtensions = () =>
- ExtensionsLoader.getInstance().getExtensions();
-
-export const extensions: typeof extensionsApi = {
- getExtension,
- getAllExtensions,
-};
+test('extensions.getContext throws when not in extension context', () => {
+ expect(() => extensionsImpl.getContext()).toThrow(
+ 'getContext() must be called within an extension context',
+ );
+});
diff --git a/superset-frontend/src/core/extensions/index.ts b/superset-frontend/src/core/extensions/index.ts
index ae49a135aed..17b6c748b03 100644
--- a/superset-frontend/src/core/extensions/index.ts
+++ b/superset-frontend/src/core/extensions/index.ts
@@ -16,9 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { extensions as extensionsApi } from '@apache-superset/core';
+import type { extensions as extensionsApi } from '@apache-superset/core';
import ExtensionsLoader from 'src/extensions/ExtensionsLoader';
+export { createExtensionContext } from 'src/extensions/ExtensionContext';
+
+const getContext: typeof extensionsApi.getContext = () => {
+ throw new Error(
+ 'getContext() must be called within an extension context. ' +
+ 'Ensure this code is being executed by an extension.',
+ );
+};
+
const getExtension: typeof extensionsApi.getExtension = id =>
ExtensionsLoader.getInstance().getExtension(id);
@@ -26,6 +35,7 @@ const getAllExtensions: typeof extensionsApi.getAllExtensions = () =>
ExtensionsLoader.getInstance().getExtensions();
export const extensions: typeof extensionsApi = {
+ getContext,
getExtension,
getAllExtensions,
};
diff --git a/superset-frontend/src/core/index.ts b/superset-frontend/src/core/index.ts
index ce5b7f4d505..ca8440c68e2 100644
--- a/superset-frontend/src/core/index.ts
+++ b/superset-frontend/src/core/index.ts
@@ -35,5 +35,6 @@ export * from './menus';
export * from './models';
export * from './navigation';
export * from './sqlLab';
+export * from './storage';
export * from './utils';
export * from './views';
diff --git a/superset-frontend/src/core/storage/binaryCodec.test.ts b/superset-frontend/src/core/storage/binaryCodec.test.ts
new file mode 100644
index 00000000000..6dc16bf9d6f
--- /dev/null
+++ b/superset-frontend/src/core/storage/binaryCodec.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { bytesToBase64, resolveSetPayload } from './binaryCodec';
+
+test('bytesToBase64 encodes bytes to a base64 string', () => {
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
+ expect(bytesToBase64(bytes)).toBe(btoa('\x89PNG'));
+});
+
+test('resolveSetPayload passes through a plain number with the json codec', () => {
+ expect(resolveSetPayload(1, undefined)).toEqual({
+ value: 1,
+ codec: 'json',
+ isBinary: false,
+ });
+});
+
+test('resolveSetPayload passes through a plain object with the json codec', () => {
+ expect(resolveSetPayload({ a: 1 }, undefined)).toEqual({
+ value: { a: 1 },
+ codec: 'json',
+ isBinary: false,
+ });
+});
+
+test('resolveSetPayload does not base64-encode a Uint8Array unless isBinary is true', () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ expect(resolveSetPayload(bytes, undefined)).toEqual({
+ value: bytes,
+ codec: 'json',
+ isBinary: false,
+ });
+});
+
+test('resolveSetPayload base64-encodes a Uint8Array when isBinary is true', () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ expect(resolveSetPayload(bytes, { isBinary: true })).toEqual({
+ value: bytesToBase64(bytes),
+ codec: 'binary',
+ isBinary: true,
+ });
+});
+
+test('resolveSetPayload base64-encodes an ArrayBuffer when isBinary is true', () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ expect(resolveSetPayload(bytes.buffer, { isBinary: true })).toEqual({
+ value: bytesToBase64(bytes),
+ codec: 'binary',
+ isBinary: true,
+ });
+});
+
+test('resolveSetPayload base64-encodes a Uint8Array when isBinary is true, even with an explicit codec', () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ expect(resolveSetPayload(bytes, { codec: 'pickle', isBinary: true })).toEqual(
+ {
+ value: bytesToBase64(bytes),
+ codec: 'pickle',
+ isBinary: true,
+ },
+ );
+});
+
+test('resolveSetPayload respects an explicit codec for a non-binary value and does not flag isBinary', () => {
+ expect(resolveSetPayload('sk-...', { codec: 'pickle' })).toEqual({
+ value: 'sk-...',
+ codec: 'pickle',
+ isBinary: false,
+ });
+});
+
+test('resolveSetPayload does not double-encode a caller-provided base64 string, and flags isBinary when told to', () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ const preEncoded = bytesToBase64(bytes);
+ expect(
+ resolveSetPayload(preEncoded, { codec: 'binary', isBinary: true }),
+ ).toEqual({
+ value: preEncoded,
+ codec: 'binary',
+ isBinary: true,
+ });
+});
+
+test('resolveSetPayload does not flag isBinary for a caller-provided string unless told to', () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ const preEncoded = bytesToBase64(bytes);
+ expect(resolveSetPayload(preEncoded, { codec: 'binary' })).toEqual({
+ value: preEncoded,
+ codec: 'binary',
+ isBinary: false,
+ });
+});
diff --git a/superset-frontend/src/core/storage/binaryCodec.ts b/superset-frontend/src/core/storage/binaryCodec.ts
new file mode 100644
index 00000000000..7fb1d66e378
--- /dev/null
+++ b/superset-frontend/src/core/storage/binaryCodec.ts
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/** Convert bytes to a base64 string, for transport over the JSON REST API. */
+export function bytesToBase64(bytes: Uint8Array): string {
+ let binary = '';
+ bytes.forEach(byte => {
+ binary += String.fromCharCode(byte);
+ });
+ return btoa(binary);
+}
+
+function isBinaryValue(value: unknown): value is Uint8Array | ArrayBuffer {
+ return value instanceof Uint8Array || value instanceof ArrayBuffer;
+}
+
+/**
+ * Resolve the codec, request-body value, and `isBinary` flag for a
+ * `set()` call.
+ *
+ * `isBinary` is caller-driven, not inferred from `value`'s JS type: it
+ * tells the REST API whether `value` on the wire is a base64 string that
+ * must be decoded before being handed to whichever codec was chosen,
+ * since JSON has no byte type and there is no way for the server to
+ * infer this from the JSON value alone. When set and `value` is a
+ * `Uint8Array`/`ArrayBuffer`, it is base64-encoded here for transport; a
+ * caller that already has a base64 string (e.g. encoded for a codec this
+ * SDK doesn't know about) can pass that directly instead.
+ */
+export function resolveSetPayload<T>(
+ value: T,
+ options: { codec?: string; isBinary?: boolean } | undefined,
+): { value: unknown; codec: string; isBinary: boolean } {
+ const explicitCodec = options?.codec;
+ const binary = options?.isBinary ?? false;
+ if (binary && isBinaryValue(value)) {
+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
+ return {
+ value: bytesToBase64(bytes),
+ codec: explicitCodec ?? 'binary',
+ isBinary: true,
+ };
+ }
+ return {
+ value,
+ codec: explicitCodec ?? (binary ? 'binary' : 'json'),
+ isBinary: binary,
+ };
+}
diff --git a/superset-frontend/src/core/storage/ephemeralState.test.ts b/superset-frontend/src/core/storage/ephemeralState.test.ts
new file mode 100644
index 00000000000..0e37bb8a006
--- /dev/null
+++ b/superset-frontend/src/core/storage/ephemeralState.test.ts
@@ -0,0 +1,170 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { SupersetClient } from '@superset-ui/core';
+import { createEphemeralState } from './ephemeralState';
+
+jest.mock('@superset-ui/core', () => ({
+ SupersetClient: {
+ get: jest.fn(),
+ put: jest.fn(),
+ delete: jest.fn(),
+ },
+}));
+
+const mockGet = SupersetClient.get as jest.Mock;
+const mockPut = SupersetClient.put as jest.Mock;
+const mockDelete = SupersetClient.delete as jest.Mock;
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockGet.mockResolvedValue({ json: { result: null } });
+ mockPut.mockResolvedValue({});
+ mockDelete.mockResolvedValue({});
+});
+
+test('get calls correct URL with publisher/name pattern', async () => {
+ const store = createEphemeralState('myorg.myext');
+ await store.get('job_progress');
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/ephemeral/job_progress',
+ });
+});
+
+test('get returns result from response', async () => {
+ mockGet.mockResolvedValue({ json: { result: { pct: 42 } } });
+ const store = createEphemeralState('myorg.myext');
+ const result = await store.get('job_progress');
+ expect(result).toEqual({ pct: 42 });
+});
+
+test('get returns null when result is absent', async () => {
+ mockGet.mockResolvedValue({ json: {} });
+ const store = createEphemeralState('myorg.myext');
+ expect(await store.get('key')).toBeNull();
+});
+
+test('set calls correct URL and includes value and ttl in body', async () => {
+ const store = createEphemeralState('myorg.myext');
+ await store.set('job_progress', { pct: 42 }, { ttl: 300 });
+ expect(mockPut).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/ephemeral/job_progress',
+ body: JSON.stringify({
+ value: { pct: 42 },
+ ttl: 300,
+ codec: 'json',
+ isBinary: false,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+});
+
+test('set passes codec from options', async () => {
+ const store = createEphemeralState('myorg.myext');
+ await store.set('job_progress', 'sk-...', { ttl: 300, codec: 'pickle' });
+ expect(mockPut).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/ephemeral/job_progress',
+ body: JSON.stringify({
+ value: 'sk-...',
+ ttl: 300,
+ codec: 'pickle',
+ isBinary: false,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+});
+
+test('set does not base64-encode a Uint8Array value unless isBinary is set', async () => {
+ const store = createEphemeralState('myorg.myext');
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
+ await store.set('icon', bytes, { ttl: 300 });
+ const body = JSON.parse(mockPut.mock.calls[0][0].body);
+ expect(body.codec).toBe('json');
+ expect(body.value).toEqual({ 0: 0x89, 1: 0x50, 2: 0x4e, 3: 0x47 });
+ expect(body.isBinary).toBe(false);
+});
+
+test('set base64-encodes a Uint8Array value when isBinary is true', async () => {
+ const store = createEphemeralState('myorg.myext');
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
+ await store.set('icon', bytes, { ttl: 300, isBinary: true });
+ const body = JSON.parse(mockPut.mock.calls[0][0].body);
+ expect(body.codec).toBe('binary');
+ expect(body.value).toBe(btoa('\x89PNG'));
+ expect(body.isBinary).toBe(true);
+});
+
+test('remove calls correct URL', async () => {
+ const store = createEphemeralState('myorg.myext');
+ await store.remove('job_progress');
+ expect(mockDelete).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/ephemeral/job_progress',
+ });
+});
+
+test('keys are URL-encoded', async () => {
+ const store = createEphemeralState('myorg.myext');
+ await store.get('key with spaces');
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/ephemeral/key%20with%20spaces',
+ });
+});
+
+test('publisher and name are URL-encoded', async () => {
+ const store = createEphemeralState('my org.my ext');
+ await store.get('key');
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/my%20org/my%20ext/storage/ephemeral/key',
+ });
+});
+
+test('shared.get appends ?shared=true', async () => {
+ const store = createEphemeralState('myorg.myext');
+ await store.shared.get('result');
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/ephemeral/result?shared=true',
+ });
+});
+
+test('shared.set appends ?shared=true and includes value and ttl', async () => {
+ const store = createEphemeralState('myorg.myext');
+ await store.shared.set('result', [1, 2, 3], { ttl: 600 });
+ expect(mockPut).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/ephemeral/result?shared=true',
+ body: JSON.stringify({
+ value: [1, 2, 3],
+ ttl: 600,
+ codec: 'json',
+ isBinary: false,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+});
+
+test('shared.remove appends ?shared=true', async () => {
+ const store = createEphemeralState('myorg.myext');
+ await store.shared.remove('result');
+ expect(mockDelete).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/ephemeral/result?shared=true',
+ });
+});
diff --git a/superset-frontend/src/core/storage/ephemeralState.ts b/superset-frontend/src/core/storage/ephemeralState.ts
new file mode 100644
index 00000000000..eaa58706746
--- /dev/null
+++ b/superset-frontend/src/core/storage/ephemeralState.ts
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type {
+ EphemeralSetOptions,
+ EphemeralStorageAccessor,
+ EphemeralStorageTier,
+ JsonValue,
+} from '@apache-superset/core/storage';
+import { SupersetClient } from '@superset-ui/core';
+import { resolveSetPayload } from './binaryCodec';
+
+/**
+ * Create ephemeral state (server cache) bound to an extension ID.
+ */
+export function createEphemeralState(
+ extensionId: string,
+): EphemeralStorageTier {
+ const [publisher, name] = extensionId.split('.');
+ const buildUrl = (key: string, shared?: boolean): string => {
+ const encodedPublisher = encodeURIComponent(publisher);
+ const encodedName = encodeURIComponent(name);
+ const encodedKey = encodeURIComponent(key);
+ const url = `/api/v1/extensions/${encodedPublisher}/${encodedName}/storage/ephemeral/${encodedKey}`;
+ return shared ? `${url}?shared=true` : url;
+ };
+
+ const shared: EphemeralStorageAccessor = {
+ async get<T = JsonValue>(key: string): Promise<T | null> {
+ const response = await SupersetClient.get({
+ endpoint: buildUrl(key, true),
+ });
+ return (response.json?.result ?? null) as T | null;
+ },
+ async set<T = JsonValue>(
+ key: string,
+ value: T,
+ options: EphemeralSetOptions,
+ ): Promise<void> {
+ const payload = resolveSetPayload(value, options);
+ await SupersetClient.put({
+ endpoint: buildUrl(key, true),
+ body: JSON.stringify({
+ value: payload.value,
+ ttl: options.ttl,
+ codec: payload.codec,
+ isBinary: payload.isBinary,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+ },
+ async remove(key: string): Promise<void> {
+ await SupersetClient.delete({ endpoint: buildUrl(key, true) });
+ },
+ };
+
+ return {
+ async get<T = JsonValue>(key: string): Promise<T | null> {
+ const response = await SupersetClient.get({ endpoint: buildUrl(key) });
+ return (response.json?.result ?? null) as T | null;
+ },
+ async set<T = JsonValue>(
+ key: string,
+ value: T,
+ options: EphemeralSetOptions,
+ ): Promise<void> {
+ const payload = resolveSetPayload(value, options);
+ await SupersetClient.put({
+ endpoint: buildUrl(key),
+ body: JSON.stringify({
+ value: payload.value,
+ ttl: options.ttl,
+ codec: payload.codec,
+ isBinary: payload.isBinary,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+ },
+ async remove(key: string): Promise<void> {
+ await SupersetClient.delete({ endpoint: buildUrl(key) });
+ },
+ shared,
+ };
+}
diff --git a/superset-frontend/src/core/extensions/index.ts b/superset-frontend/src/core/storage/index.ts
similarity index 64%
copy from superset-frontend/src/core/extensions/index.ts
copy to superset-frontend/src/core/storage/index.ts
index ae49a135aed..b26f9a411f8 100644
--- a/superset-frontend/src/core/extensions/index.ts
+++ b/superset-frontend/src/core/storage/index.ts
@@ -16,16 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { extensions as extensionsApi } from '@apache-superset/core';
-import ExtensionsLoader from 'src/extensions/ExtensionsLoader';
-const getExtension: typeof extensionsApi.getExtension = id =>
- ExtensionsLoader.getInstance().getExtension(id);
-
-const getAllExtensions: typeof extensionsApi.getAllExtensions = () =>
- ExtensionsLoader.getInstance().getExtensions();
+/**
+ * Storage implementation for extensions.
+ * Extensions access storage via getContext().storage which is bound to each extension.
+ */
-export const extensions: typeof extensionsApi = {
- getExtension,
- getAllExtensions,
-};
+export { createBrowserStorage } from './localState';
+export { createEphemeralState } from './ephemeralState';
+export { createPersistentState } from './persistentState';
diff --git a/superset-frontend/src/core/storage/localState.test.ts b/superset-frontend/src/core/storage/localState.test.ts
new file mode 100644
index 00000000000..1a446a34363
--- /dev/null
+++ b/superset-frontend/src/core/storage/localState.test.ts
@@ -0,0 +1,96 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import getBootstrapData from 'src/utils/getBootstrapData';
+import { createBrowserStorage } from './localState';
+
+jest.mock('src/utils/getBootstrapData');
+const mockedGetBootstrapData = getBootstrapData as jest.Mock;
+
+beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ mockedGetBootstrapData.mockReturnValue({ user: { userId: 42 } });
+});
+
+test('get returns null when key is not in storage', async () => {
+ const store = createBrowserStorage(localStorage, 'org.ext');
+ const result = await store.get('missing');
+ expect(result).toBeNull();
+});
+
+test('get returns parsed value for user-scoped key', async () => {
+ localStorage.setItem(
+ 'superset-ext:org.ext:user:42:prefs',
+ JSON.stringify({ theme: 'dark' }),
+ );
+ const store = createBrowserStorage(localStorage, 'org.ext');
+ const result = await store.get('prefs');
+ expect(result).toEqual({ theme: 'dark' });
+});
+
+test('set writes value under user-scoped namespaced key', async () => {
+ const store = createBrowserStorage(localStorage, 'org.ext');
+ await store.set('prefs', { theme: 'dark' });
+ expect(localStorage.getItem('superset-ext:org.ext:user:42:prefs')).toBe(
+ JSON.stringify({ theme: 'dark' }),
+ );
+});
+
+test('remove deletes user-scoped key', async () => {
+ localStorage.setItem('superset-ext:org.ext:user:42:prefs', '{}');
+ const store = createBrowserStorage(localStorage, 'org.ext');
+ await store.remove('prefs');
+ expect(localStorage.getItem('superset-ext:org.ext:user:42:prefs')).toBeNull();
+});
+
+test('get throws when user is not authenticated', async () => {
+ mockedGetBootstrapData.mockReturnValue({ user: {} });
+ const store = createBrowserStorage(localStorage, 'org.ext');
+ await expect(store.get('key')).rejects.toThrow('authenticated user');
+});
+
+test('set throws when user is not authenticated', async () => {
+ mockedGetBootstrapData.mockReturnValue({ user: {} });
+ const store = createBrowserStorage(localStorage, 'org.ext');
+ await expect(store.set('key', 'value')).rejects.toThrow('authenticated user');
+});
+
+test('different extensions use isolated keys', async () => {
+ const store1 = createBrowserStorage(localStorage, 'org.ext1');
+ const store2 = createBrowserStorage(localStorage, 'org.ext2');
+ await store1.set('key', 'value1');
+ await store2.set('key', 'value2');
+ expect(await store1.get('key')).toBe('value1');
+ expect(await store2.get('key')).toBe('value2');
+});
+
+test('different users use isolated keys', async () => {
+ const store = createBrowserStorage(localStorage, 'org.ext');
+ mockedGetBootstrapData.mockReturnValue({ user: { userId: 1 } });
+ await store.set('key', 'user1-value');
+ mockedGetBootstrapData.mockReturnValue({ user: { userId: 2 } });
+ expect(await store.get('key')).toBeNull();
+});
+
+test('works with sessionStorage', async () => {
+ const store = createBrowserStorage(sessionStorage, 'org.ext');
+ await store.set('step', 3);
+ expect(await store.get('step')).toBe(3);
+});
diff --git a/superset-frontend/src/core/storage/localState.ts b/superset-frontend/src/core/storage/localState.ts
new file mode 100644
index 00000000000..b8307db8372
--- /dev/null
+++ b/superset-frontend/src/core/storage/localState.ts
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { JsonValue, StorageAccessor } from '@apache-superset/core/storage';
+import getBootstrapData from 'src/utils/getBootstrapData';
+
+const KEY_PREFIX = 'superset-ext';
+
+function getCurrentUserId(): number {
+ const bootstrapData = getBootstrapData();
+ const userId = bootstrapData?.user?.userId;
+ if (userId === undefined) {
+ throw new Error('Storage APIs require an authenticated user.');
+ }
+ return userId;
+}
+
+function buildKey(...parts: (string | number)[]): string {
+ return [KEY_PREFIX, ...parts].join(':');
+}
+
+/**
+ * Create browser storage (localStorage/sessionStorage) bound to an extension ID.
+ */
+export function createBrowserStorage(
+ storage: Storage,
+ extensionId: string,
+): StorageAccessor {
+ return {
+ async get<T = JsonValue>(key: string): Promise<T | null> {
+ const userId = getCurrentUserId();
+ const storageKey = buildKey(extensionId, 'user', userId, key);
+ const value = storage.getItem(storageKey);
+ return value ? (JSON.parse(value) as T) : null;
+ },
+ async set<T = JsonValue>(key: string, value: T): Promise<void> {
+ const userId = getCurrentUserId();
+ const storageKey = buildKey(extensionId, 'user', userId, key);
+ const serialized = JSON.stringify(value);
+ if (serialized === undefined) {
+ throw new Error('Storage value must be JSON-serializable.');
+ }
+ storage.setItem(storageKey, serialized);
+ },
+ async remove(key: string): Promise<void> {
+ const userId = getCurrentUserId();
+ const storageKey = buildKey(extensionId, 'user', userId, key);
+ storage.removeItem(storageKey);
+ },
+ };
+}
diff --git a/superset-frontend/src/core/storage/persistentState.test.ts b/superset-frontend/src/core/storage/persistentState.test.ts
new file mode 100644
index 00000000000..47049fe6f65
--- /dev/null
+++ b/superset-frontend/src/core/storage/persistentState.test.ts
@@ -0,0 +1,261 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { SupersetClient } from '@superset-ui/core';
+import { createPersistentState } from './persistentState';
+
+jest.mock('@superset-ui/core', () => ({
+ SupersetClient: {
+ get: jest.fn(),
+ put: jest.fn(),
+ delete: jest.fn(),
+ },
+}));
+
+const mockGet = SupersetClient.get as jest.Mock;
+const mockPut = SupersetClient.put as jest.Mock;
+const mockDelete = SupersetClient.delete as jest.Mock;
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockGet.mockResolvedValue({ json: { result: null } });
+ mockPut.mockResolvedValue({});
+ mockDelete.mockResolvedValue({});
+});
+
+test('get calls correct URL with publisher/name pattern', async () => {
+ const store = createPersistentState('myorg.myext');
+ await store.get('prefs');
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/persistent/prefs',
+ });
+});
+
+test('get returns result from response', async () => {
+ mockGet.mockResolvedValue({ json: { result: { theme: 'dark' } } });
+ const store = createPersistentState('myorg.myext');
+ expect(await store.get('prefs')).toEqual({ theme: 'dark' });
+});
+
+test('get returns null when result is absent', async () => {
+ mockGet.mockResolvedValue({ json: {} });
+ const store = createPersistentState('myorg.myext');
+ expect(await store.get('key')).toBeNull();
+});
+
+test('set calls correct URL with value in body', async () => {
+ const store = createPersistentState('myorg.myext');
+ await store.set('prefs', { theme: 'dark' });
+ expect(mockPut).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/persistent/prefs',
+ body: JSON.stringify({
+ value: { theme: 'dark' },
+ encrypt: false,
+ codec: 'json',
+ isBinary: false,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+});
+
+test('set passes codec from options', async () => {
+ const store = createPersistentState('myorg.myext');
+ await store.set('prefs', 'sk-...', { codec: 'pickle' });
+ expect(mockPut).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/persistent/prefs',
+ body: JSON.stringify({
+ value: 'sk-...',
+ encrypt: false,
+ codec: 'pickle',
+ isBinary: false,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+});
+
+test('set does not base64-encode a Uint8Array value unless isBinary is set', async () => {
+ const store = createPersistentState('myorg.myext');
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
+ await store.set('icon', bytes);
+ const body = JSON.parse(mockPut.mock.calls[0][0].body);
+ expect(body.codec).toBe('json');
+ expect(body.value).toEqual({ 0: 0x89, 1: 0x50, 2: 0x4e, 3: 0x47 });
+ expect(body.isBinary).toBe(false);
+});
+
+test('set base64-encodes a Uint8Array value when isBinary is true, with no codec specified', async () => {
+ const store = createPersistentState('myorg.myext');
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
+ await store.set('icon', bytes, { isBinary: true });
+ const body = JSON.parse(mockPut.mock.calls[0][0].body);
+ expect(body.codec).toBe('binary');
+ expect(body.value).toBe(btoa('\x89PNG'));
+ expect(body.isBinary).toBe(true);
+});
+
+test('set base64-encodes a Uint8Array value when isBinary is true, even with an explicit codec', async () => {
+ const store = createPersistentState('myorg.myext');
+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
+ await store.set('icon', bytes, { codec: 'pickle', isBinary: true });
+ expect(mockPut).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/persistent/icon',
+ body: JSON.stringify({
+ value: btoa('\x89PNG'),
+ encrypt: false,
+ codec: 'pickle',
+ isBinary: true,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+});
+
+test('list calls correct URL with only page/pageSize as query params', async () => {
+ mockGet.mockResolvedValue({ json: { result: [], count: 0 } });
+ const store = createPersistentState('myorg.myext');
+ await store.list({ page: 0, pageSize: 10 });
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/persistent?page=0&page_size=10',
+ });
+});
+
+test('list returns entries and count from response', async () => {
+ mockGet.mockResolvedValue({
+ json: {
+ result: [
+ {
+ key: 'prefs',
+ value: { theme: 'dark' },
+ codec: 'json',
+ isBinary: false,
+ },
+ ],
+ count: 1,
+ },
+ });
+ const store = createPersistentState('myorg.myext');
+ const result = await store.list({ page: 0, pageSize: 10 });
+ expect(result.count).toBe(1);
+ expect(result.entries).toEqual([
+ { key: 'prefs', value: { theme: 'dark' }, codec: 'json', isBinary: false },
+ ]);
+});
+
+test('list returns empty entries and count 0 when result/count are absent', async () => {
+ mockGet.mockResolvedValue({ json: {} });
+ const store = createPersistentState('myorg.myext');
+ const result = await store.list({ page: 0, pageSize: 10 });
+ expect(result.entries).toEqual([]);
+ expect(result.count).toBe(0);
+});
+
+test('list passes filter and pagination options as query params', async () => {
+ mockGet.mockResolvedValue({ json: { result: [], count: 0 } });
+ const store = createPersistentState('myorg.myext');
+ await store.list({
+ resourceType: 'dashboard',
+ resourceUuid: 'uuid-1',
+ page: 2,
+ pageSize: 25,
+ });
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/persistent' +
+ '?resource_type=dashboard&resource_uuid=uuid-1&page=2&page_size=25',
+ });
+});
+
+test('shared.list appends ?shared=true', async () => {
+ mockGet.mockResolvedValue({ json: { result: [], count: 0 } });
+ const store = createPersistentState('myorg.myext');
+ await store.shared.list({ page: 0, pageSize: 10 });
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/persistent?shared=true&page=0&page_size=10',
+ });
+});
+
+test('shared.list combines ?shared=true with other query params', async () => {
+ mockGet.mockResolvedValue({ json: { result: [], count: 0 } });
+ const store = createPersistentState('myorg.myext');
+ await store.shared.list({ page: 1, pageSize: 10 });
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/persistent?shared=true&page=1&page_size=10',
+ });
+});
+
+test('remove calls correct URL', async () => {
+ const store = createPersistentState('myorg.myext');
+ await store.remove('prefs');
+ expect(mockDelete).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/myorg/myext/storage/persistent/prefs',
+ });
+});
+
+test('keys are URL-encoded', async () => {
+ const store = createPersistentState('myorg.myext');
+ await store.get('key/with/slashes');
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/persistent/key%2Fwith%2Fslashes',
+ });
+});
+
+test('publisher and name are URL-encoded', async () => {
+ const store = createPersistentState('my org.my ext');
+ await store.get('key');
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint: '/api/v1/extensions/my%20org/my%20ext/storage/persistent/key',
+ });
+});
+
+test('shared.get appends ?shared=true', async () => {
+ const store = createPersistentState('myorg.myext');
+ await store.shared.get('config');
+ expect(mockGet).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/persistent/config?shared=true',
+ });
+});
+
+test('shared.set appends ?shared=true', async () => {
+ const store = createPersistentState('myorg.myext');
+ await store.shared.set('config', { version: 2 });
+ expect(mockPut).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/persistent/config?shared=true',
+ body: JSON.stringify({
+ value: { version: 2 },
+ encrypt: false,
+ codec: 'json',
+ isBinary: false,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+});
+
+test('shared.remove appends ?shared=true', async () => {
+ const store = createPersistentState('myorg.myext');
+ await store.shared.remove('config');
+ expect(mockDelete).toHaveBeenCalledWith({
+ endpoint:
+ '/api/v1/extensions/myorg/myext/storage/persistent/config?shared=true',
+ });
+});
diff --git a/superset-frontend/src/core/storage/persistentState.ts b/superset-frontend/src/core/storage/persistentState.ts
new file mode 100644
index 00000000000..af45d01340c
--- /dev/null
+++ b/superset-frontend/src/core/storage/persistentState.ts
@@ -0,0 +1,143 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type {
+ JsonValue,
+ PersistentListOptions,
+ PersistentListResult,
+ PersistentSetOptions,
+ PersistentStorageAccessor,
+ PersistentStorageTier,
+} from '@apache-superset/core/storage';
+import { SupersetClient } from '@superset-ui/core';
+import { resolveSetPayload } from './binaryCodec';
+
+/**
+ * Create persistent state (database-backed) bound to an extension ID.
+ */
+export function createPersistentState(
+ extensionId: string,
+): PersistentStorageTier {
+ const [publisher, name] = extensionId.split('.');
+
+ const buildUrl = (key: string, shared?: boolean): string => {
+ const encodedPublisher = encodeURIComponent(publisher);
+ const encodedName = encodeURIComponent(name);
+ const encodedKey = encodeURIComponent(key);
+ const url = `/api/v1/extensions/${encodedPublisher}/${encodedName}/storage/persistent/${encodedKey}`;
+ return shared ? `${url}?shared=true` : url;
+ };
+
+ const buildListUrl = (
+ options: PersistentListOptions,
+ isShared?: boolean,
+ ): string => {
+ const encodedPublisher = encodeURIComponent(publisher);
+ const encodedName = encodeURIComponent(name);
+ const url = `/api/v1/extensions/${encodedPublisher}/${encodedName}/storage/persistent`;
+ const params = new URLSearchParams();
+ if (isShared) params.set('shared', 'true');
+ if (options.resourceType) params.set('resource_type', options.resourceType);
+ if (options.resourceUuid) params.set('resource_uuid', options.resourceUuid);
+ params.set('page', String(options.page));
+ params.set('page_size', String(options.pageSize));
+ const query = params.toString();
+ return query ? `${url}?${query}` : url;
+ };
+
+ const list = async <T = JsonValue>(
+ options: PersistentListOptions,
+ isShared: boolean,
+ ): Promise<PersistentListResult<T>> => {
+ const response = await SupersetClient.get({
+ endpoint: buildListUrl(options, isShared),
+ });
+ return {
+ entries: response.json?.result ?? [],
+ count: response.json?.count ?? 0,
+ };
+ };
+
+ const shared: PersistentStorageAccessor = {
+ async get<T = JsonValue>(key: string): Promise<T | null> {
+ const response = await SupersetClient.get({
+ endpoint: buildUrl(key, true),
+ });
+ return (response.json?.result ?? null) as T | null;
+ },
+ async set<T = JsonValue>(
+ key: string,
+ value: T,
+ options?: PersistentSetOptions,
+ ): Promise<void> {
+ const payload = resolveSetPayload(value, options);
+ await SupersetClient.put({
+ endpoint: buildUrl(key, true),
+ body: JSON.stringify({
+ value: payload.value,
+ encrypt: options?.encrypt ?? false,
+ codec: payload.codec,
+ isBinary: payload.isBinary,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+ },
+ async list<T = JsonValue>(
+ options: PersistentListOptions,
+ ): Promise<PersistentListResult<T>> {
+ return list<T>(options, true);
+ },
+ async remove(key: string): Promise<void> {
+ await SupersetClient.delete({ endpoint: buildUrl(key, true) });
+ },
+ };
+
+ return {
+ async get<T = JsonValue>(key: string): Promise<T | null> {
+ const response = await SupersetClient.get({ endpoint: buildUrl(key) });
+ return (response.json?.result ?? null) as T | null;
+ },
+ async set<T = JsonValue>(
+ key: string,
+ value: T,
+ options?: PersistentSetOptions,
+ ): Promise<void> {
+ const payload = resolveSetPayload(value, options);
+ await SupersetClient.put({
+ endpoint: buildUrl(key),
+ body: JSON.stringify({
+ value: payload.value,
+ encrypt: options?.encrypt ?? false,
+ codec: payload.codec,
+ isBinary: payload.isBinary,
+ }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+ },
+ async list<T = JsonValue>(
+ options: PersistentListOptions,
+ ): Promise<PersistentListResult<T>> {
+ return list<T>(options, false);
+ },
+ async remove(key: string): Promise<void> {
+ await SupersetClient.delete({ endpoint: buildUrl(key) });
+ },
+ shared,
+ };
+}
diff --git a/superset-frontend/src/extensions/ExtensionContext.test.ts b/superset-frontend/src/extensions/ExtensionContext.test.ts
new file mode 100644
index 00000000000..eef97cde887
--- /dev/null
+++ b/superset-frontend/src/extensions/ExtensionContext.test.ts
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { common } from '@apache-superset/core';
+import { createExtensionContext } from './ExtensionContext';
+
+jest.mock('src/utils/getBootstrapData', () => ({
+ __esModule: true,
+ default: jest.fn(() => ({ user: { userId: 1 } })),
+}));
+
+const createMockExtension = (id: string): common.Extension =>
+ ({
+ id,
+ name: `test-${id}`,
+ publisher: 'test',
+ }) as unknown as common.Extension;
+
+test('createExtensionContext creates context with extension metadata', () => {
+ const extension = createMockExtension('test.ext');
+ const ctx = createExtensionContext(extension);
+
+ expect(ctx.extension).toBe(extension);
+ expect(ctx.extension.id).toBe('test.ext');
+});
+
+test('createExtensionContext creates context with lazy storage', () => {
+ const extension = createMockExtension('test.ext');
+ const ctx = createExtensionContext(extension);
+
+ expect(ctx.storage).toBeDefined();
+ expect(ctx.storage.local).toBeDefined();
+ expect(ctx.storage.session).toBeDefined();
+ expect(ctx.storage.ephemeral).toBeDefined();
+});
+
+test('different extensions get different contexts', () => {
+ const ctx1 = createExtensionContext(createMockExtension('org1.ext1'));
+ const ctx2 = createExtensionContext(createMockExtension('org2.ext2'));
+
+ expect(ctx1.extension.id).toBe('org1.ext1');
+ expect(ctx2.extension.id).toBe('org2.ext2');
+ expect(ctx1).not.toBe(ctx2);
+});
diff --git a/superset-frontend/src/extensions/ExtensionContext.ts b/superset-frontend/src/extensions/ExtensionContext.ts
new file mode 100644
index 00000000000..0e1f2a3c53f
--- /dev/null
+++ b/superset-frontend/src/extensions/ExtensionContext.ts
@@ -0,0 +1,78 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import type {
+ common,
+ extensions as extensionsApi,
+} from '@apache-superset/core';
+import {
+ createBrowserStorage,
+ createEphemeralState,
+ createPersistentState,
+} from 'src/core/storage';
+
+type Extension = common.Extension;
+type ExtensionContextType = extensionsApi.ExtensionContext;
+
+/**
+ * Extension context with lazy-initialized services bound to the extension ID.
+ */
+class ExtensionContext implements ExtensionContextType {
+ readonly extension: Extension;
+
+ private _storage?: ExtensionContextType['storage'];
+
+ constructor(extension: Extension) {
+ this.extension = extension;
+ }
+
+ get storage(): ExtensionContextType['storage'] {
+ if (!this._storage) {
+ const { id } = this.extension;
+ // `local`/`session` are defined as lazy accessors, not eagerly
+ // constructed values: they read the global `localStorage`/
+ // `sessionStorage` bindings, which can throw in environments where
+ // Web Storage is unavailable or blocked (e.g. some sandboxed
+ // iframes). Deferring that access to per-tier property access means
+ // a blocked browser storage API only breaks `ctx.storage.local`/
+ // `.session` for extensions that actually use them, rather than
+ // preventing access to the server-backed `ephemeral`/`persistent`
+ // tiers as well.
+ this._storage = {
+ get local() {
+ return createBrowserStorage(localStorage, id);
+ },
+ get session() {
+ return createBrowserStorage(sessionStorage, id);
+ },
+ ephemeral: createEphemeralState(id),
+ persistent: createPersistentState(id),
+ };
+ }
+ return this._storage!;
+ }
+}
+
+/**
+ * Create an extension context.
+ */
+export function createExtensionContext(
+ extension: Extension,
+): ExtensionContextType {
+ return new ExtensionContext(extension);
+}
diff --git a/superset-frontend/src/extensions/ExtensionsLoader.test.ts b/superset-frontend/src/extensions/ExtensionsLoader.test.ts
index a02e2515e33..080dd14ede3 100644
--- a/superset-frontend/src/extensions/ExtensionsLoader.test.ts
+++ b/superset-frontend/src/extensions/ExtensionsLoader.test.ts
@@ -18,10 +18,8 @@
*/
import { SupersetClient } from '@superset-ui/core';
import { logging } from '@apache-superset/core/utils';
-import type { common as core } from '@apache-superset/core';
-import ExtensionsLoader from './ExtensionsLoader';
-
-type Extension = core.Extension;
+import ExtensionsLoader, { LoadedExtension } from './ExtensionsLoader';
+import type { Namespaces } from './Namespaces';
const mockApplicationRoot = jest.fn<string, []>(() => '');
@@ -36,7 +34,9 @@ jest.mock('src/utils/getBootstrapData', () => {
};
});
-function createMockExtension(overrides: Partial<Extension> = {}): Extension {
+function createMockExtension(
+ overrides: Partial<LoadedExtension> = {},
+): LoadedExtension {
return {
id: 'test-extension',
name: 'Test Extension',
@@ -48,9 +48,56 @@ function createMockExtension(overrides: Partial<Extension> = {}): Extension {
};
}
+// Simulate what real webpack does when __webpack_init_sharing__ runs: it
+// registers the host's own eagerly-provided @apache-superset/core versions
+// into the share scope.
+function mockWebpackSharing(
+ coreVersions: Record<string, WebpackSharedScopeModule> = {},
+) {
+ globalThis.__webpack_share_scopes__ = { default: {} };
+ globalThis.__webpack_init_sharing__ = jest.fn().mockImplementation(() => {
+ globalThis.__webpack_share_scopes__.default['@apache-superset/core'] =
+ coreVersions;
+ return Promise.resolve();
+ });
+}
+
+function cleanupWebpackSharing() {
+ delete (globalThis as { __webpack_init_sharing__?: unknown })
+ .__webpack_init_sharing__;
+ delete (globalThis as { __webpack_share_scopes__?: unknown })
+ .__webpack_share_scopes__;
+}
+
+// Intercept script element creation so onload fires synchronously in jsdom.
+function mockRemoteEntryLoad() {
+ return jest
+ .spyOn(document.head, 'appendChild')
+ .mockImplementation((el: Node) => {
+ if (el instanceof HTMLScriptElement && el.onload) {
+ (el as HTMLScriptElement).onload!(new Event('load'));
+ }
+ return el;
+ });
+}
+
beforeEach(() => {
- (ExtensionsLoader as any).instance = undefined;
+ (ExtensionsLoader as unknown as { instance?: ExtensionsLoader }).instance =
+ undefined;
mockApplicationRoot.mockReturnValue('');
+ // Reset window.superset to a base object before each test, including a
+ // shared singleton (commands) to verify identity is preserved across
+ // per-extension scoped copies.
+ window.superset = {
+ commands: { registerCommand: jest.fn() },
+ extensions: {
+ getContext: () => {
+ throw new Error('No extension context');
+ },
+ getExtension: () => undefined,
+ getAllExtensions: () => [],
+ },
+ } as unknown as Namespaces;
});
/**
@@ -170,6 +217,214 @@ test('logs success after initializeExtensions completes', async () => {
infoSpy.mockRestore();
});
+test('logs partial failure count when some extensions fail to initialize', async () => {
+ const loader = ExtensionsLoader.getInstance();
+ const infoSpy = jest.spyOn(logging, 'info').mockImplementation();
+ jest.spyOn(SupersetClient, 'get').mockResolvedValue({
+ json: {
+ result: [
+ createMockExtension({ id: 'good-ext', remoteEntry: '' }),
+ createMockExtension({
+ id: 'broken-ext',
+ remoteEntry: 'http://broken-url/remoteEntry.js',
+ }),
+ ],
+ },
+ } as any);
+ const appendChildSpy = jest
+ .spyOn(document.head, 'appendChild')
+ .mockImplementation((element: Node) => {
+ if (element instanceof HTMLScriptElement && element.onerror) {
+ setTimeout(() => {
+ (element.onerror as any)('Script load error');
+ }, 0);
+ }
+ return element;
+ });
+
+ await loader.initializeExtensions();
+
+ expect(infoSpy).toHaveBeenCalledWith(
+ expect.stringContaining('1 of 2 extension(s) failing'),
+ );
+ expect(loader.getExtension('good-ext')).toBeDefined();
+ expect(loader.getExtension('broken-ext')).toBeUndefined();
+
+ infoSpy.mockRestore();
+ appendChildSpy.mockRestore();
+});
+
+test('each extension gets an isolated getContext via module federation custom scope', async () => {
+ const loader = ExtensionsLoader.getInstance();
+
+ // Capture the scoped @apache-superset/core instance each container receives
+ const capturedCoreModules: Array<typeof import('@apache-superset/core')> = [];
+
+ const makeContainer = () => ({
+ init: jest.fn().mockImplementation(async (scope: WebpackSharedScope) => {
+ // Simulate what a real container does: resolve the module from the scope
+ const moduleFactory = await scope['@apache-superset/core']['0.1.0'].get();
+ capturedCoreModules.push(
+ moduleFactory() as typeof import('@apache-superset/core'),
+ );
+ }),
+ get: jest.fn().mockResolvedValue(() => {}),
+ });
+
+ const appendChildSpy = mockRemoteEntryLoad();
+
+ // Simulate what real webpack does when __webpack_init_sharing__ runs:
+ // it registers the host's own eagerly-provided @apache-superset/core
+ // into the share scope under its resolved version key.
+ mockWebpackSharing({
+ '0.1.0': {
+ get: () => Promise.resolve(() => ({})),
+ loaded: true,
+ eager: true,
+ },
+ });
+
+ const ext1 = createMockExtension({
+ id: 'org.ext1',
+ remoteEntry: 'http://ext1/remoteEntry.js',
+ });
+ const ext2 = createMockExtension({
+ id: 'org.ext2',
+ remoteEntry: 'http://ext2/remoteEntry.js',
+ });
+
+ (window as any).airbnb_ext1 = makeContainer();
+ (window as any).airbnb_ext2 = makeContainer();
+
+ await Promise.all([
+ loader.initializeExtension({
+ ...ext1,
+ moduleFederationName: 'airbnb_ext1',
+ }),
+ loader.initializeExtension({
+ ...ext2,
+ moduleFederationName: 'airbnb_ext2',
+ }),
+ ]);
+
+ expect(capturedCoreModules).toHaveLength(2);
+ // Each container received a different @apache-superset/core instance
+ expect(capturedCoreModules[0]).not.toBe(capturedCoreModules[1]);
+ // Each instance has getContext bound to the right extension
+ expect(capturedCoreModules[0].extensions.getContext().extension.id).toBe(
+ 'org.ext1',
+ );
+ expect(capturedCoreModules[1].extensions.getContext().extension.id).toBe(
+ 'org.ext2',
+ );
+ // Shared APIs are the same underlying objects
+ expect(capturedCoreModules[0].commands).toBe(capturedCoreModules[1].commands);
+
+ appendChildSpy.mockRestore();
+ cleanupWebpackSharing();
+});
+
+test('throws when the container is missing from window', async () => {
+ const loader = ExtensionsLoader.getInstance();
+ const errorSpy = jest.spyOn(logging, 'error').mockImplementation();
+ const appendChildSpy = mockRemoteEntryLoad();
+ mockWebpackSharing({
+ '0.1.0': { get: () => Promise.resolve(() => ({})) },
+ });
+
+ const ext = createMockExtension({
+ id: 'missing-container-ext',
+ remoteEntry: 'http://ext/remoteEntry.js',
+ moduleFederationName: 'nonexistent_container',
+ });
+
+ const succeeded = await loader.initializeExtension(ext);
+
+ expect(succeeded).toBe(false);
+ expect(errorSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Failed to initialize extension'),
+ expect.objectContaining({
+ message: expect.stringContaining(
+ 'Extension container "nonexistent_container" was not found',
+ ),
+ }),
+ );
+
+ errorSpy.mockRestore();
+ appendChildSpy.mockRestore();
+ cleanupWebpackSharing();
+});
+
+test('throws when the container does not expose init/get', async () => {
+ const loader = ExtensionsLoader.getInstance();
+ const errorSpy = jest.spyOn(logging, 'error').mockImplementation();
+ const appendChildSpy = mockRemoteEntryLoad();
+ mockWebpackSharing({
+ '0.1.0': { get: () => Promise.resolve(() => ({})) },
+ });
+
+ (window as any).malformed_container = { init: jest.fn() }; // missing `get`
+
+ const ext = createMockExtension({
+ id: 'malformed-container-ext',
+ remoteEntry: 'http://ext/remoteEntry.js',
+ moduleFederationName: 'malformed_container',
+ });
+
+ const succeeded = await loader.initializeExtension(ext);
+
+ expect(succeeded).toBe(false);
+ expect(errorSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Failed to initialize extension'),
+ expect.objectContaining({
+ message: expect.stringContaining(
+ 'does not expose the expected Module Federation runtime',
+ ),
+ }),
+ );
+
+ errorSpy.mockRestore();
+ appendChildSpy.mockRestore();
+ delete (window as any).malformed_container;
+ cleanupWebpackSharing();
+});
+
+test('throws when the host @apache-superset/core version cannot be resolved', async () => {
+ const loader = ExtensionsLoader.getInstance();
+ const errorSpy = jest.spyOn(logging, 'error').mockImplementation();
+ const appendChildSpy = mockRemoteEntryLoad();
+ // No '@apache-superset/core' entry gets registered in the share scope.
+ mockWebpackSharing();
+
+ (window as any).unresolved_version_container = {
+ init: jest.fn(),
+ get: jest.fn().mockResolvedValue(() => {}),
+ };
+
+ const ext = createMockExtension({
+ id: 'unresolved-version-ext',
+ remoteEntry: 'http://ext/remoteEntry.js',
+ moduleFederationName: 'unresolved_version_container',
+ });
+
+ const succeeded = await loader.initializeExtension(ext);
+
+ expect(succeeded).toBe(false);
+ expect(errorSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Failed to initialize extension'),
+ expect.objectContaining({
+ message: expect.stringContaining(
+ "Could not resolve the host's @apache-superset/core version",
+ ),
+ }),
+ );
+
+ errorSpy.mockRestore();
+ appendChildSpy.mockRestore();
+ delete (window as any).unresolved_version_container;
+ cleanupWebpackSharing();
+});
+
// Subdirectory regression (gap review 2026-06-10): the backend emits a
// router-relative remoteEntry URL; assigning it raw to `script.src` resolved
// it against the domain root, 404ing every extension under a subdirectory
diff --git a/superset-frontend/src/extensions/ExtensionsLoader.ts b/superset-frontend/src/extensions/ExtensionsLoader.ts
index f4abaf5fdbb..80b396fa484 100644
--- a/superset-frontend/src/extensions/ExtensionsLoader.ts
+++ b/superset-frontend/src/extensions/ExtensionsLoader.ts
@@ -20,9 +20,39 @@ import { SupersetClient } from '@superset-ui/core';
import { logging } from '@apache-superset/core/utils';
import type { common as core } from '@apache-superset/core';
import { makeUrl } from 'src/utils/navigationUtils';
+import 'src/extensions/Namespaces';
+import { createExtensionContext } from './ExtensionContext';
type Extension = core.Extension;
+/**
+ * An extension as returned by the extensions API, with loader-internal
+ * fields used to fetch and initialize its module. These fields are not
+ * part of the public `Extension` metadata exposed to extension authors,
+ * and are only present for extensions that declare a frontend bundle.
+ */
+export interface LoadedExtension extends Extension {
+ /** URL to the extension's remote entry script. */
+ remoteEntry?: string;
+ /** Webpack Module Federation container name (maps to window[name]). */
+ moduleFederationName?: string;
+}
+
+/**
+ * Narrows an unknown `window[containerName]` lookup to a
+ * `WebpackFederationContainer`, verifying it exposes the runtime methods
+ * we depend on rather than trusting an assertion.
+ */
+function isWebpackFederationContainer(
+ value: unknown,
+): value is WebpackFederationContainer {
+ const container = value as Partial<WebpackFederationContainer> | null;
+ return (
+ typeof container?.init === 'function' &&
+ typeof container?.get === 'function'
+ );
+}
+
/**
* Loads extension modules via webpack module federation.
*
@@ -33,7 +63,7 @@ type Extension = core.Extension;
class ExtensionsLoader {
private static instance: ExtensionsLoader;
- private extensionIndex: Map<string, Extension> = new Map();
+ private extensionIndex: Map<string, LoadedExtension> = new Map();
private initializationPromise: Promise<void> | null = null;
@@ -66,13 +96,19 @@ class ExtensionsLoader {
const response = await SupersetClient.get({
endpoint: '/api/v1/extensions/',
});
- const extensions: Extension[] = response.json.result;
- await Promise.all(
- extensions.map(async extension => {
- await this.initializeExtension(extension);
- }),
+ const extensions: LoadedExtension[] = response.json.result;
+ const results = await Promise.all(
+ extensions.map(ext => this.initializeExtension(ext)),
);
- logging.info('Extensions initialized successfully.');
+ if (results.every(Boolean)) {
+ logging.info('Extensions initialized successfully.');
+ } else {
+ const failedCount = results.filter(succeeded => !succeeded).length;
+ logging.info(
+ `Extensions initialized with ${failedCount} of ` +
+ `${extensions.length} extension(s) failing. See errors above.`,
+ );
+ }
} catch (error) {
logging.error('Error setting up extensions:', error);
}
@@ -85,18 +121,23 @@ class ExtensionsLoader {
* If the extension has a remote entry, loads the module (which triggers
* side-effect registrations for commands, views, menus, and editors).
* @param extension The extension to initialize.
+ * @returns Whether the extension was initialized successfully.
*/
- public async initializeExtension(extension: Extension) {
+ public async initializeExtension(
+ extension: LoadedExtension,
+ ): Promise<boolean> {
try {
if (extension.remoteEntry) {
await this.loadModule(extension);
}
this.extensionIndex.set(extension.id, extension);
+ return true;
} catch (error) {
logging.error(
`Failed to initialize extension ${extension.name}\n`,
error,
);
+ return false;
}
}
@@ -105,8 +146,11 @@ class ExtensionsLoader {
* The module's top-level side effects fire contribution registrations.
* @param extension The extension to load.
*/
- private async loadModule(extension: Extension): Promise<void> {
+ private async loadModule(extension: LoadedExtension): Promise<void> {
const { remoteEntry, id } = extension;
+ if (!remoteEntry) {
+ throw new Error(`Extension ${id} has no remote entry to load.`);
+ }
// Load the remote entry script. The backend emits a router-relative
// remoteEntry URL; `makeUrl` applies the application root for
@@ -142,17 +186,64 @@ class ExtensionsLoader {
});
// Initialize Webpack module federation
- // @ts-expect-error
await __webpack_init_sharing__('default');
- // Use moduleFederationName (camelCase) for webpack container access, fallback to id for compatibility
- const containerName = (extension as any).moduleFederationName || id;
- const container = (window as any)[containerName];
+ // Use moduleFederationName for webpack container access, fallback to id for compatibility
+ const containerName = extension.moduleFederationName || id;
+ const container = (window as unknown as Record<string, unknown>)[
+ containerName
+ ];
+ if (!isWebpackFederationContainer(container)) {
+ throw new Error(
+ `Extension container "${containerName}" was not found on window, or ` +
+ 'does not expose the expected Module Federation runtime ' +
+ '(init/get). This may indicate the remote entry failed to ' +
+ 'register itself, or a webpack version mismatch.',
+ );
+ }
- // @ts-expect-error
- await container.init(__webpack_share_scopes__.default);
+ // Build a custom scope that injects a per-extension instance of @apache-superset/core
+ // with getContext pre-bound to this extension's isolated context. All other exports
+ // (commands, views, menus, etc.) are references to the same shared host singletons,
+ // sourced from window.superset (the real implementations wired in ExtensionsStartup),
+ // not the @apache-superset/core package itself, which only contains type-only stubs.
+ // Module federation caches the resolved module per container, so every import of
+ // @apache-superset/core inside this extension — no matter when it evaluates —
+ // receives the same pre-bound instance. Parallel loading is safe because each
+ // container gets its own scope with its own resolved module instance.
+ const context = createExtensionContext(extension);
+ const scopedCore = {
+ ...window.superset,
+ extensions: {
+ ...window.superset.extensions,
+ getContext: () => context,
+ },
+ };
+ // Reuse the version key webpack already resolved for the host's own
+ // @apache-superset/core shared module, rather than recomputing it, so
+ // this entry always matches what the runtime considers the real one.
+ const sharedScope = __webpack_share_scopes__.default ?? {};
+ const existingCoreVersions = sharedScope['@apache-superset/core'] ?? {};
+ const supersetCoreVersion = Object.keys(existingCoreVersions)[0];
+ if (!supersetCoreVersion) {
+ throw new Error(
+ "Could not resolve the host's @apache-superset/core version " +
+ 'from the webpack share scope. Ensure __webpack_init_sharing__ ' +
+ 'has registered the host module before loading extensions.',
+ );
+ }
+ const customScope = {
+ ...sharedScope,
+ '@apache-superset/core': {
+ [supersetCoreVersion]: {
+ get: () => Promise.resolve(() => scopedCore),
+ loaded: true,
+ eager: true,
+ },
+ },
+ };
+ await container.init(customScope);
const factory = await container.get('./index');
- // Execute the module factory - side effects fire registrations
factory();
}
diff --git a/superset-frontend/src/extensions/webpackFederation.d.ts b/superset-frontend/src/extensions/webpackFederation.d.ts
new file mode 100644
index 00000000000..9cd71a19d9b
--- /dev/null
+++ b/superset-frontend/src/extensions/webpackFederation.d.ts
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Ambient types for webpack Module Federation runtime internals.
+ *
+ * `ModuleFederationPlugin` (`webpack/types.d.ts`) only types plugin
+ * *configuration*; the runtime globals and container shape it emits
+ * (`__webpack_init_sharing__`, `__webpack_share_scopes__`, and the
+ * `{ init, get }` container interface assigned to `window[containerName]`)
+ * are not part of webpack's public API and ship with no types of their own.
+ * The shape below documents the "dynamic remote container" pattern from
+ * https://webpack.js.org/concepts/module-federation/#dynamic-remote-containers,
+ * which is the only part of this contract webpack's docs commit to.
+ *
+ * `src/extensions/ExtensionsLoader.ts` is the sole consumer. If a webpack
+ * upgrade changes this runtime shape, this is the single place to update.
+ */
+
+/**
+ * A single shared-module entry within a Module Federation share scope.
+ */
+interface WebpackSharedScopeModule {
+ get: () => Promise<() => unknown>;
+ loaded?: boolean;
+ eager?: boolean;
+}
+
+/**
+ * A share scope: shared package name -> resolved version -> module entry.
+ */
+type WebpackSharedScope = Record<
+ string,
+ Record<string, WebpackSharedScopeModule>
+>;
+
+/**
+ * The runtime interface exposed by a Module Federation remote container,
+ * assigned to `window[containerName]` once its remoteEntry script has loaded.
+ */
+interface WebpackFederationContainer {
+ init(shareScope: WebpackSharedScope): Promise<void>;
+ get(request: string): Promise<() => unknown>;
+}
+
+declare function __webpack_init_sharing__(scopeName: string): Promise<void>;
+declare var __webpack_share_scopes__: Record<string, WebpackSharedScope>;
diff --git a/superset-frontend/webpack.config.js b/superset-frontend/webpack.config.js
index f6896d2cff3..e9043ab2004 100644
--- a/superset-frontend/webpack.config.js
+++ b/superset-frontend/webpack.config.js
@@ -186,6 +186,10 @@ const plugins = [
requiredVersion: packageConfig.dependencies.antd,
eager: true,
},
+ '@apache-superset/core': {
+ singleton: true,
+ eager: true,
+ },
},
}),
];
diff --git a/superset/config.py b/superset/config.py
index ec66e4a402f..61fddd53e4e 100644
--- a/superset/config.py
+++ b/superset/config.py
@@ -1370,6 +1370,42 @@ EXPLORE_FORM_DATA_CACHE_CONFIG: CacheConfig = {
"CODEC": JsonKeyValueCodec(),
}
+# Extension Tier 2: Ephemeral State - Server-side cache with TTL.
+# Short-lived KV storage that automatically expires. Not guaranteed to
+# survive server restarts. Use for temporary state like job progress,
+# intermediate results, or cross-request state. Can be replaced by any
+# `Flask-Caching` backend (e.g. RedisCache for production).
+EXTENSIONS_EPHEMERAL_STORAGE: CacheConfig = {
+ "CACHE_TYPE": "SupersetMetastoreCache",
+ # Maximum TTL (in seconds) that clients may request. Requests exceeding
+ # this value are rejected. Defaults to 7 days.
+ "MAX_TTL": int(timedelta(days=7).total_seconds()),
+ # Maximum size (in bytes) of a single stored value. Requests exceeding
+ # this value are rejected. Defaults to 100 KB.
+ "MAX_VALUE_SIZE": 100 * 1024,
+ # The following parameter only applies to `MetastoreCache`:
+ # How should entries be serialized/deserialized?
+ "CODEC": JsonKeyValueCodec(),
+}
+
+# Extension Tier 3: Persistent State - Database storage.
+# Durable KV storage backed by a dedicated database table (`extension_storage`).
+# Survives server restarts, cache evictions, and browser clears.
+EXTENSIONS_PERSISTENT_STORAGE: dict[str, Any] = {
+ # Maximum storage quota per extension in bytes (default: 100 MB)
+ "QUOTA_PER_EXTENSION": 100 * 1024 * 1024,
+ # Maximum size (in bytes) of a single stored value. Requests exceeding
+ # this value are rejected. Defaults to 1 MB.
+ "MAX_VALUE_SIZE": 1024 * 1024,
+ # Maximum combined value size (in bytes) that a single `list()` page may
+ # return. Requests whose page would exceed this are rejected rather than
+ # silently truncated. Defaults to 10 MB.
+ # NOTE: this response is consumed as JSON by the browser (REST API and
+ # frontend SDK), not just backend code — raising this substantially
+ # above the default risks client-side memory/parse-time issues.
+ "MAX_LIST_PAYLOAD_SIZE": 10 * 1024 * 1024,
+}
+
# store cache keys by datasource UID (via CacheKey) for custom processing/invalidation
STORE_CACHE_KEYS_IN_METADATA_DB = False
diff --git a/superset/core/api/core_api_injection.py b/superset/core/api/core_api_injection.py
index f2ab930b8bb..f2d48f31853 100644
--- a/superset/core/api/core_api_injection.py
+++ b/superset/core/api/core_api_injection.py
@@ -34,9 +34,6 @@ if TYPE_CHECKING:
from superset_core.rest_api.api import RestApi
-__all__ = ["initialize_core_api_dependencies"]
-
-
def inject_dao_implementations() -> None:
"""
Replace abstract DAO classes in superset_core common/queries/tasks daos with
@@ -191,9 +188,14 @@ def inject_rest_api_implementations() -> None:
if context:
# EXTENSION CONTEXT
- manifest = context.manifest
- base_path = f"/extensions/{manifest.publisher}/{manifest.name}"
- prefixed_id = f"extensions.{manifest.publisher}.{manifest.name}.{id}"
+ base_path = (
+ f"/extensions/{context.extension.publisher}/"
+ f"{context.extension.name}"
+ )
+ prefixed_id = (
+ f"extensions.{context.extension.publisher}."
+ f"{context.extension.name}.{id}"
+ )
else:
# HOST CONTEXT
@@ -261,8 +263,10 @@ def inject_semantic_layer_implementations() -> None:
) -> Callable[[Any], Any]:
def decorator(cls: Any) -> Any:
if context := context_module.get_current_extension_context():
- manifest = context.manifest
- prefixed_id = f"extensions.{manifest.publisher}.{manifest.name}.{id}"
+ prefixed_id = (
+ f"extensions.{context.extension.publisher}."
+ f"{context.extension.name}.{id}"
+ )
else:
prefixed_id = id
@@ -277,6 +281,40 @@ def inject_semantic_layer_implementations() -> None:
core_sl_module.semantic_layer = semantic_layer_impl # type: ignore[assignment]
+def inject_storage_implementations() -> None:
+ """
+ Replace abstract storage classes in superset_core.extensions.storage with concrete
+ implementations from Superset.
+ """
+ import superset_core.extensions.storage.dao as core_storage_dao
+ import superset_core.extensions.storage.ephemeral as core_ephemeral_state
+ import superset_core.extensions.storage.models as core_storage_models
+ import superset_core.extensions.storage.persistent as core_persistent_state
+
+ from superset.extensions.storage.ephemeral import EphemeralState
+ from superset.extensions.storage.persistent import PersistentState
+ from superset.extensions.storage.persistent_dao import ExtensionStorageDAO
+ from superset.extensions.storage.persistent_model import ExtensionStorage
+
+ # Replace abstract classes with concrete implementations
+ core_ephemeral_state.EphemeralState = EphemeralState # type: ignore[misc,assignment]
+ core_persistent_state.PersistentState = PersistentState # type: ignore[misc,assignment]
+ core_storage_models.ExtensionStorageEntry = ExtensionStorage # type: ignore[misc,assignment]
+ core_storage_dao.ExtensionStorageDAO = ExtensionStorageDAO # type: ignore[misc,assignment]
+
+
+def inject_extension_context() -> None:
+ """
+ Replace abstract get_context in superset_core.extensions.context
+ with concrete implementation from Superset.
+ """
+ import superset_core.extensions.context as core_context
+
+ from superset.extensions.context import get_context
+
+ core_context.get_context = get_context
+
+
def initialize_core_api_dependencies() -> None:
"""
Initialize all dependency injections for the superset-core API.
@@ -291,3 +329,5 @@ def initialize_core_api_dependencies() -> None:
inject_task_implementations()
inject_rest_api_implementations()
inject_semantic_layer_implementations()
+ inject_storage_implementations()
+ inject_extension_context()
diff --git a/superset/core/mcp/core_mcp_injection.py b/superset/core/mcp/core_mcp_injection.py
index d143857a685..9c5cdb60d7a 100644
--- a/superset/core/mcp/core_mcp_injection.py
+++ b/superset/core/mcp/core_mcp_injection.py
@@ -47,8 +47,10 @@ def _get_prefixed_id_with_context(base_id: str) -> tuple[str, str]:
"""
if context := get_current_extension_context():
# Extension context: prefix ID to prevent collisions
- manifest = context.manifest
- prefixed_id = f"extensions.{manifest.publisher}.{manifest.name}.{base_id}"
+ prefixed_id = (
+ f"extensions.{context.extension.publisher}."
+ f"{context.extension.name}.{base_id}"
+ )
context_type = "extension"
else:
# Host context: use original ID
diff --git a/superset/extensions/context.py b/superset/extensions/context.py
index c2b1ac9ab61..7d11822657c 100644
--- a/superset/extensions/context.py
+++ b/superset/extensions/context.py
@@ -16,75 +16,119 @@
# under the License.
"""
-Extension Context Management - provides ambient context during extension loading.
+Extension Context Management - provides ambient context for extensions.
-This module provides a thread-local context system that allows decorators to
-automatically detect whether they are being called in host or extension code
-during extension loading.
+This module provides a context system using Python's contextvars that allows
+extensions to access their context (metadata and scoped resources) via get_context().
+
+The context is set during extension loading and when extension callbacks are invoked.
+Uses ContextVar for thread-safe and async-safe context management with automatic
+save/restore for nested contexts.
"""
from __future__ import annotations
-import contextlib
-from threading import local
-from typing import Any, Generator
-
-from superset_core.extensions.types import Manifest
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import Any, Iterator
-# Thread-local storage for extension context
-_extension_context: local = local()
+from superset_core.extensions.types import BaseExtension, Manifest
-class ExtensionContext:
- """Manages ambient extension context during loading."""
+class ExtensionStorage:
+ """Extension storage with all available tiers."""
- def __init__(self, manifest: Manifest):
- self.manifest = manifest
+ @property
+ def ephemeral(self) -> Any:
+ from superset.extensions.storage.ephemeral import EphemeralState
- def __enter__(self) -> "ExtensionContext":
- if getattr(_extension_context, "current", None) is not None:
- current_extension = _extension_context.current.manifest.id
- raise RuntimeError(
- f"Cannot initialize extension {self.manifest.id} while extension "
- f"{current_extension} is already being initialized. "
- f"Nested extension initialization is not supported."
- )
+ return EphemeralState
- _extension_context.current = self
- return self
+ @property
+ def persistent(self) -> Any:
+ from superset.extensions.storage.persistent import PersistentState
- def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
- # Clear the current context
- _extension_context.current = None
+ return PersistentState
-class ExtensionContextWrapper:
- """Wrapper for extension context with extensible properties."""
+class ConcreteExtensionContext:
+ """Concrete implementation of ExtensionContext for the host."""
def __init__(self, manifest: Manifest):
self._manifest = manifest
+ self._storage = ExtensionStorage()
@property
- def manifest(self) -> Manifest:
- """Get the extension manifest."""
+ def extension(self) -> BaseExtension:
+ """Extension metadata."""
return self._manifest
- # Future: Add other context properties here
- # @property
- # def security_context(self) -> SecurityContext: ...
- # @property
- # def build_info(self) -> BuildInfo: ...
+ @property
+ def storage(self) -> ExtensionStorage:
+ return self._storage
+
+
+# Context variable for ambient extension context pattern.
+# Thread-safe and async-safe via Python's contextvars.
+_current_context: ContextVar[ConcreteExtensionContext | None] = ContextVar(
+ "extension_context", default=None
+)
+
+def get_context() -> ConcreteExtensionContext:
+ """
+ Get the current extension's context.
-def get_current_extension_context() -> ExtensionContextWrapper | None:
- """Get the currently active extension context wrapper, or None if in host code."""
- if context := getattr(_extension_context, "current", None):
- return ExtensionContextWrapper(context.manifest)
- return None
+ This is the host implementation that replaces the stub in superset_core.
+ :returns: The current extension's context.
+ :raises RuntimeError: If called outside of an extension context.
+ """
+ context = _current_context.get()
+ if context is None:
+ raise RuntimeError(
+ "get_context() must be called within an extension context. "
+ "Ensure this code is being executed during extension loading or "
+ "within an extension callback."
+ )
+ return context
-@contextlib.contextmanager
-def extension_context(manifest: Manifest) -> Generator[None, None, None]:
- """Context manager for setting extension context during loading."""
- with ExtensionContext(manifest):
+
+def get_current_extension_context() -> ConcreteExtensionContext | None:
+ """Get the currently active extension context, or None if in host code."""
+ return _current_context.get()
+
+
+@contextmanager
+def use_context(ctx: ConcreteExtensionContext) -> Iterator[None]:
+ """
+ Context manager to set ambient context for extension execution.
+
+ Used to establish the ambient context before executing extension code.
+ The context is automatically restored after execution, supporting nested
+ context switches.
+
+ :param ctx: ExtensionContext to set as the current context
+ :yields: None
+ """
+ token = _current_context.set(ctx)
+ try:
yield
+ finally:
+ _current_context.reset(token)
+
+
+@contextmanager
+def extension_context(manifest: Manifest) -> Iterator[ConcreteExtensionContext]:
+ """
+ Context manager for setting extension context during loading.
+
+ Creates a new ExtensionContext for the given manifest and sets it as
+ the current context. Supports nested contexts via ContextVar tokens.
+
+ :param manifest: The extension manifest
+ :yields: The created ExtensionContext
+ """
+ ctx = ConcreteExtensionContext(manifest)
+ with use_context(ctx):
+ yield ctx
diff --git a/superset/extensions/storage/__init__.py b/superset/extensions/storage/__init__.py
new file mode 100644
index 00000000000..8f8a59b45c2
--- /dev/null
+++ b/superset/extensions/storage/__init__.py
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Host implementations for extension storage APIs.
+
+This module provides concrete implementations that are injected into
+superset_core.extensions.storage at startup.
+"""
+
+from superset.extensions.storage.ephemeral import ( # noqa: F401
+ EphemeralState,
+ SharedEphemeralStateAccessor,
+)
diff --git a/superset/extensions/storage/api.py b/superset/extensions/storage/api.py
new file mode 100644
index 00000000000..7ba8e7be563
--- /dev/null
+++ b/superset/extensions/storage/api.py
@@ -0,0 +1,744 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+REST API for extension storage.
+
+Provides HTTP endpoints for frontend extensions to access server-side
+ephemeral storage without direct backend code.
+
+All operations are user-scoped by default. Use `?shared=true` query param
+to access shared state visible to all users.
+"""
+
+from __future__ import annotations
+
+import base64
+from typing import Any
+
+from flask import g, request
+from flask.wrappers import Response
+from flask_appbuilder.api import BaseApi, expose, protect, safe
+
+from superset.extensions.storage.codecs import DEFAULT_CODEC, get_codec, SAFE_CODECS
+from superset.extensions.storage.ephemeral_dao import (
+ ExtensionEphemeralDAO,
+ ExtensionEphemeralTTLInvalid,
+ ExtensionEphemeralValueTooLarge,
+)
+from superset.extensions.storage.persistent_dao import (
+ ExtensionStorageDAO,
+ ExtensionStorageKeyTooLong,
+ ExtensionStorageListPayloadTooLarge,
+ ExtensionStorageQuotaExceeded,
+ ExtensionStorageValueTooLarge,
+)
+from superset.extensions.storage.utils import get_extension_or_404, parse_ttl
+from superset.key_value.exceptions import KeyValueCodecEncodeException
+from superset.utils.decorators import transaction
+
+
+def _decoded_result_for_wire(decoded: Any) -> tuple[Any, bool]:
+ """Convert a codec-decoded value into its JSON wire representation.
+
+ JSON has no byte type, so a raw `bytes` value is base64-encoded to a
+ string for the response and flagged as such; every other value is
+ already JSON-representable as-is. Checked on the decoded value's
+ actual type, not the codec's name, so this keeps working for a codec
+ this module didn't define.
+
+ :returns: (wire_value, is_binary)
+ """
+ if isinstance(decoded, bytes):
+ return base64.b64encode(decoded).decode("ascii"), True
+ return decoded, False
+
+
+def _wire_value_for_request(value: Any, is_binary: bool) -> Any:
+ """Convert a request body's JSON `value` into a codec's input type.
+
+ `is_binary` is an explicit flag from the caller: JSON has no byte
+ type, so there is no way to tell, from the JSON `value` alone,
+ whether it is a base64 string that must be decoded to bytes before
+ being handed to the codec's `encode`, or a literal value to pass
+ through as-is. Only the caller knows which it sent.
+
+ :raises ValueError: if `is_binary` is set and `value` is not a valid
+ base64 string.
+ """
+ if is_binary:
+ return base64.b64decode(value, validate=True)
+ return value
+
+
+class ExtensionStorageRestApi(BaseApi):
+ """REST API for extension ephemeral (Tier 2) and persistent (Tier 3) storage."""
+
+ allow_browser_login = True
+ route_base = "/api/v1/extensions"
+
+ def response(self, status_code: int, **kwargs: Any) -> Response:
+ """Helper method to create JSON responses."""
+ from flask import jsonify
+
+ return jsonify(kwargs), status_code
+
+ def response_404(self, message: str = "Not found") -> Response:
+ """Helper method to create 404 responses."""
+ from flask import jsonify
+
+ return jsonify({"message": message}), 404
+
+ def response_400(self, message: str) -> Response:
+ """Helper method to create 400 responses."""
+ from flask import jsonify
+
+ return jsonify({"message": message}), 400
+
+ @protect()
+ @safe
+ @expose("/<publisher>/<name>/storage/ephemeral/<key>", methods=("GET",))
+ def get_ephemeral(
+ self, publisher: str, name: str, key: str, **kwargs: Any
+ ) -> Response:
+ """Get a value from ephemeral state.
+ ---
+ get:
+ summary: Get a value from ephemeral state
+ parameters:
+ - in: path
+ name: publisher
+ schema:
+ type: string
+ required: true
+ description: Extension publisher
+ - in: path
+ name: name
+ schema:
+ type: string
+ required: true
+ description: Extension name
+ - in: path
+ name: key
+ schema:
+ type: string
+ required: true
+ description: Storage key
+ - in: query
+ name: shared
+ schema:
+ type: boolean
+ required: false
+ description: If true, read from shared state visible to all users
+ responses:
+ 200:
+ description: Value retrieved successfully
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ result:
+ description: The stored value. When 'isBinary' is
+ true, this is a base64 string that must be
+ decoded to get the actual value.
+ codec:
+ type: string
+ description: Name of the codec 'result' was encoded
+ with, e.g. "json" (default) or "binary"
+ isBinary:
+ type: boolean
+ description: Whether the stored value is binary
+ data
+ 400:
+ description: Value was stored with a codec unavailable over the API
+ 404:
+ description: Extension not found
+ """
+ extension_id = f"{publisher}.{name}"
+ extension = get_extension_or_404(extension_id)
+ if not extension:
+ return self.response_404("Extension not found")
+
+ shared = request.args.get("shared", "false").lower() == "true"
+ raw = ExtensionEphemeralDAO.get_raw(extension_id, key, shared=shared)
+ if raw is None:
+ return self.response(200, result=None)
+ value, codec = raw
+ if codec not in SAFE_CODECS:
+ return self.response_400(
+ f"Value was stored with codec '{codec}', which cannot be "
+ "read over the REST API."
+ )
+
+ result, is_binary = _decoded_result_for_wire(get_codec(codec).decode(value))
+ return self.response(200, result=result, codec=codec, isBinary=is_binary)
+
+ @protect()
+ @safe
+ @expose("/<publisher>/<name>/storage/ephemeral/<key>", methods=("PUT",))
+ def set_ephemeral(
+ self, publisher: str, name: str, key: str, **kwargs: Any
+ ) -> Response:
+ """Set a value in ephemeral state.
+ ---
+ put:
+ summary: Set a value in ephemeral state
+ parameters:
+ - in: path
+ name: publisher
+ schema:
+ type: string
+ required: true
+ description: Extension publisher
+ - in: path
+ name: name
+ schema:
+ type: string
+ required: true
+ description: Extension name
+ - in: path
+ name: key
+ schema:
+ type: string
+ required: true
+ description: Storage key
+ - in: query
+ name: shared
+ schema:
+ type: boolean
+ required: false
+ description: If true, store as shared state visible to all users
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - value
+ - ttl
+ properties:
+ value:
+ description: The value to store (must not exceed
+ MAX_VALUE_SIZE bytes once encoded with 'codec').
+ When 'isBinary' is true, this must be a base64
+ string, decoded before being handed to 'codec'.
+ codec:
+ type: string
+ description: Name of the codec used to encode 'value',
+ e.g. "json" (default). Must be one of the codecs
+ allowed over the REST API.
+ isBinary:
+ type: boolean
+ description: Whether 'value' is binary data
+ ttl:
+ type: integer
+ description: Time-to-live in seconds (must be a positive
+ integer not exceeding MAX_TTL)
+ responses:
+ 200:
+ description: Value stored successfully
+ 400:
+ description: Invalid request body, or codec not allowed over the API
+ 404:
+ description: Extension not found
+ """
+ extension_id = f"{publisher}.{name}"
+ extension = get_extension_or_404(extension_id)
+ if not extension:
+ return self.response_404("Extension not found")
+
+ body = request.get_json(silent=True) or {}
+ if not isinstance(body, dict):
+ return self.response_400("Request body must be a JSON object")
+ if "value" not in body:
+ return self.response_400("Request body must contain 'value' field")
+
+ codec = body.get("codec", DEFAULT_CODEC)
+ if not isinstance(codec, str) or codec not in SAFE_CODECS:
+ return self.response_400(
+ f"Codec '{codec}' is not allowed over the REST API."
+ )
+
+ is_binary = bool(body.get("isBinary", False))
+ try:
+ value = _wire_value_for_request(body["value"], is_binary)
+ except (ValueError, TypeError):
+ return self.response_400(
+ "Value must be a valid base64 string when 'isBinary' is true."
+ )
+ ttl, error = parse_ttl(body)
+ if error:
+ return self.response_400(error)
+
+ shared = request.args.get("shared", "false").lower() == "true"
+ try:
+ ExtensionEphemeralDAO.set(
+ extension_id, key, value, ttl, codec=codec, shared=shared
+ )
+ except (ExtensionEphemeralTTLInvalid, ExtensionEphemeralValueTooLarge) as ex:
+ return self.response_400(ex.message)
+ except (KeyValueCodecEncodeException, TypeError, ValueError):
+ return self.response_400(
+ f"Value could not be encoded with codec '{codec}'."
+ )
+
+ return self.response(200, message="Value stored successfully")
+
+ @protect()
+ @safe
+ @expose("/<publisher>/<name>/storage/ephemeral/<key>", methods=("DELETE",))
+ def delete_ephemeral(
+ self, publisher: str, name: str, key: str, **kwargs: Any
+ ) -> Response:
+ """Delete a value from ephemeral state.
+ ---
+ delete:
+ summary: Delete a value from ephemeral state
+ parameters:
+ - in: path
+ name: publisher
+ schema:
+ type: string
+ required: true
+ description: Extension publisher
+ - in: path
+ name: name
+ schema:
+ type: string
+ required: true
+ description: Extension name
+ - in: path
+ name: key
+ schema:
+ type: string
+ required: true
+ description: Storage key
+ - in: query
+ name: shared
+ schema:
+ type: boolean
+ required: false
+ description: If true, delete from shared state
+ responses:
+ 200:
+ description: Value deleted successfully
+ 404:
+ description: Extension not found
+ """
+ extension_id = f"{publisher}.{name}"
+ extension = get_extension_or_404(extension_id)
+ if not extension:
+ return self.response_404("Extension not found")
+
+ shared = request.args.get("shared", "false").lower() == "true"
+ ExtensionEphemeralDAO.delete(extension_id, key, shared=shared)
+
+ return self.response(200, message="Value deleted successfully")
+
+ @protect()
+ @safe
+ @expose("/<publisher>/<name>/storage/persistent", methods=("GET",))
+ def list_persistent(self, publisher: str, name: str, **kwargs: Any) -> Response:
+ """List entries in persistent state.
+ ---
+ get:
+ summary: List entries in persistent state
+ parameters:
+ - in: path
+ name: publisher
+ schema:
+ type: string
+ required: true
+ description: Extension publisher
+ - in: path
+ name: name
+ schema:
+ type: string
+ required: true
+ description: Extension name
+ - in: query
+ name: shared
+ schema:
+ type: boolean
+ required: false
+ description: If true, list shared state visible to all users
+ - in: query
+ name: resource_type
+ schema:
+ type: string
+ required: false
+ description: Filter by resource type
+ - in: query
+ name: resource_uuid
+ schema:
+ type: string
+ required: false
+ description: Filter by resource UUID (requires resource_type)
+ - in: query
+ name: page
+ schema:
+ type: integer
+ required: false
+ description: Zero-indexed page number. Defaults to 0.
+ - in: query
+ name: page_size
+ schema:
+ type: integer
+ required: false
+ description: Number of entries per page. Defaults to 10. There
+ is no fixed ceiling, but a page whose combined value size
+ exceeds MAX_LIST_PAYLOAD_SIZE is rejected — reduce page_size
+ and retry if that happens.
+ responses:
+ 200:
+ description: Entries retrieved successfully
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ result:
+ type: array
+ items:
+ type: object
+ properties:
+ key:
+ type: string
+ value:
+ description: The stored value, or null if its
+ codec cannot be read over the REST API.
+ When 'isBinary' is true, this is a base64
+ string that must be decoded to get the
+ actual value.
+ codec:
+ type: string
+ isBinary:
+ type: boolean
+ description: Whether the stored value is
+ binary data
+ count:
+ type: integer
+ description: Total number of entries matching the
+ given scope/filters, across all pages
+ 400:
+ description: The requested page's combined value size exceeds
+ MAX_LIST_PAYLOAD_SIZE
+ 404:
+ description: Extension not found
+ """
+ extension_id = f"{publisher}.{name}"
+ extension = get_extension_or_404(extension_id)
+ if not extension:
+ return self.response_404("Extension not found")
+
+ shared = request.args.get("shared", "false").lower() == "true"
+ user_fk = None if shared else g.user.id
+ resource_type = request.args.get("resource_type")
+ resource_uuid = request.args.get("resource_uuid")
+ try:
+ page = int(request.args.get("page", 0))
+ page_size = int(request.args.get("page_size", 10))
+ except (TypeError, ValueError):
+ return self.response_400("'page' and 'page_size' must be integers")
+
+ try:
+ entries, count = ExtensionStorageDAO.list_entries(
+ extension_id,
+ user_fk=user_fk,
+ resource_type=resource_type,
+ resource_uuid=resource_uuid,
+ page=page,
+ page_size=page_size,
+ )
+ except ExtensionStorageListPayloadTooLarge as ex:
+ return self.response(ex.status, message=ex.message)
+
+ result = []
+ for entry in entries:
+ value: Any = None
+ is_binary = False
+ if entry.codec in SAFE_CODECS and entry.value is not None:
+ decoded = get_codec(entry.codec).decode(entry.value)
+ value, is_binary = _decoded_result_for_wire(decoded)
+ result.append(
+ {
+ "key": entry.key,
+ "value": value,
+ "codec": entry.codec,
+ "isBinary": is_binary,
+ }
+ )
+
+ return self.response(200, result=result, count=count)
+
+ @protect()
+ @safe
+ @expose("/<publisher>/<name>/storage/persistent/<key>", methods=("GET",))
+ def get_persistent(
+ self, publisher: str, name: str, key: str, **kwargs: Any
+ ) -> Response:
+ """Get a value from persistent state.
+ ---
+ get:
+ summary: Get a value from persistent state
+ parameters:
+ - in: path
+ name: publisher
+ schema:
+ type: string
+ required: true
+ description: Extension publisher
+ - in: path
+ name: name
+ schema:
+ type: string
+ required: true
+ description: Extension name
+ - in: path
+ name: key
+ schema:
+ type: string
+ required: true
+ description: Storage key
+ - in: query
+ name: shared
+ schema:
+ type: boolean
+ required: false
+ description: If true, read from shared state visible to all users
+ responses:
+ 200:
+ description: Value retrieved successfully
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ result:
+ description: The stored value. When 'isBinary' is
+ true, this is a base64 string that must be
+ decoded to get the actual value.
+ codec:
+ type: string
+ description: Name of the codec 'result' was encoded
+ with, e.g. "json" (default) or "binary"
+ isBinary:
+ type: boolean
+ description: Whether the stored value is binary
+ data
+ 400:
+ description: Value was stored with a codec unavailable over the API
+ 404:
+ description: Extension not found
+ """
+ extension_id = f"{publisher}.{name}"
+ extension = get_extension_or_404(extension_id)
+ if not extension:
+ return self.response_404("Extension not found")
+
+ shared = request.args.get("shared", "false").lower() == "true"
+ user_fk = None if shared else g.user.id
+ entry = ExtensionStorageDAO.get(extension_id, key, user_fk=user_fk)
+ if entry is None:
+ return self.response(200, result=None)
+ if entry.codec not in SAFE_CODECS:
+ return self.response_400(
+ f"Value was stored with codec '{entry.codec}', which cannot be "
+ "read over the REST API."
+ )
+
+ decoded = ExtensionStorageDAO.decode_entry(entry)
+ result, is_binary = _decoded_result_for_wire(decoded)
+
+ return self.response(200, result=result, codec=entry.codec, isBinary=is_binary)
+
+ @protect()
+ @safe
+ @expose("/<publisher>/<name>/storage/persistent/<key>", methods=("PUT",))
+ @transaction()
+ def set_persistent(
+ self, publisher: str, name: str, key: str, **kwargs: Any
+ ) -> Response:
+ """Set a value in persistent state.
+ ---
+ put:
+ summary: Set a value in persistent state
+ parameters:
+ - in: path
+ name: publisher
+ schema:
+ type: string
+ required: true
+ description: Extension publisher
+ - in: path
+ name: name
+ schema:
+ type: string
+ required: true
+ description: Extension name
+ - in: path
+ name: key
+ schema:
+ type: string
+ required: true
+ description: Storage key
+ - in: query
+ name: shared
+ schema:
+ type: boolean
+ required: false
+ description: If true, store as shared state visible to all users
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ - value
+ properties:
+ value:
+ description: The value to store. When 'isBinary' is
+ true, this must be a base64 string, decoded
+ before being handed to 'codec'.
+ codec:
+ type: string
+ description: Name of the codec used to encode 'value',
+ e.g. "json" (default). Must be one of the codecs
+ allowed over the REST API.
+ isBinary:
+ type: boolean
+ description: Whether 'value' is binary data
+ encrypt:
+ type: boolean
+ description: If true, the value is encrypted at rest
+ responses:
+ 200:
+ description: Value stored successfully
+ 400:
+ description: Invalid request body, codec not allowed over the
+ API, or value exceeds MAX_VALUE_SIZE
+ 404:
+ description: Extension not found
+ 413:
+ description: Extension persistent storage quota exceeded
+ """
+ extension_id = f"{publisher}.{name}"
+ extension = get_extension_or_404(extension_id)
+ if not extension:
+ return self.response_404("Extension not found")
+
+ body = request.get_json(silent=True) or {}
+ if not isinstance(body, dict):
+ return self.response_400("Request body must be a JSON object")
+ if "value" not in body:
+ return self.response_400("Request body must contain 'value' field")
+
+ codec = body.get("codec", DEFAULT_CODEC)
+ if not isinstance(codec, str) or codec not in SAFE_CODECS:
+ return self.response_400(
+ f"Codec '{codec}' is not allowed over the REST API."
+ )
+
+ is_binary = bool(body.get("isBinary", False))
+ encrypt = bool(body.get("encrypt", False))
+ shared = request.args.get("shared", "false").lower() == "true"
+ user_fk = None if shared else g.user.id
+ try:
+ wire_value = _wire_value_for_request(body["value"], is_binary)
+ except (ValueError, TypeError):
+ return self.response_400(
+ "Value must be a valid base64 string when 'isBinary' is true."
+ )
+ try:
+ value_bytes = get_codec(codec).encode(wire_value)
+ except (KeyValueCodecEncodeException, TypeError, ValueError):
+ return self.response_400(
+ f"Value could not be encoded with codec '{codec}'."
+ )
+ try:
+ ExtensionStorageDAO.set(
+ extension_id,
+ key,
+ value_bytes,
+ codec=codec,
+ user_fk=user_fk,
+ encrypt=encrypt,
+ )
+ except (
+ ExtensionStorageKeyTooLong,
+ ExtensionStorageQuotaExceeded,
+ ExtensionStorageValueTooLarge,
+ ) as ex:
+ return self.response(ex.status, message=ex.message)
+
+ return self.response(200, message="Value stored successfully")
+
+ @protect()
+ @safe
+ @expose("/<publisher>/<name>/storage/persistent/<key>", methods=("DELETE",))
+ @transaction()
+ def delete_persistent(
+ self, publisher: str, name: str, key: str, **kwargs: Any
+ ) -> Response:
+ """Delete a value from persistent state.
+ ---
+ delete:
+ summary: Delete a value from persistent state
+ parameters:
+ - in: path
+ name: publisher
+ schema:
+ type: string
+ required: true
+ description: Extension publisher
+ - in: path
+ name: name
+ schema:
+ type: string
+ required: true
+ description: Extension name
+ - in: path
+ name: key
+ schema:
+ type: string
+ required: true
+ description: Storage key
+ - in: query
+ name: shared
+ schema:
+ type: boolean
+ required: false
+ description: If true, delete from shared state
+ responses:
+ 200:
+ description: Value deleted successfully
+ 404:
+ description: Extension not found
+ """
+ extension_id = f"{publisher}.{name}"
+ extension = get_extension_or_404(extension_id)
+ if not extension:
+ return self.response_404("Extension not found")
+
+ shared = request.args.get("shared", "false").lower() == "true"
+ user_fk = None if shared else g.user.id
+ ExtensionStorageDAO.delete_by_key(extension_id, key, user_fk=user_fk)
+
+ return self.response(200, message="Value deleted successfully")
diff --git a/superset/extensions/storage/codecs.py b/superset/extensions/storage/codecs.py
new file mode 100644
index 00000000000..09285c90cb2
--- /dev/null
+++ b/superset/extensions/storage/codecs.py
@@ -0,0 +1,68 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Codec registry for extension storage (Tiers 2 and 3).
+
+Maps the codec identifier persisted alongside a stored value (e.g.
+`ExtensionStorage.codec`) to the `KeyValueCodec` instance that encodes/
+decodes it, so a value written with one codec can be read back without the
+caller having to remember which one it used.
+
+Reuses the codec implementations from `superset.key_value.types` rather than
+defining new ones, since the encode/decode logic (JSON, pickle) is identical.
+"""
+
+from __future__ import annotations
+
+from superset.key_value.types import (
+ BinaryKeyValueCodec,
+ JsonKeyValueCodec,
+ KeyValueCodec,
+ PickleKeyValueCodec,
+)
+
+#: Default codec identifier used when a caller does not specify one.
+DEFAULT_CODEC = "json"
+
+#: Codec identifiers safe to accept from an untrusted caller (e.g. the REST
+#: API). Excludes "pickle", since decoding a pickle stream can execute
+#: arbitrary code — that codec is only available to backend extension code
+#: calling the DAO directly.
+SAFE_CODECS = frozenset({"json", "binary"})
+
+_CODECS: dict[str, KeyValueCodec] = {
+ "json": JsonKeyValueCodec(),
+ "pickle": PickleKeyValueCodec(),
+ "binary": BinaryKeyValueCodec(),
+}
+
+
+class UnknownCodecError(ValueError):
+ """Raised when a codec identifier has no registered `KeyValueCodec`."""
+
+
+def get_codec(name: str) -> KeyValueCodec:
+ """Look up the `KeyValueCodec` registered for a codec identifier.
+
+ :param name: Codec identifier, e.g. "json" or "pickle".
+ :raises UnknownCodecError: if no codec is registered under `name`.
+ """
+ try:
+ return _CODECS[name]
+ except KeyError:
+ raise UnknownCodecError(f"Unknown codec: {name!r}") from None
diff --git a/superset/extensions/storage/ephemeral.py b/superset/extensions/storage/ephemeral.py
new file mode 100644
index 00000000000..b1b41e89cc0
--- /dev/null
+++ b/superset/extensions/storage/ephemeral.py
@@ -0,0 +1,141 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Host implementation for Ephemeral State (Tier 2 Storage).
+
+Provides the concrete cache-backed implementation that is injected into
+superset_core.extensions.storage.ephemeral at startup. Delegates all cache
+access and validation (MAX_TTL, MAX_VALUE_SIZE) to `ExtensionEphemeralDAO`,
+shared with the REST API (`api.py`) so both enforce the same limits.
+"""
+
+from __future__ import annotations
+
+from typing import Any, ClassVar
+
+from superset_core.extensions.storage.ephemeral import (
+ EphemeralSetOptions,
+ EphemeralState as CoreEphemeralState,
+)
+
+from superset.extensions.storage.ephemeral_dao import ExtensionEphemeralDAO
+from superset.extensions.storage.utils import get_current_extension_id
+
+
+def _get_extension_id() -> str:
+ """Get the current extension ID from context."""
+ return get_current_extension_id("ephemeral_state")
+
+
+class SharedEphemeralStateAccessor:
+ """
+ Accessor for shared (global) ephemeral state.
+
+ Data stored via this accessor is visible to all users of the extension.
+ Extension ID is resolved lazily on each operation from the current context.
+ """
+
+ def get(self, key: str) -> Any:
+ """
+ Get a value from shared ephemeral state.
+
+ :param key: The key to retrieve.
+ :returns: The stored value, or None if not found or expired.
+ """
+ extension_id = _get_extension_id()
+ return ExtensionEphemeralDAO.get(extension_id, key, shared=True)
+
+ def set(self, key: str, value: Any, options: EphemeralSetOptions) -> None:
+ """
+ Set a value in shared ephemeral state with TTL.
+
+ :param key: The key to store.
+ :param value: The value to store, encoded with `options.codec`
+ (default "json").
+ :param options: `EphemeralSetOptions`, e.g. `ttl=3600`. Required —
+ `ttl` must not exceed MAX_TTL from config. `codec="pickle"`
+ stores a value that isn't JSON-serializable.
+ """
+ extension_id = _get_extension_id()
+ ExtensionEphemeralDAO.set(
+ extension_id, key, value, options.ttl, codec=options.codec, shared=True
+ )
+
+ def remove(self, key: str) -> None:
+ """
+ Remove a value from shared ephemeral state.
+
+ :param key: The key to remove.
+ """
+ extension_id = _get_extension_id()
+ ExtensionEphemeralDAO.delete(extension_id, key, shared=True)
+
+
+class EphemeralState(CoreEphemeralState):
+ """
+ Host implementation for ephemeral state operations.
+
+ This class provides the concrete implementation that is injected into
+ superset_core.extensions.storage.ephemeral.
+
+ By default, all operations are user-scoped (private to the current user).
+ Use `shared` to access state that is visible to all users.
+ """
+
+ @staticmethod
+ def get(key: str) -> Any:
+ """
+ Get a value from user-scoped ephemeral state.
+
+ :param key: The key to retrieve.
+ :returns: The stored value, or None if not found or expired.
+ """
+ extension_id = _get_extension_id()
+ return ExtensionEphemeralDAO.get(extension_id, key, shared=False)
+
+ @staticmethod
+ def set(key: str, value: Any, options: EphemeralSetOptions) -> None:
+ """
+ Set a value in user-scoped ephemeral state with TTL.
+
+ :param key: The key to store.
+ :param value: The value to store, encoded with `options.codec`
+ (default "json").
+ :param options: `EphemeralSetOptions`, e.g. `ttl=3600`. Required —
+ `ttl` must not exceed MAX_TTL from config. `codec="pickle"`
+ stores a value that isn't JSON-serializable.
+ """
+ extension_id = _get_extension_id()
+ ExtensionEphemeralDAO.set(
+ extension_id, key, value, options.ttl, codec=options.codec, shared=False
+ )
+
+ @staticmethod
+ def remove(key: str) -> None:
+ """
+ Remove a value from user-scoped ephemeral state.
+
+ :param key: The key to remove.
+ """
+ extension_id = _get_extension_id()
+ ExtensionEphemeralDAO.delete(extension_id, key, shared=False)
+
+ #: Shared (global) ephemeral state accessor.
+ #: Data stored via this accessor is visible to all users of the extension.
+ #: WARNING: Do not store user-specific or sensitive data here.
+ shared: ClassVar[SharedEphemeralStateAccessor] = SharedEphemeralStateAccessor()
diff --git a/superset/extensions/storage/ephemeral_dao.py b/superset/extensions/storage/ephemeral_dao.py
new file mode 100644
index 00000000000..e06f5731a18
--- /dev/null
+++ b/superset/extensions/storage/ephemeral_dao.py
@@ -0,0 +1,161 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import base64
+from typing import Any
+
+from flask import current_app
+from flask_babel import gettext as _
+
+from superset.exceptions import SupersetGenericErrorException
+from superset.extensions import cache_manager
+from superset.extensions.storage.codecs import DEFAULT_CODEC, get_codec
+from superset.extensions.storage.utils import build_storage_key, get_current_user_id
+
+
+class ExtensionEphemeralTTLInvalid(SupersetGenericErrorException):
+ """Raised when a `set` call's TTL is missing or exceeds MAX_TTL."""
+
+ status = 400
+
+
+class ExtensionEphemeralValueTooLarge(SupersetGenericErrorException):
+ """Raised when a `set` call's value exceeds MAX_VALUE_SIZE."""
+
+ status = 400
+
+
+def _get_ephemeral_config() -> dict[str, Any]:
+ return current_app.config["EXTENSIONS_EPHEMERAL_STORAGE"]
+
+
+def _validate_ttl(ttl: int | None) -> int | None:
+ """Validate a TTL against MAX_TTL. Raises if missing or over the limit."""
+ if ttl is None:
+ raise ExtensionEphemeralTTLInvalid(_("A TTL is required for ephemeral state."))
+ if ttl <= 0:
+ raise ExtensionEphemeralTTLInvalid(_("TTL must be a positive integer."))
+ max_ttl = _get_ephemeral_config().get("MAX_TTL")
+ if max_ttl is not None and ttl > max_ttl:
+ raise ExtensionEphemeralTTLInvalid(
+ _("TTL must not exceed %(max_ttl)d seconds.", max_ttl=max_ttl)
+ )
+ return ttl
+
+
+def _validate_value_size(encoded: bytes) -> None:
+ """Validate encoded value bytes against MAX_VALUE_SIZE. Raises if over."""
+ max_size = _get_ephemeral_config().get("MAX_VALUE_SIZE")
+ if max_size is None:
+ return
+ if len(encoded) > max_size:
+ raise ExtensionEphemeralValueTooLarge(
+ _(
+ "Value exceeds the maximum allowed size of %(max_size)d bytes.",
+ max_size=max_size,
+ )
+ )
+
+
+class ExtensionEphemeralDAO:
+ """Cache-backed key-value store for extensions (Tier 2).
+
+ Thin wrapper around `cache_manager.extension_ephemeral_state_cache`
+ (a pluggable Flask-Caching backend) that centralizes key-building and
+ the MAX_TTL/MAX_VALUE_SIZE validation shared by the REST API
+ (`api.py`) and the ambient `ephemeral_state` accessor (`ephemeral.py`),
+ so both enforce the same limits rather than each parsing/validating
+ independently.
+
+ Values are encoded with a codec (see `superset.extensions.storage.codecs`)
+ before being handed to the cache, and stored alongside the codec name in
+ a small JSON-safe envelope (`{"codec": ..., "value": <base64 bytes>}`).
+ This keeps behavior independent of which Flask-Caching backend the
+ operator has configured: the default `SupersetMetastoreCache` backend
+ serializes cached values with its own `JsonKeyValueCodec`, which would
+ reject a non-JSON-serializable Python value (e.g. raw bytes) before it
+ ever reached this DAO's own codec.
+
+ Unlike Tier 3, there is no per-extension total quota here: the pluggable
+ cache backend has no generic way to sum bytes across an extension's
+ keys, so only a per-value size cap is enforced.
+ """
+
+ @staticmethod
+ def get_raw(
+ extension_id: str, key: str, shared: bool = False
+ ) -> tuple[bytes, str] | None:
+ """Return the raw encoded bytes and the codec they were encoded with.
+
+ :returns: (raw_bytes, codec), or None if not found or expired.
+ """
+ user_id = None if shared else get_current_user_id("ephemeral_state")
+ cache_key = build_storage_key(extension_id, key, user_id, shared)
+ envelope = cache_manager.extension_ephemeral_state_cache.get(cache_key)
+ if envelope is None:
+ return None
+ return base64.b64decode(envelope["value"]), envelope["codec"]
+
+ @staticmethod
+ def get(extension_id: str, key: str, shared: bool = False) -> Any:
+ """Get a value from ephemeral state, decoded with the codec it was
+ written with.
+
+ :returns: The decoded value, or None if not found or expired.
+ """
+ raw = ExtensionEphemeralDAO.get_raw(extension_id, key, shared=shared)
+ if raw is None:
+ return None
+ value, codec = raw
+ return get_codec(codec).decode(value)
+
+ @staticmethod
+ def set(
+ extension_id: str,
+ key: str,
+ value: Any,
+ ttl: int | None,
+ codec: str = DEFAULT_CODEC,
+ shared: bool = False,
+ ) -> None:
+ """Set a value in ephemeral state.
+
+ :param value: The value to store, encoded with `codec` before being
+ handed to the cache backend.
+ :raises ExtensionEphemeralTTLInvalid: if `ttl` is missing or exceeds
+ MAX_TTL.
+ :raises ExtensionEphemeralValueTooLarge: if the encoded value exceeds
+ MAX_VALUE_SIZE.
+ """
+ ttl = _validate_ttl(ttl)
+ encoded = get_codec(codec).encode(value)
+ _validate_value_size(encoded)
+ user_id = None if shared else get_current_user_id("ephemeral_state")
+ cache_key = build_storage_key(extension_id, key, user_id, shared)
+ envelope = {"codec": codec, "value": base64.b64encode(encoded).decode("ascii")}
+ cache_manager.extension_ephemeral_state_cache.set(
+ cache_key, envelope, timeout=ttl
+ )
+
+ @staticmethod
+ def delete(extension_id: str, key: str, shared: bool = False) -> None:
+ """Delete a value from ephemeral state."""
+ user_id = None if shared else get_current_user_id("ephemeral_state")
+ cache_key = build_storage_key(extension_id, key, user_id, shared)
+ cache_manager.extension_ephemeral_state_cache.delete(cache_key)
diff --git a/superset/extensions/storage/filters.py b/superset/extensions/storage/filters.py
new file mode 100644
index 00000000000..cb54d7bb0e8
--- /dev/null
+++ b/superset/extensions/storage/filters.py
@@ -0,0 +1,45 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Filters for ExtensionStorage model"""
+
+from typing import Any
+
+from sqlalchemy.orm.query import Query
+
+from superset.extensions.context import get_current_extension_context
+from superset.extensions.storage.persistent_model import ExtensionStorage
+from superset.views.base import BaseFilter
+
+
+class ExtensionStorageFilter(BaseFilter): # pylint: disable=too-few-public-methods
+ """
+ Filter for ExtensionStorage that scopes every query to the extension
+ currently executing, resolved from ambient context.
+
+ This is the isolation boundary for ExtensionStorageDAO: extension_id is
+ never a caller-supplied parameter, so an extension cannot query or
+ modify another extension's storage through this DAO even if it tried.
+ Queries made outside an extension context (no ambient context set) match
+ nothing, rather than falling through to an unscoped query.
+ """
+
+ def apply(self, query: Query, value: Any) -> Query:
+ """Apply the filter to the query."""
+ context = get_current_extension_context()
+ if context is None:
+ return query.filter(ExtensionStorage.extension_id.is_(None))
+ return query.filter(ExtensionStorage.extension_id == context.extension.id)
diff --git a/superset/extensions/storage/persistent.py b/superset/extensions/storage/persistent.py
new file mode 100644
index 00000000000..9b6d583555e
--- /dev/null
+++ b/superset/extensions/storage/persistent.py
@@ -0,0 +1,244 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Host implementation for Persistent State (Tier 3 Storage).
+
+Provides the concrete database-backed implementation that is injected into
+superset_core.extensions.storage.persistent at startup.
+"""
+
+from __future__ import annotations
+
+from typing import Any, ClassVar
+
+from superset_core.extensions.storage.persistent import (
+ PersistentListEntry,
+ PersistentListOptions,
+ PersistentListResult,
+ PersistentSetOptions,
+ PersistentState as CorePersistentState,
+)
+
+from superset.extensions.storage.codecs import DEFAULT_CODEC, get_codec
+from superset.extensions.storage.persistent_dao import ExtensionStorageDAO
+from superset.extensions.storage.utils import (
+ get_current_extension_id,
+ get_current_user_id,
+)
+from superset.utils.decorators import transaction
+
+
+def _get_extension_id() -> str:
+ """Get the current extension ID from context."""
+ return get_current_extension_id("persistent_state")
+
+
+def _list(
+ extension_id: str,
+ user_fk: int | None,
+ options: PersistentListOptions,
+) -> PersistentListResult:
+ """Shared `list` implementation for both scopes.
+
+ Unlike the REST API, ambient backend code has no SAFE_CODECS
+ restriction — every entry's value is decoded unconditionally, same as
+ `get_decoded_value()`.
+ """
+ entries, count = ExtensionStorageDAO.list_entries(
+ extension_id,
+ user_fk=user_fk,
+ resource_type=options.resource_type,
+ resource_uuid=options.resource_uuid,
+ page=options.page,
+ page_size=options.page_size,
+ )
+ return PersistentListResult(
+ entries=[
+ PersistentListEntry(
+ key=entry.key,
+ value=(
+ get_codec(entry.codec).decode(entry.value)
+ if entry.value is not None
+ else None
+ ),
+ codec=entry.codec,
+ )
+ for entry in entries
+ ],
+ count=count,
+ )
+
+
+class SharedPersistentStateAccessor:
+ """
+ Accessor for shared (global) persistent state.
+
+ Data stored via this accessor is visible to all users of the extension.
+ Extension ID is resolved lazily on each operation from the current context.
+ """
+
+ def get(self, key: str) -> Any:
+ """
+ Get a value from shared persistent state.
+
+ :param key: The key to retrieve.
+ :returns: The stored value, or None if not found.
+ """
+ extension_id = _get_extension_id()
+ return ExtensionStorageDAO.get_decoded_value(extension_id, key, user_fk=None)
+
+ @transaction()
+ def set(
+ self, key: str, value: Any, options: PersistentSetOptions | None = None
+ ) -> None:
+ """
+ Set a value in shared persistent state.
+
+ :param key: The key to store.
+ :param value: The value to store, encoded with `options.codec`
+ (default "json").
+ :param options: Optional `PersistentSetOptions`, e.g. `encrypt=True`
+ to store the value encrypted at rest, or `codec="pickle"` to
+ store a value that isn't JSON-serializable.
+ :raises ExtensionStorageValueTooLarge: if the encoded value exceeds
+ MAX_VALUE_SIZE.
+ :raises ExtensionStorageQuotaExceeded: if this write would exceed the
+ extension's configured persistent storage quota.
+ """
+ extension_id = _get_extension_id()
+ encrypt = options.encrypt if options is not None else False
+ codec = options.codec if options is not None else DEFAULT_CODEC
+ ExtensionStorageDAO.set(
+ extension_id,
+ key,
+ get_codec(codec).encode(value),
+ codec=codec,
+ user_fk=None,
+ encrypt=encrypt,
+ )
+
+ def list(self, options: PersistentListOptions) -> PersistentListResult:
+ """
+ List entries in shared persistent state.
+
+ :param options: `PersistentListOptions`, e.g.
+ `PersistentListOptions(page=0, page_size=10)`.
+ :returns: `PersistentListResult` with the page's entries and the
+ total count across all pages.
+ :raises ExtensionStorageListPayloadTooLarge: if the requested
+ page's combined value size exceeds MAX_LIST_PAYLOAD_SIZE.
+ """
+ extension_id = _get_extension_id()
+ return _list(extension_id, user_fk=None, options=options)
+
+ @transaction()
+ def remove(self, key: str) -> None:
+ """
+ Remove a value from shared persistent state.
+
+ :param key: The key to remove.
+ """
+ extension_id = _get_extension_id()
+ ExtensionStorageDAO.delete_by_key(extension_id, key, user_fk=None)
+
+
+class PersistentState(CorePersistentState):
+ """
+ Host implementation for persistent state operations.
+
+ This class provides the concrete implementation that is injected into
+ superset_core.extensions.storage.persistent.
+
+ By default, all operations are user-scoped (private to the current user).
+ Use `shared` to access state that is visible to all users.
+ """
+
+ @staticmethod
+ def get(key: str) -> Any:
+ """
+ Get a value from user-scoped persistent state.
+
+ :param key: The key to retrieve.
+ :returns: The stored value, or None if not found.
+ """
+ extension_id = _get_extension_id()
+ user_id = get_current_user_id("persistent_state")
+ return ExtensionStorageDAO.get_decoded_value(extension_id, key, user_fk=user_id)
+
+ @staticmethod
+ @transaction()
+ def set(key: str, value: Any, options: PersistentSetOptions | None = None) -> None:
+ """
+ Set a value in user-scoped persistent state.
+
+ :param key: The key to store.
+ :param value: The value to store, encoded with `options.codec`
+ (default "json").
+ :param options: Optional `PersistentSetOptions`, e.g. `encrypt=True`
+ to store the value encrypted at rest, or `codec="pickle"` to
+ store a value that isn't JSON-serializable.
+ :raises ExtensionStorageValueTooLarge: if the encoded value exceeds
+ MAX_VALUE_SIZE.
+ :raises ExtensionStorageQuotaExceeded: if this write would exceed the
+ extension's configured persistent storage quota.
+ """
+ extension_id = _get_extension_id()
+ user_id = get_current_user_id("persistent_state")
+ encrypt = options.encrypt if options is not None else False
+ codec = options.codec if options is not None else DEFAULT_CODEC
+ ExtensionStorageDAO.set(
+ extension_id,
+ key,
+ get_codec(codec).encode(value),
+ codec=codec,
+ user_fk=user_id,
+ encrypt=encrypt,
+ )
+
+ @staticmethod
+ def list(options: PersistentListOptions) -> PersistentListResult:
+ """
+ List entries in user-scoped persistent state.
+
+ :param options: `PersistentListOptions`, e.g.
+ `PersistentListOptions(page=0, page_size=10)`.
+ :returns: `PersistentListResult` with the page's entries and the
+ total count across all pages.
+ :raises ExtensionStorageListPayloadTooLarge: if the requested
+ page's combined value size exceeds MAX_LIST_PAYLOAD_SIZE.
+ """
+ extension_id = _get_extension_id()
+ user_id = get_current_user_id("persistent_state")
+ return _list(extension_id, user_fk=user_id, options=options)
+
+ @staticmethod
+ @transaction()
+ def remove(key: str) -> None:
+ """
+ Remove a value from user-scoped persistent state.
+
+ :param key: The key to remove.
+ """
+ extension_id = _get_extension_id()
+ user_id = get_current_user_id("persistent_state")
+ ExtensionStorageDAO.delete_by_key(extension_id, key, user_fk=user_id)
+
+ #: Shared (global) persistent state accessor.
+ #: Data stored via this accessor is visible to all users of the extension.
+ #: WARNING: Do not store user-specific or sensitive data here.
+ shared: ClassVar[SharedPersistentStateAccessor] = SharedPersistentStateAccessor()
diff --git a/superset/extensions/storage/persistent_dao.py b/superset/extensions/storage/persistent_dao.py
new file mode 100644
index 00000000000..e150a054564
--- /dev/null
+++ b/superset/extensions/storage/persistent_dao.py
@@ -0,0 +1,655 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import logging
+from dataclasses import dataclass
+from typing import Any
+
+import backoff
+from flask import current_app
+from flask_babel import gettext as _
+from sqlalchemy import and_, desc, func, LargeBinary
+
+from superset import db
+from superset.daos.base import BaseDAO
+from superset.distributed_lock import DistributedLock
+from superset.exceptions import (
+ AcquireDistributedLockFailedException,
+ SupersetGenericErrorException,
+)
+from superset.extensions.storage.codecs import DEFAULT_CODEC, get_codec
+from superset.extensions.storage.filters import ExtensionStorageFilter
+from superset.extensions.storage.persistent_model import ExtensionStorage
+from superset.utils.encrypt import (
+ DEFAULT_ENCRYPTION_ENGINE_NAME,
+ EncryptedType,
+ resolve_encryption_engine,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class ExtensionStorageQuotaExceeded(SupersetGenericErrorException):
+ """Raised when a write would exceed an extension's persistent storage quota."""
+
+ status = 413
+
+ def __init__(self, extension_id: str, quota: int) -> None:
+ super().__init__(
+ message=_(
+ "Extension '%(extension_id)s' has exceeded its persistent "
+ "storage quota of %(quota)d bytes.",
+ extension_id=extension_id,
+ quota=quota,
+ ),
+ )
+
+
+class ExtensionStorageValueTooLarge(SupersetGenericErrorException):
+ """Raised when a `set` call's value exceeds MAX_VALUE_SIZE."""
+
+ status = 400
+
+ def __init__(self, max_size: int) -> None:
+ super().__init__(
+ message=_(
+ "Value exceeds the maximum allowed size of %(max_size)d bytes.",
+ max_size=max_size,
+ ),
+ )
+
+
+class ExtensionStorageListPayloadTooLarge(SupersetGenericErrorException):
+ """Raised when a `list` page's combined value size exceeds
+ MAX_LIST_PAYLOAD_SIZE."""
+
+ status = 400
+
+ def __init__(self, requested_size: int, max_size: int) -> None:
+ super().__init__(
+ message=_(
+ "Requested page would return %(requested_size)d bytes, "
+ "exceeding the maximum allowed list payload size of "
+ "%(max_size)d bytes. Reduce page_size and try again.",
+ requested_size=requested_size,
+ max_size=max_size,
+ ),
+ )
+
+
+class ExtensionStorageKeyTooLong(SupersetGenericErrorException):
+ """Raised when a `set` call's key exceeds MAX_KEY_LENGTH."""
+
+ status = 400
+
+ def __init__(self, max_length: int) -> None:
+ super().__init__(
+ message=_(
+ "Storage key exceeds the maximum allowed length of "
+ "%(max_length)d characters.",
+ max_length=max_length,
+ ),
+ )
+
+
+#: Matches the `key` column's `String(255)` definition in `ExtensionStorage`
+#: (`persistent_model.py`). Enforced here, at the DAO boundary, so every
+#: caller (REST API, ambient accessors, direct DAO use) gets a consistent
+#: error instead of a database integrity/truncation failure — the frontend
+#: SDK enforces the same limit client-side purely so it can fail fast
+#: without a round trip, not as the source of truth.
+MAX_KEY_LENGTH = 255
+
+#: TTL for the lock guarding `ExtensionStorageDAO.set`'s select-then-write.
+#: Short because the guarded section is a handful of local DB operations, no
+#: network calls — long enough to cover normal execution, short enough that
+#: a crashed holder doesn't block the same key for long.
+SET_LOCK_TTL_SECONDS = 5
+
+
+def _validate_key_length(key: str) -> None:
+ """Validate key length against MAX_KEY_LENGTH. Raises if over."""
+ if len(key) > MAX_KEY_LENGTH:
+ raise ExtensionStorageKeyTooLong(MAX_KEY_LENGTH)
+
+
+def _derive_key(secret: str, user_fk: int) -> str:
+ """Derive a per-user encryption key from the master secret and user ID.
+
+ Uses HMAC-SHA256 so the derived key is cryptographically bound to both.
+ Ciphertext encrypted for one user cannot be decrypted as another.
+ """
+ return hmac.new(
+ secret.encode(),
+ str(user_fk).encode(),
+ hashlib.sha256,
+ ).hexdigest()
+
+
+def _enc_type(user_fk: int | None) -> EncryptedType:
+ """Return an EncryptedType for the given scope.
+
+ User-scoped rows use a key derived from SECRET_KEY and the user ID, so
+ ciphertext written for one user cannot be decrypted as another.
+ Shared rows (user_fk=None) use SECRET_KEY directly.
+ """
+ secret = current_app.config["SECRET_KEY"]
+ key = _derive_key(secret, user_fk) if user_fk is not None else secret
+ engine_name = current_app.config.get(
+ "SQLALCHEMY_ENCRYPTED_FIELD_ENGINE", DEFAULT_ENCRYPTION_ENGINE_NAME
+ )
+ return EncryptedType(
+ LargeBinary,
+ key=key,
+ engine=resolve_encryption_engine(engine_name),
+ )
+
+
+def _get_quota() -> int | None:
+ """Return the configured per-extension persistent storage quota in bytes.
+
+ Returns None when no quota is configured (unlimited).
+ """
+ config = current_app.config["EXTENSIONS_PERSISTENT_STORAGE"]
+ return config.get("QUOTA_PER_EXTENSION")
+
+
+def _get_max_list_payload_size() -> int | None:
+ """Return the configured max combined value size for a `list()` page.
+
+ Returns None when no limit is configured (unlimited).
+ """
+ config = current_app.config["EXTENSIONS_PERSISTENT_STORAGE"]
+ return config.get("MAX_LIST_PAYLOAD_SIZE")
+
+
+def _validate_value_size(encoded: bytes) -> None:
+ """Validate encoded value bytes against MAX_VALUE_SIZE. Raises if over.
+
+ Enforced independently of `QUOTA_PER_EXTENSION`: the quota bounds an
+ extension's total storage, while this bounds a single value. A
+ `list_entries()` page's combined size is bounded separately by
+ MAX_LIST_PAYLOAD_SIZE (see `ExtensionStorageDAO.list_entries`).
+ """
+ config = current_app.config["EXTENSIONS_PERSISTENT_STORAGE"]
+ max_size = config.get("MAX_VALUE_SIZE")
+ if max_size is None:
+ return
+ if len(encoded) > max_size:
+ raise ExtensionStorageValueTooLarge(max_size)
+
+
+def _check_quota(extension_id: str, new_size: int, existing_size: int = 0) -> None:
+ """Raise if writing `new_size` bytes would push the extension over quota.
+
+ `existing_size` is the size of the row being replaced (0 for inserts),
+ subtracted from current usage so overwriting a key doesn't double-count
+ it against the quota it already occupies.
+
+ The usage query sums the `value_size` column via the covering
+ `ix_ext_storage_extension_id` index (on `extension_id, value_size`)
+ instead of `LENGTH(value)`, so it can run as an index-only scan rather
+ than reading every one of the extension's stored (and potentially
+ TOASTed) blobs. It is still O(rows) for the extension, so write latency
+ grows with row count — acceptable at the row counts a single extension
+ is expected to accumulate, but not a fully constant-time check.
+ """
+ quota = _get_quota()
+ if quota is None:
+ return
+ current_usage = (
+ db.session.query(func.coalesce(func.sum(ExtensionStorage.value_size), 0))
+ .filter(ExtensionStorage.extension_id == extension_id)
+ .scalar()
+ )
+ if current_usage - existing_size + new_size > quota:
+ raise ExtensionStorageQuotaExceeded(extension_id, quota)
+
+
+def _decrypt_if_needed(
+ entry: ExtensionStorage, extension_id: str, key: str
+) -> bytes | None:
+ """Return `entry.value`, decrypted if `entry.is_encrypted`.
+
+ Returns None (and logs) if decryption fails, e.g. after key rotation.
+ """
+ if not entry.is_encrypted:
+ return entry.value
+ try:
+ return _enc_type(entry.user_fk).process_result_value(
+ entry.value, db.engine.dialect
+ )
+ except Exception: # noqa: BLE001
+ logger.error(
+ "Failed to decrypt extension storage value for "
+ "extension_id=%s key=%s — possible key rotation issue",
+ extension_id,
+ key,
+ )
+ return None
+
+
+def _scope_filter(
+ extension_id: str,
+ key: str,
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+) -> list[object]:
+ """Build the SQLAlchemy filter list for a scoped lookup."""
+ filters: list[object] = [
+ ExtensionStorage.extension_id == extension_id,
+ ExtensionStorage.key == key,
+ ]
+ if user_fk is None:
+ filters.append(ExtensionStorage.user_fk.is_(None))
+ else:
+ filters.append(ExtensionStorage.user_fk == user_fk)
+ if resource_type is None:
+ filters.append(ExtensionStorage.resource_type.is_(None))
+ else:
+ filters.append(ExtensionStorage.resource_type == resource_type)
+ if resource_uuid is None:
+ filters.append(ExtensionStorage.resource_uuid.is_(None))
+ else:
+ filters.append(ExtensionStorage.resource_uuid == resource_uuid)
+ return filters
+
+
+def _list_scope_filter(
+ extension_id: str,
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+) -> list[object]:
+ """Build the SQLAlchemy filter list for a `list()` call.
+
+ Same scope semantics as `_scope_filter` (an explicit None means "match
+ the global/unset scope"), minus the `key` filter.
+ """
+ filters: list[object] = [ExtensionStorage.extension_id == extension_id]
+ if user_fk is None:
+ filters.append(ExtensionStorage.user_fk.is_(None))
+ else:
+ filters.append(ExtensionStorage.user_fk == user_fk)
+ if resource_type is None:
+ filters.append(ExtensionStorage.resource_type.is_(None))
+ else:
+ filters.append(ExtensionStorage.resource_type == resource_type)
+ if resource_uuid is None:
+ filters.append(ExtensionStorage.resource_uuid.is_(None))
+ else:
+ filters.append(ExtensionStorage.resource_uuid == resource_uuid)
+ return filters
+
+
+@dataclass
+class ExtensionStorageListEntry:
+ """A single row returned by `ExtensionStorageDAO.list_entries`.
+
+ `value` is the raw (decrypted) payload, mirroring `get_value()` — it is
+ not decoded with `codec` here, since REST callers must first check
+ `codec` against `SAFE_CODECS` before deciding whether decoding it is
+ safe to expose over the API, while ambient backend callers (no such
+ restriction) decode unconditionally, same as `get_decoded_value()`.
+ """
+
+ key: str
+ value: bytes | None
+ codec: str
+ is_encrypted: bool
+
+
+class ExtensionStorageDAO(BaseDAO[ExtensionStorage]):
+ """Persistent key-value store for extensions (Tier 3).
+
+ Every query and mutation is scoped to the extension currently executing
+ (resolved from ambient extension context by `ExtensionStorageFilter`),
+ so an extension can never read or modify another extension's storage
+ through this DAO.
+
+ Two access shapes are supported:
+
+ * `get`/`set`/`delete_by_key`/`list_entries` — single-key or
+ paginated-listing operations with explicit scope discriminators
+ (`user_fk`, `resource_type`, `resource_uuid`), used by the ambient
+ `persistent_state`/`ephemeral_state` accessors and the REST API (both
+ of which establish the ambient extension context themselves before
+ calling in).
+ * `find_all`/`find_one_or_none`/`filter_by`/`query`/`create`/`update`/
+ `delete` (inherited from `BaseDAO`) — general-purpose DAO access for
+ backend extension code that needs to enumerate or bulk-manage its own
+ rows, exposed to extensions via `superset_core.extensions.storage.dao`.
+
+ Scope is one of:
+
+ * Global scope — user_fk=None, resource_type=None
+ * User scope — user_fk=<id>, resource_type=None
+ * Resource scope — resource_type + resource_uuid set
+ """
+
+ base_filter = ExtensionStorageFilter
+
+ # ── Read ─────────────────────────────────────────────────────────────────
+
+ @staticmethod
+ def get(
+ extension_id: str,
+ key: str,
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+ ) -> ExtensionStorage | None:
+ """Return the raw storage entry. The value field may be encrypted."""
+ entry = (
+ db.session.query(ExtensionStorage)
+ .filter(
+ and_(
+ *_scope_filter(
+ extension_id, key, user_fk, resource_type, resource_uuid
+ )
+ )
+ )
+ .first()
+ )
+ return entry
+
+ @staticmethod
+ def get_value(
+ extension_id: str,
+ key: str,
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+ ) -> bytes | None:
+ """Return the raw (decrypted) value bytes, or None if not found."""
+ entry = ExtensionStorageDAO.get(
+ extension_id, key, user_fk, resource_type, resource_uuid
+ )
+ if entry is None:
+ return None
+ return _decrypt_if_needed(entry, extension_id, key)
+
+ @staticmethod
+ def get_decoded_value(
+ extension_id: str,
+ key: str,
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+ ) -> Any:
+ """Return the value decoded with the codec it was written with.
+
+ :returns: The decoded value, or None if not found.
+ """
+ entry = ExtensionStorageDAO.get(
+ extension_id, key, user_fk, resource_type, resource_uuid
+ )
+ if entry is None:
+ return None
+ return ExtensionStorageDAO.decode_entry(entry)
+
+ @staticmethod
+ def decode_entry(entry: ExtensionStorage) -> Any:
+ """Decode an already-fetched entry's value with the codec it was
+ written with.
+
+ Unlike `get_decoded_value`, this takes the entry directly instead
+ of re-querying for it, so a caller that already fetched (and, e.g.,
+ validated the codec of) an entry decodes that exact same row
+ instead of racing a concurrent write between two separate reads.
+
+ :returns: The decoded value, or None if the value fails to decrypt.
+ """
+ raw = _decrypt_if_needed(entry, entry.extension_id, entry.key)
+ if raw is None:
+ return None
+ return get_codec(entry.codec).decode(raw)
+
+ @staticmethod
+ def list_entries(
+ extension_id: str,
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+ page: int = 0,
+ page_size: int = 10,
+ ) -> tuple[list[ExtensionStorageListEntry], int]:
+ """List entries in the given scope, most recently changed first.
+
+ Named `list_entries` rather than `list` (unlike the single-key
+ `get`/`set`/`delete_by_key` shape) because `BaseDAO` already
+ defines a generic `list()` with a different, incompatible
+ signature (search/sort/column-selection over arbitrary models);
+ overriding it here would break that contract for callers relying
+ on polymorphic DAO access.
+
+ Callers may request any `page_size` — there is no row-count
+ ceiling — but the combined `value_size` of the requested page is
+ checked against MAX_LIST_PAYLOAD_SIZE *before* the (potentially
+ large) `value` column is fetched for any row, so an oversized
+ request fails fast rather than reading data it will then reject.
+
+ :returns: (entries, total_count). `entries[i].value` is the raw
+ (decrypted) payload — see `ExtensionStorageListEntry`.
+ :raises ExtensionStorageListPayloadTooLarge: if the requested page's
+ combined value size exceeds MAX_LIST_PAYLOAD_SIZE.
+ """
+ filters = _list_scope_filter(
+ extension_id, user_fk, resource_type, resource_uuid
+ )
+ base_query = db.session.query(ExtensionStorage).filter(and_(*filters))
+ total_count = base_query.count()
+
+ page = max(page, 0)
+ page_size = max(page_size, 1)
+ page_query = (
+ base_query.order_by(desc(ExtensionStorage.changed_on))
+ .offset(page * page_size)
+ .limit(page_size)
+ )
+
+ if (max_payload_size := _get_max_list_payload_size()) is not None:
+ # Sum value_size for exactly this page's rows, without touching
+ # the `value` column, by reusing the same ordered/offset/limited
+ # query as a subquery.
+ subquery = page_query.with_entities(ExtensionStorage.value_size).subquery()
+ requested_size = db.session.query(
+ func.coalesce(func.sum(subquery.c.value_size), 0)
+ ).scalar()
+ if requested_size > max_payload_size:
+ raise ExtensionStorageListPayloadTooLarge(
+ requested_size, max_payload_size
+ )
+
+ entries = [
+ ExtensionStorageListEntry(
+ key=row.key,
+ value=_decrypt_if_needed(row, extension_id, row.key),
+ codec=row.codec,
+ is_encrypted=row.is_encrypted,
+ )
+ for row in page_query.all()
+ ]
+ return entries, total_count
+
+ # ── Write (upsert) ────────────────────────────────────────────────────────
+
+ @staticmethod
+ @backoff.on_exception(
+ backoff.expo,
+ AcquireDistributedLockFailedException,
+ factor=0.1,
+ base=2,
+ max_tries=8,
+ )
+ def set(
+ extension_id: str,
+ key: str,
+ value: bytes,
+ codec: str = DEFAULT_CODEC,
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+ encrypt: bool = False,
+ ) -> ExtensionStorage:
+ """Upsert a storage entry. Encrypts value when encrypt=True.
+
+ The select-then-insert/update below is guarded by a distributed lock
+ scoped to the whole extension, for two independent reasons:
+
+ * The row's unique constraint can't be relied on to catch concurrent
+ writes to the same key, since `user_fk`, `resource_type`, and
+ `resource_uuid` are nullable and standard SQL never treats
+ NULL = NULL, so two concurrent inserts for the same *global* or
+ *resource*-scoped key (where one or more of those columns is NULL)
+ would not violate it and would land as duplicate rows.
+ * `_check_quota` below enforces usage extension-wide, summed across
+ every key. A lock scoped to only this key would let concurrent
+ writes to *different* keys of the same extension each read usage
+ before the other commits, both pass the check, and land a combined
+ write that exceeds the extension's quota.
+
+ The commit happens here, inside the lock, rather than being left to
+ the caller's `@transaction()` — releasing the lock before the row is
+ committed would let a second writer's `SELECT`, run right after
+ acquiring the now-free lock, still miss the first writer's
+ not-yet-committed row under READ COMMITTED isolation, recreating the
+ exact duplicate-row race the lock exists to prevent.
+
+ :raises ExtensionStorageKeyTooLong: if `key` exceeds MAX_KEY_LENGTH.
+ :raises ExtensionStorageValueTooLarge: if `value` exceeds
+ MAX_VALUE_SIZE.
+ :raises ExtensionStorageQuotaExceeded: if writing `value` would push
+ the extension over its total storage quota.
+ """
+ _validate_key_length(key)
+ _validate_value_size(value)
+ stored_value = (
+ _enc_type(user_fk).process_bind_param(value, db.engine.dialect)
+ if encrypt
+ else value
+ )
+
+ with DistributedLock(
+ namespace="extension_storage_set",
+ ttl_seconds=SET_LOCK_TTL_SECONDS,
+ extension_id=extension_id,
+ ):
+ entry = (
+ db.session.query(ExtensionStorage)
+ .filter(
+ and_(
+ *_scope_filter(
+ extension_id, key, user_fk, resource_type, resource_uuid
+ )
+ )
+ )
+ .first()
+ )
+ new_size = len(stored_value)
+ existing_size = entry.value_size if entry is not None else 0
+ _check_quota(extension_id, new_size, existing_size)
+ if entry is not None:
+ entry.value = stored_value
+ entry.value_size = new_size
+ entry.codec = codec
+ entry.is_encrypted = encrypt
+ else:
+ entry = ExtensionStorage(
+ extension_id=extension_id,
+ key=key,
+ value=stored_value,
+ value_size=new_size,
+ codec=codec,
+ user_fk=user_fk,
+ resource_type=resource_type,
+ resource_uuid=resource_uuid,
+ is_encrypted=encrypt,
+ )
+ db.session.add(entry)
+ db.session.flush()
+ # Committed here, inside the lock, rather than left to the
+ # caller's @transaction(): that decorator only commits after
+ # this whole function returns, which is after the lock above
+ # has already been released — see the docstring.
+ db.session.commit() # pylint: disable=consider-using-transaction
+ return entry
+
+ # ── Create (disallowed) ─────────────────────────────────────────────────────
+
+ @classmethod
+ def create(
+ cls,
+ item: ExtensionStorage | None = None,
+ attributes: dict[str, Any] | None = None,
+ ) -> ExtensionStorage:
+ """Not supported for this DAO.
+
+ `create()` is `BaseDAO`'s raw insert: no upsert dedup against an
+ existing row for the same scoped key, no quota/key-length/value-size
+ validation, and no locking — calling it directly could construct a
+ duplicate row for a key `set()` already wrote (see `set()`'s
+ docstring) without any of the checks that make that safe.
+
+ :raises NotImplementedError: always; use `ExtensionStorageDAO.set()`
+ (or the ambient `ctx.storage.persistent.set()` accessor) instead.
+ """
+ raise NotImplementedError(
+ "ExtensionStorageDAO.create() is not supported for extension "
+ "storage: it bypasses the locking, quota, and validation that "
+ "make writing a value safe. Use ctx.storage.persistent.set() "
+ "(or ExtensionStorageDAO.set() from backend code) instead."
+ )
+
+ # ── Delete ────────────────────────────────────────────────────────────────
+
+ @staticmethod
+ def delete_by_key(
+ extension_id: str,
+ key: str,
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+ ) -> bool:
+ """Delete a single entry by key. Returns True if a row was removed.
+
+ A single row is all there ever is to remove: `set()` commits its
+ upsert while still holding the extension-wide lock (see its
+ docstring), so two concurrent writes to the same scoped key can
+ never land as duplicate rows in the first place.
+ """
+ entry = (
+ db.session.query(ExtensionStorage)
+ .filter(
+ and_(
+ *_scope_filter(
+ extension_id, key, user_fk, resource_type, resource_uuid
+ )
+ )
+ )
+ .first()
+ )
+ if entry is None:
+ return False
+ db.session.delete(entry)
+ db.session.flush()
+ return True
diff --git a/superset/extensions/storage/persistent_model.py b/superset/extensions/storage/persistent_model.py
new file mode 100644
index 00000000000..1adc15db719
--- /dev/null
+++ b/superset/extensions/storage/persistent_model.py
@@ -0,0 +1,139 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import uuid as uuid_module
+
+from flask_appbuilder import Model
+from sqlalchemy import (
+ Boolean,
+ Column,
+ ForeignKey,
+ Index,
+ Integer,
+ LargeBinary,
+ String,
+ UniqueConstraint,
+)
+from sqlalchemy_utils import UUIDType
+from superset_core.extensions.storage.models import (
+ ExtensionStorageEntry as CoreExtensionStorageEntry,
+)
+
+from superset.models.helpers import AuditMixinNullable
+
+
+class ExtensionStorage(CoreExtensionStorageEntry, AuditMixinNullable, Model):
+ """Generic persistent key-value storage for extensions (Tier 3).
+
+ Each row is identified by (extension_id, user_fk, resource_type,
+ resource_uuid, key):
+
+ * Global scope — user_fk IS NULL, resource_type IS NULL
+ * User scope — user_fk set, resource_type IS NULL
+ * Resource scope — resource_type + resource_uuid set (user_fk optional)
+
+ The payload is stored as raw bytes (value) alongside the identifier of
+ the codec used to encode it (codec), so the same bytes can be decoded
+ back into a value on read. When is_encrypted is True the value has been
+ encrypted at the DAO layer using Fernet and must be decrypted before
+ decoding.
+ """
+
+ __tablename__ = "extension_storage"
+
+ id = Column(Integer, primary_key=True, autoincrement=True)
+ uuid = Column(
+ UUIDType(binary=True),
+ default=uuid_module.uuid4,
+ unique=True,
+ nullable=False,
+ )
+
+ # Extension identity
+ extension_id = Column(String(255), nullable=False)
+
+ # Scope discriminators — all nullable; NULLs define the scope (see docstring).
+ # No relationship() is declared for user_fk: extension storage rows are
+ # deleted at the database level when their owning user is (ondelete=
+ # "CASCADE"), and nothing reads through such a relationship, so there's
+ # no ORM object here for a future change to attach a cascade to.
+ # CASCADE (rather than SET NULL) is required here: setting user_fk to
+ # NULL would silently promote a deleted user's private rows into
+ # global/shared scope, exposing them to every user of the extension.
+ user_fk = Column(
+ Integer,
+ ForeignKey(
+ "ab_user.id",
+ ondelete="CASCADE",
+ name="fk_extension_storage_user_fk_ab_user",
+ ),
+ nullable=True,
+ )
+ # No FK here: resource_type is a free-form string naming the referenced
+ # table (a built-in Superset model or a resource type defined by another
+ # extension entirely), so the table a given row's resource_uuid points
+ # into varies per row and can't be fixed at the schema level.
+ resource_type = Column(String(64), nullable=True)
+ resource_uuid = Column(String(36), nullable=True)
+
+ # Storage key within the scope
+ key = Column(String(255), nullable=False)
+
+ # Payload. Size is bounded at the application level by
+ # EXTENSIONS_PERSISTENT_STORAGE["MAX_VALUE_SIZE"], enforced in
+ # ExtensionStorageDAO.set(), rather than by a fixed column length here.
+ value = Column(LargeBinary, nullable=False)
+ # Byte length of `value`, kept in sync at write time so the quota SUM in
+ # _check_quota() can be computed from this fixed-width column instead of
+ # reading (and, once TOASTed, detoasting) every extension's stored blobs.
+ value_size = Column(Integer, nullable=False)
+ codec = Column(String(255), nullable=False, default="json")
+ is_encrypted = Column(Boolean, nullable=False, default=False)
+
+ __table_args__ = (
+ # user_fk, resource_type, and resource_uuid are nullable, and
+ # standard SQL never treats NULL = NULL, so this constraint applies
+ # only when all three are non-NULL — a global/resource-scoped key
+ # (all three NULL) falls outside it.
+ UniqueConstraint(
+ "extension_id",
+ "user_fk",
+ "resource_type",
+ "resource_uuid",
+ "key",
+ name="uq_extension_storage_scoped_key",
+ ),
+ # Composite index covering all lookup dimensions
+ Index(
+ "ix_ext_storage_lookup",
+ "extension_id",
+ "user_fk",
+ "resource_type",
+ "resource_uuid",
+ "key",
+ ),
+ # Covers both extension_id-only lookups (leftmost prefix) and the
+ # quota SUM(value_size) query, letting the latter run as an
+ # index-only scan instead of touching the LargeBinary value column.
+ Index("ix_ext_storage_extension_id", "extension_id", "value_size"),
+ )
+
+ def __repr__(self) -> str:
+ return (
+ f"<ExtensionStorage {self.extension_id}/"
+ f"user={self.user_fk}/res={self.resource_type}/{self.key}>"
+ )
diff --git a/superset/extensions/storage/utils.py b/superset/extensions/storage/utils.py
new file mode 100644
index 00000000000..bdd9a537a9d
--- /dev/null
+++ b/superset/extensions/storage/utils.py
@@ -0,0 +1,112 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Shared helpers for extension storage (Tiers 2 and 3).
+
+Centralizes cache-key construction and context/user resolution used by the
+REST API (`api.py`) and the ambient `ephemeral`/`persistent` state accessors,
+so isolation and scoping logic is defined once rather than duplicated per
+call site.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from superset.extensions.context import get_current_extension_context
+from superset.extensions.types import LoadedExtension
+from superset.extensions.utils import get_extensions
+from superset.utils.core import get_user_id
+
+# Key separator
+SEPARATOR = ":"
+
+# Key prefix for extension storage
+KEY_PREFIX = "superset-ext"
+
+
+def build_cache_key(*parts: Any) -> str:
+ """Build a namespaced cache key from parts."""
+ return SEPARATOR.join(str(part) for part in parts)
+
+
+def build_storage_key(
+ extension_id: str, key: str, user_id: int | None, shared: bool
+) -> str:
+ """Build the cache key based on scope (user or shared)."""
+ if shared:
+ return build_cache_key(KEY_PREFIX, extension_id, "shared", key)
+ return build_cache_key(KEY_PREFIX, extension_id, "user", user_id, key)
+
+
+def get_extension_or_404(extension_id: str) -> LoadedExtension | None:
+ """Get extension by ID or return None if not found."""
+ extensions = get_extensions()
+ return extensions.get(extension_id)
+
+
+def parse_ttl(body: dict[str, Any]) -> tuple[int | None, str | None]:
+ """Parse TTL from a request body into a positive integer.
+
+ Only handles type coercion of the raw JSON value; the MAX_TTL business
+ rule is enforced once, in `ExtensionEphemeralDAO`, shared by both the
+ REST API and the ambient `ephemeral_state` accessor.
+
+ Returns:
+ (ttl, error_message) - error_message is set if the value is missing or invalid.
+ """
+ if "ttl" not in body:
+ return None, "Field 'ttl' is required"
+ try:
+ ttl = int(body["ttl"])
+ except (TypeError, ValueError):
+ return None, "Field 'ttl' must be a positive integer"
+ if ttl <= 0:
+ return None, "Field 'ttl' must be a positive integer"
+ return ttl, None
+
+
+def get_current_extension_id(caller: str) -> str:
+ """Get the current extension ID from context.
+
+ :param caller: Name of the calling accessor (e.g. "ephemeral_state",
+ "persistent_state"), used in the error message.
+ """
+ context = get_current_extension_context()
+ if context is None:
+ raise RuntimeError(
+ f"{caller} can only be used within an extension context. "
+ "Ensure this code is being executed during extension loading or "
+ "within an extension API request handler."
+ )
+ return context.extension.id
+
+
+def get_current_user_id(caller: str) -> int:
+ """Get the current authenticated user's ID.
+
+ :param caller: Name of the calling accessor (e.g. "ephemeral_state",
+ "persistent_state"), used in the error message.
+ """
+ user_id = get_user_id()
+ if user_id is None:
+ raise RuntimeError(
+ f"{caller} requires an authenticated user. "
+ "Ensure the request has been authenticated."
+ )
+ return user_id
diff --git a/superset/initialization/__init__.py b/superset/initialization/__init__.py
index c70f4844233..7cf9e49a0c8 100644
--- a/superset/initialization/__init__.py
+++ b/superset/initialization/__init__.py
@@ -294,8 +294,10 @@ class SupersetAppInitializer: # pylint: disable=too-many-public-methods
if feature_flag_manager.is_feature_enabled("ENABLE_EXTENSIONS"):
from superset.extensions.api import ExtensionsRestApi
+ from superset.extensions.storage.api import ExtensionStorageRestApi
appbuilder.add_api(ExtensionsRestApi)
+ appbuilder.add_api(ExtensionStorageRestApi)
if feature_flag_manager.is_feature_enabled("GLOBAL_TASK_FRAMEWORK"):
from superset.tasks.api import TaskRestApi
diff --git a/superset/key_value/types.py b/superset/key_value/types.py
index b33d6661488..fbc6cc56526 100644
--- a/superset/key_value/types.py
+++ b/superset/key_value/types.py
@@ -88,6 +88,23 @@ class PickleKeyValueCodec(KeyValueCodec):
return pickle.loads(value) # noqa: S301
+class BinaryKeyValueCodec(KeyValueCodec):
+ """Identity codec for raw bytes; stored as-is, no transformation applied.
+
+ JSON has no binary type, so a caller transporting this codec's value
+ over a JSON transport (e.g. a REST API) must carry it as a base64
+ string on the wire. That base64 encoding/decoding is a transport
+ concern handled by the REST layer around this codec, not something
+ this codec's `encode`/`decode` does itself.
+ """
+
+ def encode(self, value: bytes) -> bytes:
+ return value
+
+ def decode(self, value: bytes) -> bytes:
+ return value
+
+
class MarshmallowKeyValueCodec(JsonKeyValueCodec):
def __init__(self, schema: Schema):
self.schema = schema
diff --git a/superset/migrations/versions/2026-07-07_12-00_e5f6a7b8c9d0_add_extension_storage_table.py b/superset/migrations/versions/2026-07-07_12-00_e5f6a7b8c9d0_add_extension_storage_table.py
new file mode 100644
index 00000000000..41511519c44
--- /dev/null
+++ b/superset/migrations/versions/2026-07-07_12-00_e5f6a7b8c9d0_add_extension_storage_table.py
@@ -0,0 +1,109 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add_extension_storage_table
+
+Revision ID: e5f6a7b8c9d0
+Revises: d24e6b0a9c7f
+Create Date: 2026-06-23 12:00:00.000000
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = "e5f6a7b8c9d0"
+down_revision = "d24e6b0a9c7f"
+
+import sqlalchemy as sa # noqa: E402
+from alembic import op # noqa: E402
+from sqlalchemy_utils import UUIDType # noqa: E402
+
+
+def upgrade() -> None:
+ op.create_table(
+ "extension_storage",
+ sa.Column("id", sa.Integer(), nullable=False, autoincrement=True),
+ sa.Column("uuid", UUIDType(binary=True), nullable=False),
+ sa.Column("extension_id", sa.String(255), nullable=False),
+ sa.Column("user_fk", sa.Integer(), nullable=True),
+ sa.Column("resource_type", sa.String(64), nullable=True),
+ sa.Column("resource_uuid", sa.String(36), nullable=True),
+ sa.Column("key", sa.String(255), nullable=False),
+ sa.Column("value", sa.LargeBinary(), nullable=False),
+ sa.Column("value_size", sa.Integer(), nullable=False),
+ sa.Column(
+ "codec",
+ sa.String(255),
+ nullable=False,
+ server_default="json",
+ ),
+ sa.Column(
+ "is_encrypted",
+ sa.Boolean(),
+ nullable=False,
+ server_default=sa.false(),
+ ),
+ sa.Column("created_on", sa.DateTime(), nullable=True),
+ sa.Column("changed_on", sa.DateTime(), nullable=True),
+ sa.Column("created_by_fk", sa.Integer(), nullable=True),
+ sa.Column("changed_by_fk", sa.Integer(), nullable=True),
+ sa.ForeignKeyConstraint(
+ ["user_fk"],
+ ["ab_user.id"],
+ name="fk_extension_storage_user_fk_ab_user",
+ ondelete="CASCADE",
+ ),
+ sa.ForeignKeyConstraint(
+ ["created_by_fk"],
+ ["ab_user.id"],
+ name="fk_extension_storage_created_by_fk_ab_user",
+ ondelete="SET NULL",
+ ),
+ sa.ForeignKeyConstraint(
+ ["changed_by_fk"],
+ ["ab_user.id"],
+ name="fk_extension_storage_changed_by_fk_ab_user",
+ ondelete="SET NULL",
+ ),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint("uuid"),
+ sa.UniqueConstraint(
+ "extension_id",
+ "user_fk",
+ "resource_type",
+ "resource_uuid",
+ "key",
+ name="uq_extension_storage_scoped_key",
+ ),
+ )
+ # Covers both the extension_id-only lookups (leftmost prefix) and the
+ # quota SUM(value_size) query, letting the latter run as an index-only
+ # scan instead of touching the LargeBinary value column.
+ op.create_index(
+ "ix_ext_storage_extension_id",
+ "extension_storage",
+ ["extension_id", "value_size"],
+ )
+ op.create_index(
+ "ix_ext_storage_lookup",
+ "extension_storage",
+ ["extension_id", "user_fk", "resource_type", "resource_uuid", "key"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_ext_storage_lookup", "extension_storage")
+ op.drop_index("ix_ext_storage_extension_id", "extension_storage")
+ op.drop_table("extension_storage")
diff --git a/superset/tasks/decorators.py b/superset/tasks/decorators.py
index 0e29f84c102..1cd7ff6497c 100644
--- a/superset/tasks/decorators.py
+++ b/superset/tasks/decorators.py
@@ -119,9 +119,9 @@ def task(
if context := get_current_extension_context():
# Extension context: prefix task name to prevent collisions
- manifest = context.manifest
task_name = (
- f"extensions.{manifest.publisher}.{manifest.name}.{base_task_name}"
+ f"extensions.{context.extension.publisher}."
+ f"{context.extension.name}.{base_task_name}"
)
else:
# Host context: use original task name
diff --git a/superset/utils/cache_manager.py b/superset/utils/cache_manager.py
index 7ab54dead15..509c9b10110 100644
--- a/superset/utils/cache_manager.py
+++ b/superset/utils/cache_manager.py
@@ -193,15 +193,25 @@ class CacheManager:
self._thumbnail_cache = SupersetCache()
self._filter_state_cache = SupersetCache()
self._explore_form_data_cache = ExploreFormDataCache()
+ self._extension_ephemeral_state_cache = SupersetCache()
self._distributed_coordination: (
RedisCacheBackend | RedisSentinelCacheBackend | None
) = None
@staticmethod
def _init_cache(
- app: Flask, cache: Cache, cache_config_key: str, required: bool = False
+ app: Flask,
+ cache: Cache,
+ config: str | dict[str, Any],
+ required: bool = False,
) -> None:
- cache_config = app.config[cache_config_key]
+ if isinstance(config, dict):
+ cache_config = config
+ config_name = cache_config.get("CACHE_KEY_PREFIX", "unknown")
+ else:
+ cache_config = app.config[config]
+ config_name = config
+
cache_type = cache_config.get("CACHE_TYPE")
if (required and cache_type is None) or cache_type == "SupersetMetastoreCache":
if cache_type is None and not app.debug:
@@ -210,10 +220,10 @@ class CacheManager:
"metadata database, for the following cache: `%s`. "
"It is recommended to use `RedisCache`, `MemcachedCache` or "
"another dedicated caching backend for production deployments",
- cache_config_key,
+ config_name,
)
cache_type = CACHE_IMPORT_PATH
- cache_key_prefix = cache_config.get("CACHE_KEY_PREFIX", cache_config_key)
+ cache_key_prefix = cache_config.get("CACHE_KEY_PREFIX", config_name)
cache_config.update(
{"CACHE_TYPE": cache_type, "CACHE_KEY_PREFIX": cache_key_prefix}
)
@@ -237,6 +247,12 @@ class CacheManager:
"EXPLORE_FORM_DATA_CACHE_CONFIG",
required=True,
)
+ self._init_cache(
+ app,
+ self._extension_ephemeral_state_cache,
+ app.config.get("EXTENSIONS_EPHEMERAL_STORAGE", {}),
+ required=True,
+ )
self._init_distributed_coordination(app)
def _init_distributed_coordination(self, app: Flask) -> None:
@@ -284,6 +300,10 @@ class CacheManager:
def explore_form_data_cache(self) -> Cache:
return self._explore_form_data_cache
+ @property
+ def extension_ephemeral_state_cache(self) -> Cache:
+ return self._extension_ephemeral_state_cache
+
@property
def distributed_coordination(
self,
diff --git a/superset/utils/encrypt.py b/superset/utils/encrypt.py
index 217d60b8cb8..c0e22ef769c 100644
--- a/superset/utils/encrypt.py
+++ b/superset/utils/encrypt.py
@@ -49,6 +49,15 @@ ENCRYPTION_ENGINES: dict[str, type[EncryptionDecryptionBaseEngine]] = {
# The historical fallback engine when the config does not name one.
DEFAULT_ENCRYPTION_ENGINE_NAME = "aes"
+# Tables that store encrypted data in a plain column gated by a boolean flag
+# rather than using EncryptedType directly. Each entry is a 3-tuple of
+# (table_name, value_column, is_encrypted_flag_column). SecretsMigrator.run()
+# handles these via a second pass that SELECTs only flagged rows and re-encrypts
+# them with the same logic used for declared EncryptedType columns.
+CONDITIONAL_ENCRYPTED_TABLES: list[tuple[str, str, str]] = [
+ ("extension_storage", "value", "is_encrypted"),
+]
+
# Engines whose ciphertext is authenticated: a successful decrypt is
# cryptographic proof the value is genuinely in that form. AES-GCM carries an
# authentication tag; AES-CBC does not, so a CBC "success" can be coincidental.
@@ -516,6 +525,79 @@ class SecretsMigrator:
{**pk_bind, **re_encrypted_columns},
)
+ def _re_encrypt_conditional_table(
+ self,
+ conn: Connection,
+ table_name: str,
+ value_col: str,
+ flag_col: str,
+ stats: ReEncryptStats,
+ ) -> None:
+ """Re-encrypt rows in a conditionally-encrypted table.
+
+ Unlike declared EncryptedType columns, these tables store encrypted and
+ plaintext values in the same column, gated by a boolean flag.
+ Only rows where the flag is TRUE are selected and processed; plaintext
+ rows are never touched.
+
+ The value column type is read from table metadata, so the same
+ source-decryptor waterfall and idempotency logic from _re_encrypt_row
+ applies.
+ """
+ from flask_appbuilder import ( # pylint: disable=import-outside-toplevel
+ Model as FABModel,
+ )
+
+ tables: dict[str, Any] = dict(FABModel.metadata.tables)
+ for tname, tobj in self._db.metadata.tables.items():
+ tables.setdefault(tname, tobj)
+
+ table = tables.get(table_name)
+ if table is None:
+ logger.warning(
+ "Conditional-encrypted table %s not found in metadata; skipping",
+ table_name,
+ )
+ return
+
+ pk_columns = [c.name for c in table.primary_key.columns]
+ if not pk_columns:
+ logger.warning(
+ "Skipping %s: no primary key, cannot target rows for update",
+ table_name,
+ )
+ return
+
+ # Build a synthetic EncryptedType reflecting how data is currently
+ # stored (current engine + current key). _re_encrypt_row's
+ # _target_type / _source_decryptors machinery then handles key rotation
+ # and engine migration identically to any declared EncryptedType column.
+ engine_name = current_app.config.get(
+ "SQLALCHEMY_ENCRYPTED_FIELD_ENGINE", DEFAULT_ENCRYPTION_ENGINE_NAME
+ )
+ current_engine = resolve_encryption_engine(engine_name)
+ enc_type = EncryptedType(
+ table.columns[value_col].type,
+ key=self._secret_key,
+ engine=current_engine,
+ )
+
+ cols = ", ".join(pk_columns + [value_col])
+ rows = conn.execute(
+ text(
+ f"SELECT {cols} FROM {table_name} WHERE {flag_col} = true" # noqa: S608
+ )
+ )
+ for row in rows:
+ self._re_encrypt_row(
+ conn,
+ row,
+ table_name,
+ {value_col: enc_type},
+ pk_columns,
+ stats,
+ )
+
def run(self) -> ReEncryptStats:
"""
Re-encrypt every encrypted column in the ORM into the target form
@@ -550,6 +632,11 @@ class SecretsMigrator:
conn, row, table_name, columns, pk_columns, stats
)
+ for table_name, value_col, flag_col in CONDITIONAL_ENCRYPTED_TABLES:
+ self._re_encrypt_conditional_table(
+ conn, table_name, value_col, flag_col, stats
+ )
+
logger.info(
"Re-encryption summary: %d re-encrypted, %d skipped,"
" %d null, %d failed",
diff --git a/tests/unit_tests/extensions/storage/__init__.py b/tests/unit_tests/extensions/storage/__init__.py
new file mode 100644
index 00000000000..13a83393a91
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/__init__.py
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
diff --git a/tests/unit_tests/extensions/storage/conftest.py b/tests/unit_tests/extensions/storage/conftest.py
new file mode 100644
index 00000000000..cf57460ec00
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/conftest.py
@@ -0,0 +1,64 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Shared fixtures and helpers for extension storage tests."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+import pytest
+from flask import Flask, g
+from superset_core.extensions.types import Manifest
+
+from superset.extensions.context import ConcreteExtensionContext
+
+
+@pytest.fixture
+def app() -> Flask:
+ """Minimal Flask app for storage tests."""
+ flask_app = Flask(__name__)
+ flask_app.config["TESTING"] = True
+ # Mirrors the defaults set in superset/config.py, which are always
+ # present in a real Superset app.
+ flask_app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {}
+ flask_app.config["EXTENSIONS_PERSISTENT_STORAGE"] = {}
+ return flask_app
+
+
+def create_manifest(publisher: str = "test-org", name: str = "test-ext") -> Manifest:
+ """Create a test Manifest with the given publisher and name."""
+ return Manifest.model_validate(
+ {
+ "id": f"{publisher}.{name}",
+ "publisher": publisher,
+ "name": name,
+ "displayName": f"Test {name}",
+ }
+ )
+
+
+def create_context(
+ publisher: str = "test-org", name: str = "test-ext"
+) -> ConcreteExtensionContext:
+ """Create a ConcreteExtensionContext for the given publisher and name."""
+ return ConcreteExtensionContext(create_manifest(publisher, name))
+
+
+def set_user(user_id: int) -> None:
+ """Set a mock authenticated user on Flask's g object."""
+ g.user = MagicMock(id=user_id)
diff --git a/tests/unit_tests/extensions/storage/test_api.py b/tests/unit_tests/extensions/storage/test_api.py
new file mode 100644
index 00000000000..c5f81547e7d
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/test_api.py
@@ -0,0 +1,1146 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for the Extension Storage REST API endpoint handler logic.
+
+Pure helper functions (`parse_ttl`, `get_extension_or_404`, etc.) are shared
+across call sites and tested once in `superset.extensions.storage.utils`;
+see `test_utils.py`. Ephemeral (Tier 2) cache access and MAX_TTL/
+MAX_VALUE_SIZE validation live in `ExtensionEphemeralDAO`, tested in
+`test_ephemeral_dao.py`; these tests mock that DAO to verify the endpoints
+call into it correctly.
+"""
+
+from __future__ import annotations
+
+import base64
+from unittest.mock import MagicMock, patch
+
+from flask import Flask, g
+from flask_babel import Babel
+
+from superset.extensions.storage.api import ExtensionStorageRestApi
+from superset.extensions.storage.codecs import get_codec
+from superset.extensions.storage.ephemeral_dao import (
+ ExtensionEphemeralTTLInvalid,
+ ExtensionEphemeralValueTooLarge,
+)
+from superset.extensions.storage.persistent_dao import (
+ ExtensionStorageListEntry,
+ ExtensionStorageListPayloadTooLarge,
+ ExtensionStorageQuotaExceeded,
+ ExtensionStorageValueTooLarge,
+)
+
+# ── Ephemeral GET / PUT / DELETE endpoint logic ──────────────────────────────
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_get_delegates_to_dao(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """get_ephemeral calls ExtensionEphemeralDAO.get_raw with the right scope."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_dao.get_raw.return_value = (get_codec("json").encode({"data": 42}), "json")
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/my-key"
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().get_ephemeral(
+ "acme", "dashboard", "my-key"
+ )
+
+ assert status_code == 200
+ assert body.get_json()["result"] == {"data": 42}
+ assert body.get_json()["codec"] == "json"
+ mock_dao.get_raw.assert_called_once_with(
+ "acme.dashboard", "my-key", shared=False
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_get_returns_none_when_entry_missing(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """get_ephemeral returns result=None without a codec check when absent."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_dao.get_raw.return_value = None
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/missing"
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().get_ephemeral(
+ "acme", "dashboard", "missing"
+ )
+
+ assert status_code == 200
+ assert body.get_json()["result"] is None
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_get_returns_400_for_unsafe_stored_codec(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """get_ephemeral returns 400 when the stored value's codec is not in
+ SAFE_CODECS, rather than attempting to decode/return it over the API."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_dao.get_raw.return_value = (get_codec("pickle").encode({"x": 1}), "pickle")
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/my-key"
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().get_ephemeral(
+ "acme", "dashboard", "my-key"
+ )
+
+ assert status_code == 400
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_get_returns_binary_value_base64_encoded(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """get_ephemeral base64-encodes a binary-codec value for the response
+ and flags it with isBinary=True, since JSON has no byte type. Checked
+ on the decoded value's actual type, not the codec's name."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ raw_bytes = b"\x89PNG\r\n"
+ mock_dao.get_raw.return_value = (get_codec("binary").encode(raw_bytes), "binary")
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/logo"
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().get_ephemeral(
+ "acme", "dashboard", "logo"
+ )
+
+ assert status_code == 200
+ payload = body.get_json()
+ assert payload["result"] == base64.b64encode(raw_bytes).decode("ascii")
+ assert payload["codec"] == "binary"
+ assert payload["isBinary"] is True
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_set_passes_ttl_and_value_to_dao(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """set_ephemeral parses TTL from the body and delegates to the DAO."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/job",
+ method="PUT",
+ json={"value": {"progress": 50}, "ttl": 600},
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().set_ephemeral(
+ "acme", "dashboard", "job"
+ )
+
+ assert status_code == 200
+ mock_dao.set.assert_called_once_with(
+ "acme.dashboard", "job", {"progress": 50}, 600, codec="json", shared=False
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_set_with_binary_flag_decodes_base64(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """set_ephemeral base64-decodes 'value' before handing it to the DAO
+ when 'isBinary' is true, independent of which codec was chosen."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ raw_bytes = b"\x89PNG\r\n"
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/logo",
+ method="PUT",
+ json={
+ "value": base64.b64encode(raw_bytes).decode("ascii"),
+ "codec": "binary",
+ "isBinary": True,
+ "ttl": 600,
+ },
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().set_ephemeral(
+ "acme", "dashboard", "logo"
+ )
+
+ assert status_code == 200
+ mock_dao.set.assert_called_once_with(
+ "acme.dashboard", "logo", raw_bytes, 600, codec="binary", shared=False
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_set_rejects_invalid_base64_when_binary_flag_set(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """set_ephemeral returns 400 when 'isBinary' is true but 'value' is not
+ valid base64, and never calls the DAO."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/logo",
+ method="PUT",
+ json={"value": "not-base64!!", "isBinary": True, "ttl": 600},
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().set_ephemeral(
+ "acme", "dashboard", "logo"
+ )
+
+ assert status_code == 400
+ mock_dao.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_set_rejects_unsafe_codec(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """set_ephemeral returns 400 when 'codec' is not in SAFE_CODECS, and never
+ calls the DAO — pickle deserialization must not be reachable from the API.
+ """
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/job",
+ method="PUT",
+ json={"value": {"progress": 50}, "ttl": 600, "codec": "pickle"},
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().set_ephemeral(
+ "acme", "dashboard", "job"
+ )
+
+ assert status_code == 400
+ assert "not allowed" in body.get_json()["message"].lower()
+ mock_dao.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_set_rejects_non_string_codec(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """set_ephemeral returns 400, rather than a 500 from an unhashable-type
+ membership check, when 'codec' is a non-string JSON value (e.g. a list).
+ """
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/job",
+ method="PUT",
+ json={"value": {"progress": 50}, "ttl": 600, "codec": ["json"]},
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().set_ephemeral(
+ "acme", "dashboard", "job"
+ )
+
+ assert status_code == 400
+ mock_dao.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_set_returns_400_on_ttl_invalid(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """set_ephemeral returns a 400 when the DAO rejects the TTL."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_dao.set.side_effect = ExtensionEphemeralTTLInvalid("TTL too large")
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/job",
+ method="PUT",
+ json={"value": {"progress": 50}, "ttl": 999999},
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().set_ephemeral(
+ "acme", "dashboard", "job"
+ )
+
+ assert status_code == 400
+ assert "TTL too large" in body.get_json()["message"]
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_set_returns_400_on_value_too_large(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """set_ephemeral returns a 400 when the DAO rejects an oversized value."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_dao.set.side_effect = ExtensionEphemeralValueTooLarge("Value too large")
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/job",
+ method="PUT",
+ json={"value": "x" * 1000, "ttl": 300},
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().set_ephemeral(
+ "acme", "dashboard", "job"
+ )
+
+ assert status_code == 400
+ assert "Value too large" in body.get_json()["message"]
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_delete_delegates_to_dao(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """delete_ephemeral calls ExtensionEphemeralDAO.delete with the right scope."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/to-delete",
+ method="DELETE",
+ ):
+ g.user = MagicMock(id=7)
+
+ body, status_code = ExtensionStorageRestApi().delete_ephemeral(
+ "acme", "dashboard", "to-delete"
+ )
+
+ assert status_code == 200
+ mock_dao.delete.assert_called_once_with(
+ "acme.dashboard", "to-delete", shared=False
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionEphemeralDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_ephemeral_shared_query_param_uses_shared_scope(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """?shared=true passes shared=True through to the DAO instead of scoping by user."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_dao.get_raw.return_value = (get_codec("json").encode("shared-data"), "json")
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/ephemeral/config?shared=true"
+ ):
+ g.user = MagicMock(id=99)
+
+ body, status_code = ExtensionStorageRestApi().get_ephemeral(
+ "acme", "dashboard", "config"
+ )
+
+ assert status_code == 200
+ assert body.get_json()["result"] == "shared-data"
+ mock_dao.get_raw.assert_called_once_with(
+ "acme.dashboard", "config", shared=True
+ )
+
+
+# ── Persistent GET / PUT / DELETE endpoint logic ─────────────────────────────
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_get_user_scoped(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent GET with user scope passes user_fk to DAO."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.get_value.return_value = b'{"theme":"dark"}'
+
+ with app.app_context():
+ g.user = MagicMock(id=42)
+
+ extension_id = "acme.dashboard"
+ user_fk = g.user.id
+ raw = mock_dao.get_value(extension_id, "prefs", user_fk=user_fk)
+
+ assert raw == b'{"theme":"dark"}'
+ mock_dao.get_value.assert_called_once_with(
+ "acme.dashboard", "prefs", user_fk=42
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_get_shared_scope(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent GET with shared=True passes user_fk=None to DAO."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.get_value.return_value = b'{"version":2}'
+
+ with app.app_context():
+ g.user = MagicMock(id=42)
+
+ extension_id = "acme.dashboard"
+ raw = mock_dao.get_value(extension_id, "config", user_fk=None)
+
+ assert raw == b'{"version":2}'
+ mock_dao.get_value.assert_called_once_with(
+ "acme.dashboard", "config", user_fk=None
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_encodes_and_stores(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT encodes value as JSON bytes and calls DAO.set."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.app_context():
+ g.user = MagicMock(id=42)
+
+ from superset.utils import json
+
+ extension_id = "acme.dashboard"
+ value = {"theme": "dark"}
+ value_bytes = json.dumps(value).encode()
+ mock_dao.set(extension_id, "prefs", value_bytes, user_fk=42, encrypt=False)
+
+ mock_dao.set.assert_called_once_with(
+ "acme.dashboard", "prefs", value_bytes, user_fk=42, encrypt=False
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_encrypt_flag(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT passes encrypt=True to DAO when encrypt=True in body."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.app_context():
+ g.user = MagicMock(id=42)
+
+ from superset.utils import json
+
+ extension_id = "acme.dashboard"
+ value = {"secret": "token"}
+ value_bytes = json.dumps(value).encode()
+ mock_dao.set(extension_id, "token", value_bytes, user_fk=42, encrypt=True)
+
+ mock_dao.set.assert_called_once_with(
+ "acme.dashboard", "token", value_bytes, user_fk=42, encrypt=True
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_delete_calls_dao(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent DELETE calls DAO.delete_by_key with correct scope."""
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.app_context():
+ g.user = MagicMock(id=42)
+
+ extension_id = "acme.dashboard"
+ mock_dao.delete_by_key(extension_id, "prefs", user_fk=42)
+
+ mock_dao.delete_by_key.assert_called_once_with(
+ "acme.dashboard", "prefs", user_fk=42
+ )
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_returns_413_on_quota_exceeded(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT returns a 413 response when the DAO raises quota-exceeded."""
+ Babel(app)
+ # Bypass @protect()'s auth checks via its public-resource short-circuit,
+ # so this test exercises route logic (the quota except-branch) without
+ # standing up the full Flask-AppBuilder security stack.
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.set.side_effect = ExtensionStorageQuotaExceeded("acme.dashboard", 100)
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/prefs",
+ method="PUT",
+ json={"value": {"theme": "dark"}},
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().set_persistent(
+ "acme", "dashboard", "prefs"
+ )
+
+ assert status_code == 413
+ assert "quota" in body.get_json()["message"].lower()
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_returns_400_on_value_too_large(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT returns a 400 response when the DAO rejects an
+ oversized value."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.set.side_effect = ExtensionStorageValueTooLarge(10)
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/prefs",
+ method="PUT",
+ json={"value": "x" * 1000},
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().set_persistent(
+ "acme", "dashboard", "prefs"
+ )
+
+ assert status_code == 400
+ assert "exceeds" in body.get_json()["message"].lower()
+
+
+# ── Persistent codec validation ──────────────────────────────────────────────
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_rejects_unsafe_codec(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT returns 400 when 'codec' is not in SAFE_CODECS, and never
+ calls the DAO — pickle deserialization must not be reachable from the API.
+ """
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/prefs",
+ method="PUT",
+ json={"value": "sk-...", "codec": "pickle"},
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().set_persistent(
+ "acme", "dashboard", "prefs"
+ )
+
+ assert status_code == 400
+ assert "not allowed" in body.get_json()["message"].lower()
+ mock_dao.set.assert_not_called()
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_rejects_non_string_codec(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT returns 400, rather than a 500 from an unhashable-type
+ membership check, when 'codec' is a non-string JSON value (e.g. a list).
+ """
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/prefs",
+ method="PUT",
+ json={"value": "sk-...", "codec": ["json"]},
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().set_persistent(
+ "acme", "dashboard", "prefs"
+ )
+
+ assert status_code == 400
+ mock_dao.set.assert_not_called()
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_returns_400_when_isbinary_codec_mismatch(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT returns 400, rather than a 500 from an uncaught codec
+ encode error, when 'isBinary' decodes 'value' to raw bytes but 'codec'
+ (e.g. the default "json") can't encode a bytes value."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/prefs",
+ method="PUT",
+ json={"value": "aGVsbG8=", "isBinary": True},
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().set_persistent(
+ "acme", "dashboard", "prefs"
+ )
+
+ assert status_code == 400
+ mock_dao.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_defaults_codec_to_json(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT without a 'codec' field encodes with json and stores
+ codec="json" on the entry."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/prefs",
+ method="PUT",
+ json={"value": {"theme": "dark"}},
+ ):
+ g.user = MagicMock(id=42)
+
+ ExtensionStorageRestApi().set_persistent("acme", "dashboard", "prefs")
+
+ from superset.utils import json
+
+ mock_dao.set.assert_called_once_with(
+ "acme.dashboard",
+ "prefs",
+ json.dumps({"theme": "dark"}).encode(),
+ codec="json",
+ user_fk=42,
+ encrypt=False,
+ )
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_with_binary_flag_decodes_base64(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT base64-decodes 'value' before encoding it with 'codec'
+ when 'isBinary' is true, independent of which codec was chosen."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ raw_bytes = b"\x89PNG\r\n"
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/logo",
+ method="PUT",
+ json={
+ "value": base64.b64encode(raw_bytes).decode("ascii"),
+ "codec": "binary",
+ "isBinary": True,
+ },
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().set_persistent(
+ "acme", "dashboard", "logo"
+ )
+
+ assert status_code == 200
+ mock_dao.set.assert_called_once_with(
+ "acme.dashboard",
+ "logo",
+ raw_bytes,
+ codec="binary",
+ user_fk=42,
+ encrypt=False,
+ )
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_set_rejects_invalid_base64_when_binary_flag_set(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """Persistent PUT returns 400 when 'isBinary' is true but 'value' is not
+ valid base64, and never calls the DAO."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/logo",
+ method="PUT",
+ json={"value": "not-base64!!", "codec": "binary", "isBinary": True},
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().set_persistent(
+ "acme", "dashboard", "logo"
+ )
+
+ assert status_code == 400
+ mock_dao.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_get_returns_400_for_unsafe_stored_codec(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent GET returns 400 when the stored entry's codec is not in
+ SAFE_CODECS, rather than attempting to decode/return it over the API."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ entry = MagicMock()
+ entry.codec = "pickle"
+ mock_dao.get.return_value = entry
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/prefs"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().get_persistent(
+ "acme", "dashboard", "prefs"
+ )
+
+ assert status_code == 400
+ mock_dao.decode_entry.assert_not_called()
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_get_returns_none_when_entry_missing(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent GET returns result=None without a codec check when absent."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.get.return_value = None
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/missing"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().get_persistent(
+ "acme", "dashboard", "missing"
+ )
+
+ assert status_code == 200
+ assert body.get_json()["result"] is None
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_persistent_get_returns_binary_value_base64_encoded(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Persistent GET base64-encodes a binary-codec value for the response
+ and flags it with isBinary=True."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ entry = MagicMock()
+ entry.codec = "binary"
+ mock_dao.get.return_value = entry
+ raw_bytes = b"\x89PNG\r\n"
+ mock_dao.decode_entry.return_value = raw_bytes
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent/logo"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().get_persistent(
+ "acme", "dashboard", "logo"
+ )
+
+ assert status_code == 200
+ payload = body.get_json()
+ assert payload["result"] == base64.b64encode(raw_bytes).decode("ascii")
+ assert payload["codec"] == "binary"
+ assert payload["isBinary"] is True
+
+
+# ── Persistent list endpoint ──────────────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_list_persistent_returns_decoded_entries_and_count(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """list_persistent decodes each safe-codec entry's value and returns
+ the total count alongside the page."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.list_entries.return_value = (
+ [
+ ExtensionStorageListEntry(
+ key="prefs",
+ value=b'{"theme": "dark"}',
+ codec="json",
+ is_encrypted=False,
+ ),
+ ],
+ 1,
+ )
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().list_persistent(
+ "acme", "dashboard"
+ )
+
+ assert status_code == 200
+ payload = body.get_json()
+ assert payload["count"] == 1
+ assert payload["result"] == [
+ {
+ "key": "prefs",
+ "value": {"theme": "dark"},
+ "codec": "json",
+ "isBinary": False,
+ }
+ ]
+ mock_dao.list_entries.assert_called_once_with(
+ "acme.dashboard",
+ user_fk=42,
+ resource_type=None,
+ resource_uuid=None,
+ page=0,
+ page_size=10,
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_list_persistent_omits_value_for_unsafe_codec(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """An entry stored with a codec outside SAFE_CODECS (e.g. pickle) comes
+ back with value=null, but the row and its codec are still listed."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.list_entries.return_value = (
+ [
+ ExtensionStorageListEntry(
+ key="secret",
+ value=b"\x80pickled",
+ codec="pickle",
+ is_encrypted=False,
+ ),
+ ],
+ 1,
+ )
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().list_persistent(
+ "acme", "dashboard"
+ )
+
+ assert status_code == 200
+ result = body.get_json()["result"]
+ assert result == [
+ {
+ "key": "secret",
+ "value": None,
+ "codec": "pickle",
+ "isBinary": False,
+ }
+ ]
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_list_persistent_flags_binary_entries_as_base64(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """list_persistent base64-encodes a binary-codec entry's value and
+ flags it with isBinary=True."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ raw_bytes = b"\x89PNG\r\n"
+ mock_dao.list_entries.return_value = (
+ [
+ ExtensionStorageListEntry(
+ key="logo",
+ value=get_codec("binary").encode(raw_bytes),
+ codec="binary",
+ is_encrypted=False,
+ ),
+ ],
+ 1,
+ )
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().list_persistent(
+ "acme", "dashboard"
+ )
+
+ assert status_code == 200
+ assert body.get_json()["result"] == [
+ {
+ "key": "logo",
+ "value": base64.b64encode(raw_bytes).decode("ascii"),
+ "codec": "binary",
+ "isBinary": True,
+ }
+ ]
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_list_persistent_passes_query_params_to_dao(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """Query params (resource_type, resource_uuid, page, page_size, shared)
+ are parsed and passed through to the DAO."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.list_entries.return_value = ([], 0)
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent"
+ "?shared=true&resource_type=dashboard&resource_uuid=uuid-1"
+ "&page=2&page_size=25"
+ ):
+ g.user = MagicMock(id=42)
+
+ ExtensionStorageRestApi().list_persistent("acme", "dashboard")
+
+ mock_dao.list_entries.assert_called_once_with(
+ "acme.dashboard",
+ user_fk=None,
+ resource_type="dashboard",
+ resource_uuid="uuid-1",
+ page=2,
+ page_size=25,
+ )
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_list_persistent_returns_400_for_non_integer_page(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """A non-integer page/page_size query param returns 400 rather than a
+ 500 from a failed int() conversion."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent?page=not-a-number"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().list_persistent(
+ "acme", "dashboard"
+ )
+
+ assert status_code == 400
+ mock_dao.list_entries.assert_not_called()
+
+
+@patch("superset.extensions.storage.api.ExtensionStorageDAO")
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_list_persistent_returns_400_on_payload_too_large(
+ mock_get_ext: MagicMock, mock_dao: MagicMock, app: Flask
+) -> None:
+ """list_persistent returns 400 when the DAO rejects the page for
+ exceeding MAX_LIST_PAYLOAD_SIZE."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {"acme.dashboard": MagicMock()}
+ mock_dao.list_entries.side_effect = ExtensionStorageListPayloadTooLarge(100, 50)
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().list_persistent(
+ "acme", "dashboard"
+ )
+
+ assert status_code == 400
+
+
+@patch("superset.extensions.storage.utils.get_extensions")
+def test_list_persistent_returns_404_for_missing_extension(
+ mock_get_ext: MagicMock, app: Flask
+) -> None:
+ """list_persistent returns 404 when the extension does not exist."""
+ Babel(app)
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm.is_item_public.return_value = True
+ mock_get_ext.return_value = {}
+
+ with app.test_request_context(
+ "/api/v1/extensions/acme/dashboard/storage/persistent"
+ ):
+ g.user = MagicMock(id=42)
+
+ body, status_code = ExtensionStorageRestApi().list_persistent(
+ "acme", "dashboard"
+ )
+
+ assert status_code == 404
+
+
+# ── Extension ID reconstruction ──────────────────────────────────────────────
+
+
+def test_extension_id_reconstruction():
+ """Verify publisher + name are correctly joined to form extension_id."""
+ publisher = "acme"
+ name = "dashboard"
+ extension_id = f"{publisher}.{name}"
+ assert extension_id == "acme.dashboard"
+
+
+def test_extension_id_with_special_characters():
+ """Extension ID supports publisher/name with hyphens."""
+ publisher = "my-org"
+ name = "my-ext"
+ extension_id = f"{publisher}.{name}"
+ assert extension_id == "my-org.my-ext"
+
+
+# ── Missing value field ─────────────────────────────────────────────────────
+
+
+def test_set_ephemeral_requires_value_field():
+ """PUT body must contain 'value' field — test the validation logic."""
+ body = {"ttl": 300} # missing 'value'
+ assert "value" not in body
+
+
+def test_set_persistent_requires_value_field():
+ """PUT body must contain 'value' field — test the validation logic."""
+ body = {"some_other_field": True} # missing 'value'
+ assert "value" not in body
diff --git a/tests/unit_tests/extensions/storage/test_codecs.py b/tests/unit_tests/extensions/storage/test_codecs.py
new file mode 100644
index 00000000000..e630ac0901f
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/test_codecs.py
@@ -0,0 +1,94 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for the extension storage codec registry."""
+
+from __future__ import annotations
+
+import pytest
+
+from superset.extensions.storage.codecs import (
+ DEFAULT_CODEC,
+ get_codec,
+ SAFE_CODECS,
+ UnknownCodecError,
+)
+from superset.key_value.types import (
+ BinaryKeyValueCodec,
+ JsonKeyValueCodec,
+ PickleKeyValueCodec,
+)
+
+
+def test_get_codec_returns_json_codec() -> None:
+ """'json' resolves to a JsonKeyValueCodec instance."""
+ assert isinstance(get_codec("json"), JsonKeyValueCodec)
+
+
+def test_get_codec_returns_pickle_codec() -> None:
+ """'pickle' resolves to a PickleKeyValueCodec instance."""
+ assert isinstance(get_codec("pickle"), PickleKeyValueCodec)
+
+
+def test_get_codec_raises_for_unknown_name() -> None:
+ """An unregistered codec identifier raises UnknownCodecError."""
+ with pytest.raises(UnknownCodecError):
+ get_codec("yaml")
+
+
+def test_json_round_trips_through_registry() -> None:
+ """A value encoded via the registry's json codec decodes back unchanged."""
+ codec = get_codec("json")
+ encoded = codec.encode({"a": 1})
+ assert codec.decode(encoded) == {"a": 1}
+
+
+def test_default_codec_is_json() -> None:
+ """DEFAULT_CODEC resolves to the json codec."""
+ assert DEFAULT_CODEC == "json"
+ assert isinstance(get_codec(DEFAULT_CODEC), JsonKeyValueCodec)
+
+
+def test_pickle_is_not_a_safe_codec() -> None:
+ """'pickle' is excluded from SAFE_CODECS since it can deserialize
+ arbitrary code and must not be reachable from the REST API."""
+ assert "pickle" not in SAFE_CODECS
+
+
+def test_json_is_a_safe_codec() -> None:
+ """'json' is included in SAFE_CODECS."""
+ assert "json" in SAFE_CODECS
+
+
+def test_binary_is_a_safe_codec() -> None:
+ """'binary' is included in SAFE_CODECS — it stores raw bytes as-is,
+ with no code-execution risk on decode."""
+ assert "binary" in SAFE_CODECS
+
+
+def test_get_codec_returns_binary_codec() -> None:
+ """'binary' resolves to a BinaryKeyValueCodec instance."""
+ assert isinstance(get_codec("binary"), BinaryKeyValueCodec)
+
+
+def test_binary_round_trips_through_registry() -> None:
+ """Raw bytes encoded via the registry's binary codec decode back
+ unchanged."""
+ codec = get_codec("binary")
+ raw = b"binary\x00data"
+ assert codec.encode(raw) == raw
+ assert codec.decode(raw) == raw
diff --git a/tests/unit_tests/extensions/storage/test_context.py b/tests/unit_tests/extensions/storage/test_context.py
new file mode 100644
index 00000000000..732b08ae09d
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/test_context.py
@@ -0,0 +1,124 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for extension context management."""
+
+import pytest
+
+from superset.extensions.context import (
+ ConcreteExtensionContext,
+ extension_context,
+ get_context,
+ get_current_extension_context,
+ use_context,
+)
+from tests.unit_tests.extensions.storage.conftest import create_manifest
+
+
+def test_get_context_raises_outside_context():
+ """get_context() raises RuntimeError when called outside extension context."""
+ with pytest.raises(
+ RuntimeError, match="must be called within an extension context"
+ ):
+ get_context()
+
+
+def test_get_current_extension_context_returns_none_outside_context():
+ """get_current_extension_context() returns None when called outside context."""
+ assert get_current_extension_context() is None
+
+
+def test_use_context_sets_and_restores_context():
+ """use_context() sets context during execution and restores None after."""
+ manifest = create_manifest()
+ ctx = ConcreteExtensionContext(manifest)
+
+ assert get_current_extension_context() is None
+
+ with use_context(ctx):
+ assert get_current_extension_context() is ctx
+ assert get_context() is ctx
+
+ assert get_current_extension_context() is None
+
+
+def test_use_context_supports_nesting():
+ """use_context() properly handles nested context switches."""
+ manifest1 = create_manifest("org1", "ext1")
+ manifest2 = create_manifest("org2", "ext2")
+ ctx1 = ConcreteExtensionContext(manifest1)
+ ctx2 = ConcreteExtensionContext(manifest2)
+
+ with use_context(ctx1):
+ assert get_context().extension.id == "org1.ext1"
+
+ with use_context(ctx2):
+ assert get_context().extension.id == "org2.ext2"
+
+ # ctx1 is restored after inner context exits
+ assert get_context().extension.id == "org1.ext1"
+
+ assert get_current_extension_context() is None
+
+
+def test_extension_context_creates_and_sets_context():
+ """extension_context() creates context from manifest and sets it."""
+ manifest = create_manifest("my-org", "my-ext")
+
+ with extension_context(manifest) as ctx:
+ assert ctx.extension is manifest
+ assert get_context() is ctx
+ assert get_context().extension.id == "my-org.my-ext"
+
+ assert get_current_extension_context() is None
+
+
+def test_context_provides_extension_property():
+ """Context provides extension property as alias for manifest."""
+ manifest = create_manifest()
+ ctx = ConcreteExtensionContext(manifest)
+
+ with use_context(ctx):
+ assert get_context().extension is manifest
+ assert get_context().extension.id == manifest.id
+
+
+def test_context_provides_storage_property():
+ """Context provides storage property with ephemeral tier."""
+ manifest = create_manifest()
+ ctx = ConcreteExtensionContext(manifest)
+
+ with use_context(ctx):
+ storage = get_context().storage
+ assert storage is not None
+ assert hasattr(storage, "ephemeral")
+
+
+def test_context_exception_still_restores():
+ """Context is properly restored even when exception occurs."""
+ manifest = create_manifest()
+ ctx = ConcreteExtensionContext(manifest)
+
+ def raise_in_context() -> None:
+ with use_context(ctx):
+ assert get_current_extension_context() is ctx
+ raise ValueError("test error")
+
+ with pytest.raises(ValueError, match="test error"):
+ raise_in_context()
+
+ assert get_current_extension_context() is None
diff --git a/tests/unit_tests/extensions/storage/test_ephemeral.py b/tests/unit_tests/extensions/storage/test_ephemeral.py
new file mode 100644
index 00000000000..06284cfddf3
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/test_ephemeral.py
@@ -0,0 +1,276 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for the ephemeral state ambient accessor (ephemeral.py).
+
+Cache-key construction, TTL/MAX_VALUE_SIZE validation live in
+`ExtensionEphemeralDAO` (`ephemeral_dao.py`) and are tested once in
+`test_ephemeral_dao.py`; these tests cover the accessor's context/user
+resolution and delegation to that DAO.
+"""
+
+from __future__ import annotations
+
+import base64
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+from flask_babel import Babel
+
+from superset.extensions.context import use_context
+from superset.extensions.storage.codecs import get_codec
+from superset.extensions.storage.ephemeral import EphemeralSetOptions, EphemeralState
+from superset.extensions.storage.ephemeral_dao import (
+ ExtensionEphemeralTTLInvalid,
+ ExtensionEphemeralValueTooLarge,
+)
+from tests.unit_tests.extensions.storage.conftest import (
+ create_context,
+ set_user,
+)
+
+
+def _envelope(value: Any, codec: str = "json") -> dict[str, str]:
+ """Build the cache envelope ExtensionEphemeralDAO stores values as."""
+ encoded = get_codec(codec).encode(value)
+ return {"codec": codec, "value": base64.b64encode(encoded).decode("ascii")}
+
+
+def test_ephemeral_state_raises_without_context(app: Flask) -> None:
+ """EphemeralState operations raise RuntimeError without extension context."""
+ with app.app_context():
+ set_user(1)
+
+ with pytest.raises(RuntimeError, match="within an extension context"):
+ EphemeralState.get("key")
+
+ with pytest.raises(RuntimeError, match="within an extension context"):
+ EphemeralState.set("key", "value", EphemeralSetOptions(ttl=300))
+
+ with pytest.raises(RuntimeError, match="within an extension context"):
+ EphemeralState.remove("key")
+
+
+def test_ephemeral_state_raises_without_user(app: Flask) -> None:
+ """EphemeralState operations raise RuntimeError without authenticated user."""
+ ctx = create_context()
+
+ with app.app_context(), use_context(ctx):
+ # No user set on g
+ with pytest.raises(RuntimeError, match="requires an authenticated user"):
+ EphemeralState.get("key")
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_ephemeral_state_get_builds_correct_key(mock_cm: MagicMock, app: Flask) -> None:
+ """EphemeralState.get() builds user-scoped key and calls cache.get()."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = _envelope({"data": "test"})
+
+ ctx = create_context("my-org", "my-ext")
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ result = EphemeralState.get("my-key")
+
+ expected_key = "superset-ext:my-org.my-ext:user:42:my-key"
+ mock_cache.get.assert_called_once_with(expected_key)
+ assert result == {"data": "test"}
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_ephemeral_state_set_builds_correct_key_and_uses_ttl(
+ mock_cm: MagicMock, app: Flask
+) -> None:
+ """EphemeralState.set() builds user-scoped key and passes TTL to cache."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ ctx = create_context("my-org", "my-ext")
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ EphemeralState.set("my-key", {"value": 123}, EphemeralSetOptions(ttl=600))
+
+ expected_key = "superset-ext:my-org.my-ext:user:42:my-key"
+ mock_cache.set.assert_called_once_with(
+ expected_key, _envelope({"value": 123}), timeout=600
+ )
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_ephemeral_state_set_uses_given_codec(mock_cm: MagicMock, app: Flask) -> None:
+ """EphemeralState.set() encodes the value with options.codec."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ ctx = create_context("my-org", "my-ext")
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ EphemeralState.set(
+ "my-key", {"value": 123}, EphemeralSetOptions(ttl=600, codec="pickle")
+ )
+
+ expected_key = "superset-ext:my-org.my-ext:user:42:my-key"
+ mock_cache.set.assert_called_once_with(
+ expected_key, _envelope({"value": 123}, codec="pickle"), timeout=600
+ )
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_ephemeral_state_set_rejects_ttl_exceeding_max(
+ mock_cm: MagicMock, app: Flask
+) -> None:
+ """EphemeralState.set() raises when ttl exceeds MAX_TTL, same as the REST API."""
+ app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {"MAX_TTL": 3600}
+ Babel(app)
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ ctx = create_context()
+
+ with app.app_context(), use_context(ctx):
+ set_user(1)
+ with pytest.raises(ExtensionEphemeralTTLInvalid):
+ EphemeralState.set("key", "value", EphemeralSetOptions(ttl=7200))
+
+ mock_cache.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_ephemeral_state_set_rejects_value_exceeding_max_size(
+ mock_cm: MagicMock, app: Flask
+) -> None:
+ """EphemeralState.set() raises when value exceeds MAX_VALUE_SIZE."""
+ app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {"MAX_VALUE_SIZE": 10}
+ Babel(app)
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ ctx = create_context()
+
+ with app.app_context(), use_context(ctx):
+ set_user(1)
+ with pytest.raises(ExtensionEphemeralValueTooLarge):
+ EphemeralState.set("key", "x" * 100, EphemeralSetOptions(ttl=300))
+
+ mock_cache.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_ephemeral_state_remove_deletes_key(mock_cm: MagicMock, app: Flask) -> None:
+ """EphemeralState.remove() calls cache.delete() with correct key."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ ctx = create_context("org", "ext")
+
+ with app.app_context(), use_context(ctx):
+ set_user(99)
+ EphemeralState.remove("to-delete")
+
+ expected_key = "superset-ext:org.ext:user:99:to-delete"
+ mock_cache.delete.assert_called_once_with(expected_key)
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_shared_accessor_builds_shared_key(mock_cm: MagicMock, app: Flask) -> None:
+ """SharedEphemeralStateAccessor builds key without user scope."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = _envelope("shared-value")
+
+ ctx = create_context("org", "ext")
+
+ with app.app_context(), use_context(ctx):
+ set_user(1) # User is set but should not appear in shared key
+ result = EphemeralState.shared.get("shared-key")
+
+ expected_key = "superset-ext:org.ext:shared:shared-key"
+ mock_cache.get.assert_called_once_with(expected_key)
+ assert result == "shared-value"
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_shared_accessor_set_and_remove(mock_cm: MagicMock, app: Flask) -> None:
+ """SharedEphemeralStateAccessor set() and remove() use shared key."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ ctx = create_context("org", "ext")
+
+ with app.app_context(), use_context(ctx):
+ set_user(1)
+ EphemeralState.shared.set("key", {"shared": True}, EphemeralSetOptions(ttl=300))
+ EphemeralState.shared.remove("key")
+
+ expected_key = "superset-ext:org.ext:shared:key"
+ mock_cache.set.assert_called_once_with(
+ expected_key, _envelope({"shared": True}), timeout=300
+ )
+ mock_cache.delete.assert_called_once_with(expected_key)
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_different_extensions_have_isolated_keys(
+ mock_cm: MagicMock, app: Flask
+) -> None:
+ """Different extensions use different key prefixes for isolation."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.side_effect = lambda k: _envelope(f"value-for-{k}")
+
+ ctx1 = create_context("org1", "ext1")
+ ctx2 = create_context("org2", "ext2")
+
+ with app.app_context():
+ set_user(1)
+
+ with use_context(ctx1):
+ EphemeralState.get("same-key")
+
+ with use_context(ctx2):
+ EphemeralState.get("same-key")
+
+ calls = [call.args[0] for call in mock_cache.get.call_args_list]
+ assert "superset-ext:org1.ext1:user:1:same-key" in calls
+ assert "superset-ext:org2.ext2:user:1:same-key" in calls
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_different_users_have_isolated_keys(mock_cm: MagicMock, app: Flask) -> None:
+ """Different users use different key prefixes for isolation."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = None
+
+ ctx = create_context()
+
+ with app.app_context(), use_context(ctx):
+ set_user(1)
+ EphemeralState.get("key")
+
+ set_user(2)
+ EphemeralState.get("key")
+
+ calls = [call.args[0] for call in mock_cache.get.call_args_list]
+ assert any(":user:1:" in k for k in calls)
+ assert any(":user:2:" in k for k in calls)
diff --git a/tests/unit_tests/extensions/storage/test_ephemeral_dao.py b/tests/unit_tests/extensions/storage/test_ephemeral_dao.py
new file mode 100644
index 00000000000..d2ec98fead5
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/test_ephemeral_dao.py
@@ -0,0 +1,323 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for ExtensionEphemeralDAO — the shared Tier 2 cache access and
+MAX_TTL/MAX_VALUE_SIZE validation used by both the REST API and the ambient
+`ephemeral_state` accessor."""
+
+from __future__ import annotations
+
+import base64
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+from flask_babel import Babel
+
+from superset.extensions.storage.codecs import get_codec
+from superset.extensions.storage.ephemeral_dao import (
+ ExtensionEphemeralDAO,
+ ExtensionEphemeralTTLInvalid,
+ ExtensionEphemeralValueTooLarge,
+)
+from tests.unit_tests.extensions.storage.conftest import set_user
+
+
+def _envelope(value: Any, codec: str = "json") -> dict[str, str]:
+ """Build the cache envelope ExtensionEphemeralDAO stores values as."""
+ encoded = get_codec(codec).encode(value)
+ return {"codec": codec, "value": base64.b64encode(encoded).decode("ascii")}
+
+
+# ── get / set / delete key building ──────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_get_user_scoped_key(mock_cm: MagicMock, app: Flask) -> None:
+ """get() builds a user-scoped key when shared=False."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = _envelope("value")
+
+ with app.app_context():
+ set_user(42)
+ result = ExtensionEphemeralDAO.get("acme.ext", "key", shared=False)
+
+ assert result == "value"
+ mock_cache.get.assert_called_once_with("superset-ext:acme.ext:user:42:key")
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_get_user_scoped_raises_without_user(mock_cm: MagicMock, app: Flask) -> None:
+ """get() raises RuntimeError when shared=False and no user is authenticated."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ with pytest.raises(RuntimeError, match="requires an authenticated user"):
+ ExtensionEphemeralDAO.get("acme.ext", "key", shared=False)
+
+ mock_cache.get.assert_not_called()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_get_shared_key(mock_cm: MagicMock, app: Flask) -> None:
+ """get() builds a shared key when shared=True, no user needed."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = _envelope("value")
+
+ with app.app_context():
+ result = ExtensionEphemeralDAO.get("acme.ext", "key", shared=True)
+
+ assert result == "value"
+ mock_cache.get.assert_called_once_with("superset-ext:acme.ext:shared:key")
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_get_returns_none_when_not_found(mock_cm: MagicMock, app: Flask) -> None:
+ """get() returns None without attempting to decode when the cache misses."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = None
+
+ with app.app_context():
+ result = ExtensionEphemeralDAO.get("acme.ext", "key", shared=True)
+
+ assert result is None
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_get_decodes_with_stored_codec(mock_cm: MagicMock, app: Flask) -> None:
+ """get() decodes the cached envelope using the codec it was written with."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = _envelope({"pct": 42})
+
+ with app.app_context():
+ result = ExtensionEphemeralDAO.get("acme.ext", "key", shared=True)
+
+ assert result == {"pct": 42}
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_get_raw_returns_bytes_and_codec(mock_cm: MagicMock, app: Flask) -> None:
+ """get_raw() returns the decoded envelope's raw bytes and codec name."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = _envelope({"pct": 42}, codec="json")
+
+ with app.app_context():
+ result = ExtensionEphemeralDAO.get_raw("acme.ext", "key", shared=True)
+
+ assert result is not None
+ raw, codec = result
+ assert codec == "json"
+ assert get_codec(codec).decode(raw) == {"pct": 42}
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_get_raw_returns_none_when_not_found(mock_cm: MagicMock, app: Flask) -> None:
+ """get_raw() returns None when the cache misses."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+ mock_cache.get.return_value = None
+
+ with app.app_context():
+ result = ExtensionEphemeralDAO.get_raw("acme.ext", "key", shared=True)
+
+ assert result is None
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_delete_calls_cache_delete(mock_cm: MagicMock, app: Flask) -> None:
+ """delete() calls cache.delete() with the scoped key."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ ExtensionEphemeralDAO.delete("acme.ext", "key", shared=True)
+
+ mock_cache.delete.assert_called_once_with("superset-ext:acme.ext:shared:key")
+
+
+# ── set() TTL validation ──────────────────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_passes_ttl_to_cache(mock_cm: MagicMock, app: Flask) -> None:
+ """set() passes the given TTL through to cache.set()."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ ExtensionEphemeralDAO.set("acme.ext", "key", "value", 300, shared=True)
+
+ mock_cache.set.assert_called_once_with(
+ "superset-ext:acme.ext:shared:key", _envelope("value"), timeout=300
+ )
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_defaults_codec_to_json(mock_cm: MagicMock, app: Flask) -> None:
+ """set() encodes the value with the json codec when none is specified."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ ExtensionEphemeralDAO.set("acme.ext", "key", {"pct": 42}, 300, shared=True)
+
+ envelope = mock_cache.set.call_args[0][1]
+ assert envelope["codec"] == "json"
+ assert get_codec("json").decode(base64.b64decode(envelope["value"])) == {"pct": 42}
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_stores_given_codec(mock_cm: MagicMock, app: Flask) -> None:
+ """set() encodes the value with the caller-supplied codec."""
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ ExtensionEphemeralDAO.set(
+ "acme.ext", "key", {"pct": 42}, 300, codec="pickle", shared=True
+ )
+
+ envelope = mock_cache.set.call_args[0][1]
+ assert envelope["codec"] == "pickle"
+ assert get_codec("pickle").decode(base64.b64decode(envelope["value"])) == {
+ "pct": 42
+ }
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_raises_when_ttl_missing(mock_cm: MagicMock, app: Flask) -> None:
+ """set() raises ExtensionEphemeralTTLInvalid when ttl is None."""
+ Babel(app)
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ with pytest.raises(ExtensionEphemeralTTLInvalid):
+ ExtensionEphemeralDAO.set("acme.ext", "key", "value", None, shared=True)
+
+ mock_cache.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_raises_when_ttl_not_positive(mock_cm: MagicMock, app: Flask) -> None:
+ """set() raises ExtensionEphemeralTTLInvalid when ttl <= 0."""
+ Babel(app)
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ with pytest.raises(ExtensionEphemeralTTLInvalid):
+ ExtensionEphemeralDAO.set("acme.ext", "key", "value", 0, shared=True)
+
+ mock_cache.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_rejects_ttl_exceeding_max(mock_cm: MagicMock, app: Flask) -> None:
+ """set() raises ExtensionEphemeralTTLInvalid when ttl exceeds MAX_TTL."""
+ app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {"MAX_TTL": 3600}
+ Babel(app)
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ with pytest.raises(ExtensionEphemeralTTLInvalid):
+ ExtensionEphemeralDAO.set("acme.ext", "key", "value", 7200, shared=True)
+
+ mock_cache.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_accepts_ttl_equal_to_max(mock_cm: MagicMock, app: Flask) -> None:
+ """set() accepts a TTL exactly equal to MAX_TTL."""
+ app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {"MAX_TTL": 3600}
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ ExtensionEphemeralDAO.set("acme.ext", "key", "value", 3600, shared=True)
+
+ mock_cache.set.assert_called_once()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_accepts_any_ttl_when_max_not_configured(
+ mock_cm: MagicMock, app: Flask
+) -> None:
+ """set() accepts any positive TTL when MAX_TTL is not configured."""
+ app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {}
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ ExtensionEphemeralDAO.set("acme.ext", "key", "value", 999999, shared=True)
+
+ mock_cache.set.assert_called_once()
+
+
+# ── set() value size validation ──────────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_rejects_value_exceeding_max_size(mock_cm: MagicMock, app: Flask) -> None:
+ """set() raises ExtensionEphemeralValueTooLarge when the JSON-encoded
+ value exceeds MAX_VALUE_SIZE."""
+ app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {"MAX_VALUE_SIZE": 10}
+ Babel(app)
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ with pytest.raises(ExtensionEphemeralValueTooLarge):
+ ExtensionEphemeralDAO.set("acme.ext", "key", "x" * 100, 300, shared=True)
+
+ mock_cache.set.assert_not_called()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_accepts_value_within_max_size(mock_cm: MagicMock, app: Flask) -> None:
+ """set() accepts a value at or under MAX_VALUE_SIZE."""
+ app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {"MAX_VALUE_SIZE": 1000}
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ ExtensionEphemeralDAO.set("acme.ext", "key", "small", 300, shared=True)
+
+ mock_cache.set.assert_called_once()
+
+
+@patch("superset.extensions.storage.ephemeral_dao.cache_manager")
+def test_set_accepts_any_size_when_max_not_configured(
+ mock_cm: MagicMock, app: Flask
+) -> None:
+ """set() accepts any value size when MAX_VALUE_SIZE is not configured."""
+ app.config["EXTENSIONS_EPHEMERAL_STORAGE"] = {}
+ mock_cache = MagicMock()
+ mock_cm.extension_ephemeral_state_cache = mock_cache
+
+ with app.app_context():
+ ExtensionEphemeralDAO.set("acme.ext", "key", "x" * 10000, 300, shared=True)
+
+ mock_cache.set.assert_called_once()
diff --git a/tests/unit_tests/extensions/storage/test_filters.py b/tests/unit_tests/extensions/storage/test_filters.py
new file mode 100644
index 00000000000..612dd89f420
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/test_filters.py
@@ -0,0 +1,78 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for ExtensionStorageFilter — the ambient-context isolation boundary."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+from flask import Flask
+
+from superset.extensions.context import use_context
+from superset.extensions.storage.filters import ExtensionStorageFilter
+from superset.extensions.storage.persistent_model import ExtensionStorage
+
+from .conftest import create_context
+
+
+def test_apply_scopes_to_the_ambient_extension_id(app: Flask) -> None:
+ """apply() filters by the extension_id of the current ambient context."""
+ ctx = create_context(publisher="acme", name="widgets")
+ query = MagicMock()
+
+ with app.app_context(), use_context(ctx):
+ ExtensionStorageFilter("extension_id", MagicMock()).apply(query, None)
+
+ filter_arg = query.filter.call_args[0][0]
+ assert filter_arg.right.value == "acme.widgets"
+
+
+def test_apply_matches_nothing_outside_an_extension_context(app: Flask) -> None:
+ """apply() filters on extension_id IS NULL when no ambient context is set.
+
+ This is a deliberate fail-closed default: a query made outside extension
+ execution (e.g. accidentally from host code) must never fall through to
+ an unscoped query that would return every extension's storage.
+ """
+ query = MagicMock()
+
+ with app.app_context():
+ ExtensionStorageFilter("extension_id", MagicMock()).apply(query, None)
+
+ filter_arg = query.filter.call_args[0][0]
+ assert str(filter_arg) == str(ExtensionStorage.extension_id.is_(None))
+
+
+def test_different_extensions_get_different_filters(app: Flask) -> None:
+ """Two different ambient contexts produce two different filter clauses."""
+ ctx_a = create_context(publisher="acme", name="widgets")
+ ctx_b = create_context(publisher="acme", name="gadgets")
+
+ query_a = MagicMock()
+ query_b = MagicMock()
+
+ with app.app_context():
+ with use_context(ctx_a):
+ ExtensionStorageFilter("extension_id", MagicMock()).apply(query_a, None)
+ with use_context(ctx_b):
+ ExtensionStorageFilter("extension_id", MagicMock()).apply(query_b, None)
+
+ filter_a = query_a.filter.call_args[0][0]
+ filter_b = query_b.filter.call_args[0][0]
+ assert filter_a.right.value == "acme.widgets"
+ assert filter_b.right.value == "acme.gadgets"
diff --git a/tests/unit_tests/extensions/storage/test_persistent.py b/tests/unit_tests/extensions/storage/test_persistent.py
new file mode 100644
index 00000000000..5430354898a
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/test_persistent.py
@@ -0,0 +1,318 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for persistent state storage implementation."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+
+from superset.extensions.context import use_context
+from superset.extensions.storage.persistent import (
+ PersistentListOptions,
+ PersistentSetOptions,
+ PersistentState,
+ SharedPersistentStateAccessor,
+)
+from superset.extensions.storage.persistent_dao import ExtensionStorageListEntry
+from superset.utils import json
+from tests.unit_tests.extensions.storage.conftest import (
+ create_context,
+ set_user,
+)
+
+
+@patch("superset.db")
+def test_persistent_state_raises_without_context(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """PersistentState operations raise RuntimeError without extension context."""
+ with app.app_context():
+ set_user(1)
+
+ with pytest.raises(RuntimeError, match="within an extension context"):
+ PersistentState.get("key")
+
+ with pytest.raises(RuntimeError, match="within an extension context"):
+ PersistentState.set("key", "value")
+
+ with pytest.raises(RuntimeError, match="within an extension context"):
+ PersistentState.remove("key")
+
+
+def test_persistent_state_raises_without_user(app: Flask) -> None:
+ """PersistentState operations raise RuntimeError without authenticated user."""
+ ctx = create_context()
+
+ with app.app_context(), use_context(ctx):
+ with pytest.raises(RuntimeError, match="requires an authenticated user"):
+ PersistentState.get("key")
+
+
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_persistent_state_get_returns_value(mock_dao: MagicMock, app: Flask) -> None:
+ """PersistentState.get returns decoded value from DAO."""
+ ctx = create_context()
+ mock_dao.get_decoded_value.return_value = {"theme": "dark"}
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ result = PersistentState.get("prefs")
+
+ mock_dao.get_decoded_value.assert_called_once_with(
+ "test-org.test-ext", "prefs", user_fk=42
+ )
+ assert result == {"theme": "dark"}
+
+
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_persistent_state_get_returns_none_when_missing(
+ mock_dao: MagicMock, app: Flask
+) -> None:
+ """PersistentState.get returns None when key does not exist."""
+ ctx = create_context()
+ mock_dao.get_decoded_value.return_value = None
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ result = PersistentState.get("missing")
+
+ assert result is None
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_persistent_state_set_encodes_value(
+ mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """PersistentState.set encodes value as JSON bytes."""
+ ctx = create_context()
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ PersistentState.set("prefs", {"theme": "dark"})
+
+ expected_bytes = json.dumps({"theme": "dark"}).encode()
+ mock_dao.set.assert_called_once_with(
+ "test-org.test-ext",
+ "prefs",
+ expected_bytes,
+ codec="json",
+ user_fk=42,
+ encrypt=False,
+ )
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_persistent_state_set_with_encrypt_option(
+ mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """PersistentState.set passes encrypt=True when options.encrypt is set."""
+ ctx = create_context()
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ PersistentState.set("token", "sk-...", PersistentSetOptions(encrypt=True))
+
+ expected_bytes = json.dumps("sk-...").encode()
+ mock_dao.set.assert_called_once_with(
+ "test-org.test-ext",
+ "token",
+ expected_bytes,
+ codec="json",
+ user_fk=42,
+ encrypt=True,
+ )
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_shared_accessor_set_with_encrypt_option(
+ mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """SharedPersistentStateAccessor.set passes encrypt=True when requested."""
+ ctx = create_context()
+ accessor = SharedPersistentStateAccessor()
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ accessor.set("shared_token", "sk-...", PersistentSetOptions(encrypt=True))
+
+ expected_bytes = json.dumps("sk-...").encode()
+ mock_dao.set.assert_called_once_with(
+ "test-org.test-ext",
+ "shared_token",
+ expected_bytes,
+ codec="json",
+ user_fk=None,
+ encrypt=True,
+ )
+
+
+@patch("superset.db")
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_persistent_state_remove_deletes_entry(
+ mock_dao: MagicMock, mock_db: MagicMock, app: Flask
+) -> None:
+ """PersistentState.remove calls DAO delete."""
+ ctx = create_context()
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ PersistentState.remove("prefs")
+
+ mock_dao.delete_by_key.assert_called_once_with(
+ "test-org.test-ext", "prefs", user_fk=42
+ )
+
+
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_shared_accessor_uses_null_user_fk(mock_dao: MagicMock, app: Flask) -> None:
+ """SharedPersistentStateAccessor uses user_fk=None for global scope."""
+ ctx = create_context()
+ mock_dao.get_decoded_value.return_value = "shared_value"
+
+ accessor = SharedPersistentStateAccessor()
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ result = accessor.get("config")
+
+ mock_dao.get_decoded_value.assert_called_once_with(
+ "test-org.test-ext", "config", user_fk=None
+ )
+ assert result == "shared_value"
+
+
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_persistent_state_list_decodes_entries_and_forwards_options(
+ mock_dao: MagicMock, app: Flask
+) -> None:
+ """PersistentState.list decodes every entry's value (no SAFE_CODECS
+ restriction for ambient backend code) and forwards the given options."""
+ ctx = create_context()
+ mock_dao.list_entries.return_value = (
+ [
+ ExtensionStorageListEntry(
+ key="prefs",
+ value=json.dumps({"theme": "dark"}).encode(),
+ codec="json",
+ is_encrypted=False,
+ ),
+ ],
+ 1,
+ )
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ result = PersistentState.list(PersistentListOptions(page=0, page_size=10))
+
+ mock_dao.list_entries.assert_called_once_with(
+ "test-org.test-ext",
+ user_fk=42,
+ resource_type=None,
+ resource_uuid=None,
+ page=0,
+ page_size=10,
+ )
+ assert result.count == 1
+ assert len(result.entries) == 1
+ assert result.entries[0].key == "prefs"
+ assert result.entries[0].value == {"theme": "dark"}
+ assert result.entries[0].codec == "json"
+
+
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_persistent_state_list_forwards_custom_options(
+ mock_dao: MagicMock, app: Flask
+) -> None:
+ """PersistentState.list forwards caller-supplied PersistentListOptions."""
+ ctx = create_context()
+ mock_dao.list_entries.return_value = ([], 0)
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ PersistentState.list(
+ PersistentListOptions(
+ resource_type="dashboard",
+ resource_uuid="uuid-1",
+ page=2,
+ page_size=25,
+ )
+ )
+
+ mock_dao.list_entries.assert_called_once_with(
+ "test-org.test-ext",
+ user_fk=42,
+ resource_type="dashboard",
+ resource_uuid="uuid-1",
+ page=2,
+ page_size=25,
+ )
+
+
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_persistent_state_list_handles_none_value(
+ mock_dao: MagicMock, app: Flask
+) -> None:
+ """PersistentState.list does not attempt to decode a None value (e.g.
+ a decryption failure), passing it through as None instead of raising."""
+ ctx = create_context()
+ mock_dao.list_entries.return_value = (
+ [
+ ExtensionStorageListEntry(
+ key="broken",
+ value=None,
+ codec="json",
+ is_encrypted=True,
+ ),
+ ],
+ 1,
+ )
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ result = PersistentState.list(PersistentListOptions(page=0, page_size=10))
+
+ assert result.entries[0].value is None
+
+
+@patch("superset.extensions.storage.persistent.ExtensionStorageDAO")
+def test_shared_accessor_list_uses_null_user_fk(
+ mock_dao: MagicMock, app: Flask
+) -> None:
+ """SharedPersistentStateAccessor.list uses user_fk=None for global scope."""
+ ctx = create_context()
+ mock_dao.list_entries.return_value = ([], 0)
+ accessor = SharedPersistentStateAccessor()
+
+ with app.app_context(), use_context(ctx):
+ set_user(42)
+ accessor.list(PersistentListOptions(page=0, page_size=10))
+
+ mock_dao.list_entries.assert_called_once_with(
+ "test-org.test-ext",
+ user_fk=None,
+ resource_type=None,
+ resource_uuid=None,
+ page=0,
+ page_size=10,
+ )
diff --git a/tests/unit_tests/extensions/storage/test_persistent_dao.py b/tests/unit_tests/extensions/storage/test_persistent_dao.py
new file mode 100644
index 00000000000..40181bc47de
--- /dev/null
+++ b/tests/unit_tests/extensions/storage/test_persistent_dao.py
@@ -0,0 +1,957 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for ExtensionStorageDAO — encryption, scoping, and CRUD behavior."""
+
+from __future__ import annotations
+
+from collections.abc import Generator
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+from flask import Flask
+from flask_babel import Babel
+from sqlalchemy.orm.session import Session
+
+from superset.extensions.storage.codecs import get_codec
+from superset.extensions.storage.filters import ExtensionStorageFilter
+from superset.extensions.storage.persistent_dao import (
+ _derive_key,
+ _enc_type,
+ ExtensionStorageDAO,
+ ExtensionStorageKeyTooLong,
+ ExtensionStorageListPayloadTooLarge,
+ ExtensionStorageQuotaExceeded,
+ ExtensionStorageValueTooLarge,
+ MAX_KEY_LENGTH,
+ SET_LOCK_TTL_SECONDS,
+)
+from superset.extensions.storage.persistent_model import ExtensionStorage
+
+
+@pytest.fixture
+def app() -> Flask:
+ """Create a minimal Flask app for testing."""
+ flask_app = Flask(__name__)
+ flask_app.config["TESTING"] = True
+ flask_app.config["SECRET_KEY"] = "test-secret-key" # noqa: S105
+ # Mirrors the default set in superset/config.py, which is always present
+ # in a real Superset app.
+ flask_app.config["EXTENSIONS_PERSISTENT_STORAGE"] = {}
+ return flask_app
+
+
+@pytest.fixture
+def app_with_quota(app: Flask) -> Flask:
+ """App fixture with a configured persistent storage quota (100 bytes).
+
+ Initializes Babel since exceeding the quota raises an exception whose
+ message is built with flask_babel's gettext.
+ """
+ app.config["EXTENSIONS_PERSISTENT_STORAGE"] = {"QUOTA_PER_EXTENSION": 100}
+ Babel(app)
+ return app
+
+
+@pytest.fixture
+def app_with_max_value_size(app: Flask) -> Flask:
+ """App fixture with a configured MAX_VALUE_SIZE (10 bytes).
+
+ Initializes Babel since exceeding the limit raises an exception whose
+ message is built with flask_babel's gettext.
+ """
+ app.config["EXTENSIONS_PERSISTENT_STORAGE"] = {"MAX_VALUE_SIZE": 10}
+ Babel(app)
+ return app
+
+
+@pytest.fixture
+def app_with_max_list_payload_size(app: Flask) -> Flask:
+ """App fixture with a configured MAX_LIST_PAYLOAD_SIZE (20 bytes).
+
+ Initializes Babel since exceeding the limit raises an exception whose
+ message is built with flask_babel's gettext.
+ """
+ app.config["EXTENSIONS_PERSISTENT_STORAGE"] = {"MAX_LIST_PAYLOAD_SIZE": 20}
+ Babel(app)
+ return app
+
+
+@pytest.fixture(autouse=True)
+def mock_distributed_lock() -> Generator[MagicMock, None, None]:
+ """`ExtensionStorageDAO.set` wraps its select-then-write section in a
+ `DistributedLock`, which needs a configured lock backend (Redis or an
+ initialized DB session) to acquire. These tests exercise DAO logic
+ against a mocked `db`, not lock acquisition, so replace it with a no-op.
+ """
+ with patch("superset.extensions.storage.persistent_dao.DistributedLock") as mock:
+ yield mock
+
+
+@pytest.fixture
+def list_session(session: Session) -> Session:
+ """In-memory SQLite session with the extension_storage table created,
+ used only by `list()` tests below (which exercise real queries rather
+ than mocking `db.session`, since `list()`'s query chain — count,
+ order_by, offset, limit, a value_size subquery sum — is too complex to
+ mock link-by-link without the test just re-asserting the
+ implementation)."""
+ ExtensionStorage.metadata.create_all(session.get_bind()) # pylint: disable=no-member
+ return session
+
+
+def _create_entry(
+ session: Session,
+ extension_id: str,
+ key: str,
+ value: bytes = b"{}",
+ codec: str = "json",
+ user_fk: int | None = None,
+ resource_type: str | None = None,
+ resource_uuid: str | None = None,
+ is_encrypted: bool = False,
+) -> ExtensionStorage:
+ """Insert an ExtensionStorage row directly, bypassing DAO.set() (whose
+ own validation isn't what these `list()` tests are exercising)."""
+ entry = ExtensionStorage(
+ extension_id=extension_id,
+ key=key,
+ value=value,
+ value_size=len(value),
+ codec=codec,
+ user_fk=user_fk,
+ resource_type=resource_type,
+ resource_uuid=resource_uuid,
+ is_encrypted=is_encrypted,
+ )
+ session.add(entry)
+ session.flush()
+ return entry
+
+
+# ── get / get_value ───────────────────────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_get_returns_none_when_not_found(mock_db: MagicMock, app: Flask) -> None:
+ """get() returns None when no entry exists for the given scope."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ result = ExtensionStorageDAO.get("my-ext", "key", user_fk=1)
+
+ assert result is None
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_get_value_returns_raw_bytes_for_unencrypted(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """get_value() returns raw bytes unchanged when the entry is not encrypted."""
+ entry = MagicMock()
+ entry.is_encrypted = False
+ entry.value = b'{"foo": "bar"}'
+ mock_db.session.query.return_value.filter.return_value.first.return_value = entry
+
+ with app.app_context():
+ result = ExtensionStorageDAO.get_value("my-ext", "key", user_fk=1)
+
+ assert result == b'{"foo": "bar"}'
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_get_value_returns_none_when_not_found(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """get_value() returns None when the key does not exist."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ result = ExtensionStorageDAO.get_value("my-ext", "missing", user_fk=1)
+
+ assert result is None
+
+
+# ── get_decoded_value ─────────────────────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_get_decoded_value_decodes_with_stored_codec(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """get_decoded_value() decodes the raw bytes using the entry's codec."""
+ entry = MagicMock()
+ entry.is_encrypted = False
+ entry.value = b'{"theme": "dark"}'
+ entry.codec = "json"
+ mock_db.session.query.return_value.filter.return_value.first.return_value = entry
+
+ with app.app_context():
+ result = ExtensionStorageDAO.get_decoded_value("my-ext", "key", user_fk=1)
+
+ assert result == {"theme": "dark"}
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_get_decoded_value_returns_none_when_not_found(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """get_decoded_value() returns None when no entry exists."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ result = ExtensionStorageDAO.get_decoded_value("my-ext", "missing", user_fk=1)
+
+ assert result is None
+
+
+@patch("superset.extensions.storage.persistent_dao._enc_type")
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_get_value_decrypts_encrypted_entry(
+ mock_db: MagicMock, mock_enc_type: MagicMock, app: Flask
+) -> None:
+ """get_value() decrypts the stored value for encrypted entries."""
+ entry = MagicMock()
+ entry.is_encrypted = True
+ entry.user_fk = 1
+ entry.value = b"encrypted-bytes"
+ mock_db.session.query.return_value.filter.return_value.first.return_value = entry
+ mock_enc_type.return_value.process_result_value.return_value = (
+ b'{"decrypted": true}'
+ )
+
+ with app.app_context():
+ result = ExtensionStorageDAO.get_value("my-ext", "key", user_fk=1)
+
+ assert result == b'{"decrypted": true}'
+ mock_enc_type.assert_called_once_with(1)
+ mock_enc_type.return_value.process_result_value.assert_called_once_with(
+ b"encrypted-bytes", mock_db.engine.dialect
+ )
+
+
+@patch("superset.extensions.storage.persistent_dao._enc_type")
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_get_value_returns_none_on_decryption_failure(
+ mock_db: MagicMock, mock_enc_type: MagicMock, app: Flask
+) -> None:
+ """get_value() returns None and logs an error when decryption fails."""
+ entry = MagicMock()
+ entry.is_encrypted = True
+ entry.user_fk = 1
+ entry.value = b"corrupted"
+ mock_db.session.query.return_value.filter.return_value.first.return_value = entry
+ mock_enc_type.return_value.process_result_value.side_effect = Exception(
+ "bad decrypt"
+ )
+
+ with app.app_context():
+ result = ExtensionStorageDAO.get_value("my-ext", "key", user_fk=1)
+
+ assert result is None
+
+
+# ── set (upsert) ──────────────────────────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_creates_new_entry_when_absent(mock_db: MagicMock, app: Flask) -> None:
+ """set() adds a new entry when no existing entry is found."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b'{"value": 1}', user_fk=1)
+
+ mock_db.session.add.assert_called_once()
+ mock_db.session.flush.assert_called_once()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_locks_the_whole_extension_not_just_the_key(
+ mock_db: MagicMock, mock_distributed_lock: MagicMock, app: Flask
+) -> None:
+ """set()'s lock is scoped to extension_id alone, not to the specific key:
+ _check_quota sums usage across every key in the extension, so a lock
+ scoped to just this key would let concurrent writes to different keys
+ each pass the quota check before either commits, letting the extension
+ exceed its quota."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b'{"value": 1}', user_fk=1)
+
+ mock_distributed_lock.assert_called_once_with(
+ namespace="extension_storage_set",
+ ttl_seconds=SET_LOCK_TTL_SECONDS,
+ extension_id="my-ext",
+ )
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_updates_existing_entry(mock_db: MagicMock, app: Flask) -> None:
+ """set() updates in-place when an entry already exists (no duplicate row)."""
+ existing = MagicMock()
+ existing.value_size = 0
+ mock_db.session.query.return_value.filter.return_value.first.return_value = existing
+
+ with app.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b'{"new": true}', user_fk=1)
+
+ assert existing.value == b'{"new": true}'
+ assert existing.value_size == len(b'{"new": true}')
+ mock_db.session.add.assert_not_called()
+ mock_db.session.flush.assert_called_once()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_defaults_codec_to_json(mock_db: MagicMock, app: Flask) -> None:
+ """set() stores codec="json" on the entry when not specified."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b'{"value": 1}', user_fk=1)
+
+ added_entry = mock_db.session.add.call_args[0][0]
+ assert added_entry.codec == "json"
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_stores_given_codec(mock_db: MagicMock, app: Flask) -> None:
+ """set() stores the caller-supplied codec identifier on the entry."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ ExtensionStorageDAO.set(
+ "my-ext", "key", b"\x80pickled", codec="pickle", user_fk=1
+ )
+
+ added_entry = mock_db.session.add.call_args[0][0]
+ assert added_entry.codec == "pickle"
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_updates_codec_on_existing_entry(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """set() overwrites the stored codec when re-writing an existing key."""
+ existing = MagicMock()
+ existing.value_size = 0
+ existing.codec = "json"
+ mock_db.session.query.return_value.filter.return_value.first.return_value = existing
+
+ with app.app_context():
+ ExtensionStorageDAO.set(
+ "my-ext", "key", b"\x80pickled", codec="pickle", user_fk=1
+ )
+
+ assert existing.codec == "pickle"
+
+
+@patch("superset.extensions.storage.persistent_dao._enc_type")
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_encrypts_value_when_requested(
+ mock_db: MagicMock, mock_enc_type: MagicMock, app: Flask
+) -> None:
+ """set() encrypts value bytes with user-derived key and sets is_encrypted=True."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+ mock_enc_type.return_value.process_bind_param.return_value = b"ciphertext"
+
+ with app.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b"plaintext", user_fk=1, encrypt=True)
+
+ mock_enc_type.assert_called_once_with(1)
+ mock_enc_type.return_value.process_bind_param.assert_called_once_with(
+ b"plaintext", mock_db.engine.dialect
+ )
+ added_entry = mock_db.session.add.call_args[0][0]
+ assert added_entry.value == b"ciphertext"
+ assert added_entry.value_size == len(b"ciphertext")
+ assert added_entry.is_encrypted is True
+
+
+# ── value size ────────────────────────────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_allows_key_at_max_length(mock_db: MagicMock, app: Flask) -> None:
+ """set() accepts a key exactly at MAX_KEY_LENGTH."""
+ Babel(app)
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ ExtensionStorageDAO.set("my-ext", "k" * MAX_KEY_LENGTH, b"value", user_fk=1)
+
+ mock_db.session.add.assert_called_once()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_rejects_key_exceeding_max_length(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """set() raises ExtensionStorageKeyTooLong and does not write when the
+ key exceeds MAX_KEY_LENGTH."""
+ Babel(app)
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ with pytest.raises(ExtensionStorageKeyTooLong):
+ ExtensionStorageDAO.set(
+ "my-ext", "k" * (MAX_KEY_LENGTH + 1), b"value", user_fk=1
+ )
+
+ mock_db.session.add.assert_not_called()
+ mock_db.session.flush.assert_not_called()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_checks_key_length_before_value_size(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """set() rejects an over-length key before running the value-size query,
+ since the key check happens first."""
+ Babel(app)
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ with pytest.raises(ExtensionStorageKeyTooLong):
+ ExtensionStorageDAO.set(
+ "my-ext", "k" * (MAX_KEY_LENGTH + 1), b"value", user_fk=1
+ )
+
+ mock_db.session.query.return_value.filter.return_value.first.assert_not_called()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_allows_write_when_no_max_value_size_configured(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """set() skips the value-size check entirely when MAX_VALUE_SIZE is unset."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b"x" * 10000, user_fk=1)
+
+ mock_db.session.add.assert_called_once()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_allows_value_within_max_value_size(
+ mock_db: MagicMock, app_with_max_value_size: Flask
+) -> None:
+ """set() accepts a value at or under MAX_VALUE_SIZE."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app_with_max_value_size.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b"x" * 10, user_fk=1)
+
+ mock_db.session.add.assert_called_once()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_rejects_value_exceeding_max_value_size(
+ mock_db: MagicMock, app_with_max_value_size: Flask
+) -> None:
+ """set() raises ExtensionStorageValueTooLarge and does not write when the
+ value exceeds MAX_VALUE_SIZE."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app_with_max_value_size.app_context():
+ with pytest.raises(ExtensionStorageValueTooLarge):
+ ExtensionStorageDAO.set("my-ext", "key", b"x" * 11, user_fk=1)
+
+ mock_db.session.add.assert_not_called()
+ mock_db.session.flush.assert_not_called()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_checks_value_size_before_quota(
+ mock_db: MagicMock, app_with_max_value_size: Flask
+) -> None:
+ """set() rejects an oversized value before running the quota usage query."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app_with_max_value_size.app_context():
+ with pytest.raises(ExtensionStorageValueTooLarge):
+ ExtensionStorageDAO.set("my-ext", "key", b"x" * 11, user_fk=1)
+
+ # scalar() is only called by the quota-usage query; it must not run.
+ mock_db.session.query.return_value.filter.return_value.scalar.assert_not_called()
+
+
+# ── quota ─────────────────────────────────────────────────────────────────────
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_allows_write_when_no_quota_configured(
+ mock_db: MagicMock, app: Flask
+) -> None:
+ """set() skips the quota check entirely when no quota is configured."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+
+ with app.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b'{"value": 1}', user_fk=1)
+
+ # scalar() is only called by the quota-usage query; it must not run.
+ mock_db.session.query.return_value.filter.return_value.scalar.assert_not_called()
+ mock_db.session.add.assert_called_once()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_allows_write_under_quota(
+ mock_db: MagicMock, app_with_quota: Flask
+) -> None:
+ """set() succeeds when current usage plus the new value stays within quota."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+ mock_db.session.query.return_value.filter.return_value.scalar.return_value = 50
+
+ with app_with_quota.app_context():
+ ExtensionStorageDAO.set("my-ext", "key", b"x" * 10, user_fk=1)
+
+ mock_db.session.add.assert_called_once()
+ mock_db.session.flush.assert_called_once()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_rejects_write_over_quota(
+ mock_db: MagicMock, app_with_quota: Flask
+) -> None:
+ """set() raises ExtensionStorageQuotaExceeded and does not write when over quota."""
+ mock_db.session.query.return_value.filter.return_value.first.return_value = None
+ mock_db.session.query.return_value.filter.return_value.scalar.return_value = 95
+
+ with app_with_quota.app_context(), pytest.raises(ExtensionStorageQuotaExceeded):
+ ExtensionStorageDAO.set("my-ext", "key", b"x" * 10, user_fk=1)
+
+ mock_db.session.add.assert_not_called()
+ mock_db.session.flush.assert_not_called()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_overwrite_does_not_double_count_existing_row(
+ mock_db: MagicMock, app_with_quota: Flask
+) -> None:
+ """Overwriting a key nets out its own existing size against quota usage."""
+ existing = MagicMock()
+ existing.value = b"x" * 20
+ existing.value_size = 20
+ mock_db.session.query.return_value.filter.return_value.first.return_value = existing
+ # Usage already includes the 20 bytes this row occupies.
+ mock_db.session.query.return_value.filter.return_value.scalar.return_value = 95
+
+ with app_with_quota.app_context():
+ # Same-size replacement: 95 - 20 + 20 = 95 <= 100, must not raise even
+ # though total usage (95) is already close to the 100-byte quota.
+ ExtensionStorageDAO.set("my-ext", "key", b"x" * 20, user_fk=1)
+
+ assert existing.value == b"x" * 20
+ assert existing.value_size == 20
+ mock_db.session.flush.assert_called_once()
+
+
+@patch("superset.extensions.storage.persistent_dao.db")
+def test_dao_set_overwrite_still_rejected_when_growth_exceeds_quota(
... 660 lines suppressed ...