Files
Felipe Martin 2b3fb21fe3 Add KVListWithOptions for server-side prefix filtering in plugin KV store (#35441)
* Add KVListWithOptions to push prefix filtering into SQL

Add server-side prefix filtering for plugin KV store key listing via
KVListWithOptions across the full stack: store interface, SQL
implementation, platform service, app layer, plugin API, pluginapi
helper, and memory store.

Previously, WithPrefix in pluginapi.ListKeys performed client-side
filtering after fetching all keys. This pushes the LIKE filter into
the SQL query for efficiency, using sanitizeSearchTerm to escape
SQL wildcards.

* Add KVListWithOptions backward-compat fallback for old servers

Manually implement the KVListWithOptions RPC glue instead of generating
it so the client can detect "rpc: can't find method" errors from
pre-11.5 servers and return a proper AppError with StatusNotImplemented.
The generated version silently returns (nil, nil) on RPC errors, which
is indistinguishable from an empty result due to encoding/gob conflating
nil and empty slices. The pluginapi helper already checks for
StatusNotImplemented and falls back to KVList with client-side prefix
filtering.

* Address review findings on KVListWithOptions

- Escape backslashes in the SQL prefix instead of stripping them.
- Return an AppError for every RPC failure in the KVListWithOptions client.
- AND multiple WithPrefix options again; extra prefixes become checkers.
- Make the old-server fallback page over prefix-filtered keys and trigger
  only on StatusNotImplemented.
- Set the minimum server version to 12.2 and fix the WithChecker doc.
- Remove the unused PlatformService.KVListWithOptions.
- Route List and ListPluginKeys through their WithOptions variants.

* Tighten KV list tests from CodeRabbit nitpicks

- Assert exact keys per page in the prefix pagination store test.
- Drop unused pgHost/pgPort lookups in the KV integration test.
- Include compiler output in the plugin build failure message.

* Use snake_case mlog field key in ListPluginKeysWithOptions

* Move KVListWithOptions integration tests into regular test suites

- Cover the plugin-to-SQL path with a test_kv_list_with_options plugin run by TestBasicAPIPlugins.
- Cover the old-server RPC error mapping with a unit test against an RPC server that lacks the method.
- Remove server/integration/pluginapi and the testcontainers dependency it pulled into server/go.mod.

* Combine WithPrefix prefixes so all prefix filtering stays server-side

A second prefix ran as a checker after page and count were applied, so
pages came back short. Nested prefixes now collapse to the longest one,
and prefixes that cannot both match return no keys.

* Use a fixed batch size for the ListKeys prefix fallback scan

The scan read the caller's count keys per KVList call, so a small count
made many RPCs. It now reads 1000 keys per call, independent of count.

* Use an explicit ESCAPE '*' for the plugin KV prefix LIKE

Matches the other LIKE queries in the store and does not depend on the
default backslash escape of Postgres.

* Rename the KVListWithOptions RPC error ids to plugin.api.kv_list_with_options.*

Matches the naming of the other plugin API error ids.

* Add a benchmark for listing plugin keys with a prefix

Compares paging through KVList and filtering in Go with KVListWithOptions,
for 10k, 100k and 1M keys.

* Document KVListWithOptions and prefix listing for plugins

Expands the doc comments that generate the server plugin reference, and
adds a best-practices section on listing KV store keys with a prefix.
2026-11-01 09:37:48 +01:00

4.5 KiB

title, sidebar_position
title sidebar_position
Best practices 0

How should plugins serve publicly available static files?

Add all static files under a file directory named public within the plugin directory, and include the files in the plugin bundle using the Makefile.

How do plugins make sure http requests are authentic?

Plugins can implement the ServeHTTP to listen to http requests. This can be used to receive post action requests when Interactive Messages Buttons and Menus are triggered by users.

When plugins act as an HTTP server, they serve requests from Mattermost clients (which are authenticated in a Mattermost sense), but may also serve HTTP requests from external services like webhooks. These requests from external services might use the Authorization header to authorize themselves against the plugin.

Since these requests are just HTTP requests, anyone can send them to the plugin. Hence, the plugin must make sure the requests are authentic. The Mattermost Server sets the HTTP header Mattermost-User-Id when the request is made by an authenticated client. If the plugin is expecting the request to come from an authenticated Mattermost user, and the Mattermost-User-Id is blank, it's the plugin's responsibility to reject the request.

From Mattermost v9.4, external systems can use the Authorization header to authenticate with the plugin. HTTP requests to server-side plugins can use an Authorization header in the request for the plugin to use, and the header value will be present in the request received by the plugin, as long as the token provided in the header is not a user token issued by the Mattermost server. This is useful for connecting external systems that require authentication through an Authorization header with their own token.

How should plugins handle request cancellation?

Long-running ServeHTTP handlers should pass r.Context() to downstream operations and stop work when it is canceled. Mattermost v12.0 and later propagates deadlines and explicit cancellation for server-to-plugin and inter-plugin HTTP requests when the destination plugin is built with a context-aware plugin runtime.

Inter-plugin callers can opt in with http.NewRequestWithContext or req.WithContext. If cancellation happens before response headers arrive, PluginHTTP returns nil and the caller can inspect request.Context().Err(). If it happens after headers arrive, reading the response body returns context.Canceled or context.DeadlineExceeded. Callers must close response bodies as usual.

Context values are not propagated. Use headers or plugin.Context for supported cross-process metadata. Plugins that require end-to-end cancellation should declare Mattermost v12.0 as their minimum server version. Older servers retain legacy behavior: they continue to process the request without context propagation, and the call may not return promptly after cancellation.

How should plugins list key-value store keys with a prefix?

Use KVListWithOptions with the Prefix option, or the pluginapi method ListKeys with WithPrefix. From Mattermost v12.2, the database filters the keys on the prefix before it applies the page and page size. Each page then contains only matching keys, and a page with fewer keys than the page size is the last page:

client := pluginapi.NewClient(p.API, p.Driver)

var keys []string
for page := 0; ; page++ {
	pageKeys, err := client.KV.ListKeys(page, 100, pluginapi.WithPrefix("user_"))
	if err != nil {
		return err
	}
	keys = append(keys, pageKeys...)
	if len(pageKeys) < 100 {
		break
	}
}

Don't page through KVList and filter the keys in the plugin. The page and page size then apply to all keys, so a page can contain fewer matching keys than the page size before the last page, or none at all. A loop that stops on a short page then misses keys. Reading all keys also takes much longer when the plugin stores many keys.

All characters in the prefix match literally, including % and _. On servers older than v12.2, KVListWithOptions returns an error with status code 501. ListKeys with WithPrefix handles this: it lists all keys and filters them in the plugin, and returns the same pages. WithChecker filters apply after the page and page size, so pages can contain fewer keys than the page size before the last page.