diff --git a/admin/src/index.css b/admin/src/index.css index bfbb645e1c8..29413dee9f3 100644 --- a/admin/src/index.css +++ b/admin/src/index.css @@ -1314,6 +1314,38 @@ a.pm-btn-primary:link, a.pm-btn-primary:visited { color: #fff; } cursor: help; } +.pm-tag--official { + background: rgba(20,148,116,.12); + color: var(--ep-accent-d); + border: 1px solid rgba(20,148,116,.3); + cursor: help; +} +.pm-tag--third-party { + background: var(--line-2); + color: var(--ink-2); + border: 1px solid var(--line); + cursor: help; +} + +/* Third-party install confirmation */ +.pm-dialog-content { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + z-index: 101; + width: min(460px, calc(100vw - 32px)); + background: var(--panel); + color: var(--ink); + border: 1px solid var(--line); + border-radius: var(--r-lg); + padding: 20px; + box-shadow: 0 10px 38px -10px rgba(0,0,0,.35); +} +.pm-dialog-title { margin: 0 0 8px; font-size: 16px; font-weight: 600; } +.pm-dialog-body { margin: 0; font-size: 13.5px; line-height: 1.5; color: var(--ink-2); } +.pm-dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 18px; } + /* Toolbar (search + sort) */ .pm-toolbar { display: flex; diff --git a/admin/src/pages/HomePage.tsx b/admin/src/pages/HomePage.tsx index e879820ec84..a9ab98e995d 100644 --- a/admin/src/pages/HomePage.tsx +++ b/admin/src/pages/HomePage.tsx @@ -5,6 +5,7 @@ import {useDebounce} from "../utils/useDebounce.ts"; import {Trans, useTranslation} from "react-i18next"; import {ArrowUpFromDot, Download, ExternalLink, Plug, RefreshCw, Search, Trash, X} from "lucide-react"; import {IconButton} from "../components/IconButton.tsx"; +import * as Dialog from "@radix-ui/react-dialog"; export const HomePage = () => { const pluginsSocket = useStore(state => state.pluginsSocket) @@ -24,6 +25,9 @@ export const HomePage = () => { searchTerm: '', }) const [searchTerm, setSearchTerm] = useState('') + // Third-party plugin awaiting the admin's confirmation before install. + const [confirmInstall, setConfirmInstall] = + useState<{name: string, version?: string} | null>(null) const {t} = useTranslation() const updatableCount = useMemo( @@ -140,11 +144,26 @@ export const HomePage = () => { setInstalledPlugins(installedPlugins.filter(i => i.name !== pluginName)) } - const installPlugin = (pluginName: string) => { - pluginsSocket!.emit('install', pluginName) + // With a version, the server installs exactly that release: the one the + // catalog showed and classified, not whatever is latest by then. + const installPlugin = (pluginName: string, version?: string) => { + pluginsSocket!.emit('install', version ? {name: pluginName, version} : pluginName) setPlugins(plugins.filter(p => p.name !== pluginName)) } + // Official plugins install with one click. A third-party plugin runs code + // the Etherpad project has not reviewed, so the admin confirms first; the + // extra, deliberate click also blunts clickjacking of the Install button. + // Updates go through here too; an update whose target version could not + // be classified is treated as third-party. + const requestInstall = (plugin: {name: string, version?: string, official?: boolean}) => { + if (plugin.official === true) { + installPlugin(plugin.name, plugin.version) + } else { + setConfirmInstall({name: plugin.name, version: plugin.version}) + } + } + useDebounce(() => { setSearchParams({...searchParams, offset: 0, searchTerm}) }, 500, [searchTerm]) @@ -152,6 +171,40 @@ export const HomePage = () => { return (
+ { if (!open) setConfirmInstall(null) }} + > + + + + + + + + {t('admin_plugins.third_party_confirm_body', {plugin: confirmInstall?.name ?? ''})} + +
+ + + + +
+
+
+
+ {catalogDisabled && (
@@ -264,7 +317,11 @@ export const HomePage = () => {
{plugin.updatable ? ( installPlugin(plugin.name)} + onClick={() => requestInstall({ + name: plugin.name, + version: plugin.latestVersion, + official: plugin.official, + })} icon={} title={t('admin_plugins.update_tooltip')} /> @@ -362,6 +419,17 @@ export const HomePage = () => { target="_blank" rel="noopener noreferrer" >{plugin.name} + {plugin.official ? ( + + ) : ( + + )}
@@ -385,7 +453,7 @@ export const HomePage = () => { diff --git a/admin/src/pages/Plugin.ts b/admin/src/pages/Plugin.ts index db28fa732f3..d7f3b23a7fb 100644 --- a/admin/src/pages/Plugin.ts +++ b/admin/src/pages/Plugin.ts @@ -3,6 +3,10 @@ export type PluginDef = { description: string, version: string, time: string, + /** + * Published from an ether/* GitHub repository, as shown by npm provenance. + * Computed by the server; anything else is third-party. + */ official: boolean, /** * `@feature:*` Playwright tags for core specs the plugin intentionally @@ -20,6 +24,10 @@ export type InstalledPlugin = { version: string, description?: string, updatable?: boolean, + /** For an updatable plugin: the catalog version an update installs. */ + latestVersion?: string, + /** For an updatable plugin: whether that version is official. */ + official?: boolean, /** * Reason this installed plugin should no longer be used (npm deprecation * message, or core's reason for treating it as superseded). Set by the diff --git a/doc/plugins.adoc b/doc/plugins.adoc index 5e19630acf0..1d82d0239fd 100644 --- a/doc/plugins.adoc +++ b/doc/plugins.adoc @@ -26,6 +26,43 @@ a failed lookup — if the npm registry cannot be reached the full catalog is listed and installs proceed — and `pnpm run plugins i ep_` on the server installs it anyway, for an operator who knows what they are doing. +==== Official and third-party plugins + +Anyone can publish an `ep_*` package to npm, and the Etherpad project cannot +review all of them. The catalog marks a plugin *Official* when npm +provenance shows that the published version was built by GitHub Actions from +a repository in the https://github.com/ether[ether] GitHub org. Everything +else is labelled *Third-party*: it is not maintained by the Etherpad +project and it runs code on your server. The admin UI asks for confirmation +before installing a third-party plugin; official plugins install with one +click. Updates of an installed plugin follow the same rule, and an install +always fetches the exact version the catalog showed, so a label shown for one +release never covers a different one. + +The check is done when the catalog is refreshed and cached per published +version, so it adds no latency to browsing. It relies on npm provenance +rather than on the package's `repository` field, its maintainer list or the +feed's own flags, because a publisher can set any of those to whatever they +like (`src/static/js/pluginfw/pluginTrust.ts`). A plugin from the ether org +that has not been released with provenance yet shows as third-party until its +next release. + +Placeholder packages (a `0.0.0-*` version, or no `repository` in +package.json) are left out of the list, but a search for the exact package +name still finds them, so you can find a package you have just published. + +The `pluginCatalogThirdParty` setting in `settings.json` changes this: + +|=== +| Value | Effect + +| `label` (default) | List third-party plugins with a badge; placeholders only on an exact-name search. +| `hide` | List official plugins only. Needs registry.npmjs.org: if it cannot be reached, nothing can be verified and the list is empty. +| `all` | List everything, placeholders included. +|=== + +None of this affects `pnpm run plugins i ep_` on the server. + === Folder structure Ideally a plugin has the following folder structure: diff --git a/doc/plugins.md b/doc/plugins.md index 4ec6700b350..33c4a31d9cd 100644 --- a/doc/plugins.md +++ b/doc/plugins.md @@ -27,6 +27,41 @@ a failed lookup — if the npm registry cannot be reached the full catalog is listed and installs proceed — and `pnpm run plugins i ep_` on the server installs it anyway, for an operator who knows what they are doing. +### Official and third-party plugins + +Anyone can publish an `ep_*` package to npm, and the Etherpad project cannot +review all of them. The catalog marks a plugin **Official** when npm +provenance shows that the published version was built by GitHub Actions from +a repository in the [ether](https://github.com/ether) GitHub org. Everything +else is labelled **Third-party**: it is not maintained by the Etherpad +project and it runs code on your server. The admin UI asks for confirmation +before installing a third-party plugin; official plugins install with one +click. Updates of an installed plugin follow the same rule, and an install +always fetches the exact version the catalog showed, so a label shown for one +release never covers a different one. + +The check is done when the catalog is refreshed and cached per published +version, so it adds no latency to browsing. It relies on npm provenance +rather than on the package's `repository` field, its maintainer list or the +feed's own flags, because a publisher can set any of those to whatever they +like (`src/static/js/pluginfw/pluginTrust.ts`). A plugin from the ether org +that has not been released with provenance yet shows as third-party until its +next release. + +Placeholder packages — a `0.0.0-*` version, or no `repository` in +package.json — are left out of the list, but a search for the exact package +name still finds them, so you can find a package you have just published. + +The `pluginCatalogThirdParty` setting in `settings.json` changes this: + +| Value | Effect | +| --- | --- | +| `label` (default) | List third-party plugins with a badge; placeholders only on an exact-name search. | +| `hide` | List official plugins only. Needs registry.npmjs.org: if it cannot be reached, nothing can be verified and the list is empty. | +| `all` | List everything, placeholders included. | + +None of this affects `pnpm run plugins i ep_` on the server. + ## Folder structure Ideally a plugin has the following folder structure: diff --git a/settings.json.template b/settings.json.template index f6ab6f114b9..44dbd861e62 100644 --- a/settings.json.template +++ b/settings.json.template @@ -488,6 +488,23 @@ "pluginCatalog": "${PRIVACY_PLUGIN_CATALOG:true}" }, + /* + * Plugins in the admin catalog that are not published by the Etherpad + * project are labelled "Third-party": they are not reviewed by the project + * and run code on your server. "Official" means npm provenance shows the + * package was built from a repository in the ether GitHub org. + * - "label" (default): list third-party plugins with a badge and ask for + * confirmation before installing them. Placeholder + * packages (0.0.0-* versions, no repository) are only + * listed when searched for by their exact name. + * - "hide" : list official plugins only. Official status needs + * registry.npmjs.org; if it cannot be reached, nothing + * can be verified and the list is empty. + * - "all" : list everything, placeholders included. + * `pnpm run plugins i ep_` on the server is never affected. + */ + "pluginCatalogThirdParty": "${PLUGIN_CATALOG_THIRD_PARTY:label}", + /* * Should we suppress errors from being visible in the default Pad Text? */ diff --git a/src/locales/en.json b/src/locales/en.json index 7160819df6a..fbc722f1a1d 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -94,6 +94,12 @@ "admin_plugins.deprecated_title": "This plugin is no longer maintained and may break Etherpad. Consider uninstalling it.", "admin_plugins.tag_core": "Core", "admin_plugins.tag_deprecated": "Deprecated", + "admin_plugins.tag_official": "Official", + "admin_plugins.tag_official_title": "Published by the Etherpad project from the ether GitHub organization.", + "admin_plugins.tag_third_party": "Third-party", + "admin_plugins.tag_third_party_title": "Not maintained by the Etherpad project. Plugins run code on your server.", + "admin_plugins.third_party_confirm_title": "Install a third-party plugin?", + "admin_plugins.third_party_confirm_body": "{{plugin}} is not maintained by the Etherpad project and has not been reviewed by it. Plugins run code on your server, with access to your pads and settings. Only install it if you trust its author.", "admin_plugins.update_tooltip": "Update", "admin_plugins.updates_available": "Updates available", "admin_plugins.update_now": "Update", diff --git a/src/node/hooks/express/adminplugins.ts b/src/node/hooks/express/adminplugins.ts index f168c28b0bc..e16d1895c07 100644 --- a/src/node/hooks/express/adminplugins.ts +++ b/src/node/hooks/express/adminplugins.ts @@ -6,6 +6,7 @@ import {QueryType} from "../../types/QueryType"; import { getAvailablePlugins, + getBrowsablePlugins, getInstalledPluginWarnings, install, search, @@ -28,22 +29,27 @@ exports.socketio = (hookName:string, args:ArgsExpressType, cb:Function) => { const {session: {user: {is_admin: isAdmin} = {}} = {}} = socket.conn.request; if (!isAdmin) return; - const checkPluginForUpdates = async () => { + const checkPluginForUpdates = async () => (await checkUpdatesAgainstCatalog()).updatable; + + const checkUpdatesAgainstCatalog = async (): Promise<{ + updatable: string[], catalog: MapArrayType, + }> => { let results: MapArrayType try { results = await getAvailablePlugins(/* maxCacheAge:*/ 60 * 10); } catch (error) { console.error('Error checking for plugin updates:', error); - return []; + return {updatable: [], catalog: {}}; } - return Object.keys(pluginDefs.plugins).filter((plugin) => { + const updatable = Object.keys(pluginDefs.plugins).filter((plugin) => { if (!results[plugin]) return false; const latestVersion = results[plugin].version; const currentVersion = pluginDefs.plugins[plugin].package.version; return semver.gt(latestVersion, currentVersion); - }) + }); + return {updatable, catalog: results}; } socket.on('getStats', ()=>{ @@ -62,7 +68,7 @@ exports.socketio = (hookName:string, args:ArgsExpressType, cb:Function) => { .map((plugin) => ({...pluginDefs.plugins[plugin].package})); if (settings.privacy.pluginCatalog) { - const updatable = await checkPluginForUpdates(); + const {updatable, catalog} = await checkUpdatesAgainstCatalog(); // An installed plugin that has since been deprecated or superseded is // flagged in the UI: the catalog filter only stops new installs, it // cannot help an admin who installed the plugin before (#8246). @@ -75,6 +81,13 @@ exports.socketio = (hookName:string, args:ArgsExpressType, cb:Function) => { installed.forEach((plugin) => { plugin.updatable = updatable.includes(plugin.name); plugin.deprecated = deprecated.get(plugin.name); + if (plugin.updatable) { + // The update installs the catalog's version, so the admin UI + // needs that version and its classification to decide whether + // to ask for confirmation first. + plugin.latestVersion = catalog[plugin.name].version; + plugin.official = catalog[plugin.name].official === true; + } }) } // When the catalog is disabled, `updatable` simply stays unset on @@ -109,7 +122,7 @@ exports.socketio = (hookName:string, args:ArgsExpressType, cb:Function) => { return; } try { - const results = await getAvailablePlugins(/* maxCacheAge:*/ false); + const results = await getBrowsablePlugins(/* maxCacheAge:*/ false); socket.emit('results:available', results); } catch (er) { console.error(er); @@ -137,7 +150,14 @@ exports.socketio = (hookName:string, args:ArgsExpressType, cb:Function) => { } }); - socket.on('install', (pluginName: string) => { + // `install` takes a plugin name, or {name, version} to install the exact + // version the catalog showed (and classified as official or third-party). + socket.on('install', (request: string | {name?: unknown, version?: unknown}) => { + const pluginName = typeof request === 'string' ? request + : typeof request?.name === 'string' ? request.name : ''; + const version = typeof request === 'object' && typeof request?.version === 'string' + ? request.version : undefined; + if (!pluginName) return; install(pluginName, (err: ErrorCaused) => { if (err) console.warn(err.stack || err.toString()); @@ -146,7 +166,7 @@ exports.socketio = (hookName:string, args:ArgsExpressType, cb:Function) => { code: err ? err.code : null, error: err ? err.message : null, }); - }); + }, version); }); diff --git a/src/node/types/PackageInfo.ts b/src/node/types/PackageInfo.ts index ea10c6a360a..fe309eb27dd 100644 --- a/src/node/types/PackageInfo.ts +++ b/src/node/types/PackageInfo.ts @@ -24,8 +24,21 @@ export type PackageInfo = { * `warning` or `failed`. Feed-provided; see pluginCatalogFilter.ts. */ compatibility?: string, + /** + * Catalog entries only: published from an ether/* GitHub repository, as + * shown by npm provenance. Set by core (pluginTrust.ts); the feed's own + * `official` flag is overwritten because it cannot be verified. + */ + official?: boolean, + /** + * Catalog entries only: a `0.0.0-*` or repository-less package, left out + * of browsing and listed only on an exact-name search. + */ + placeholder?: boolean, /** Set on *installed* plugins when a newer version is available. */ updatable?: boolean, + /** Set on *installed*, updatable plugins: the catalog version an update installs. */ + latestVersion?: string, /** * Set on *installed* plugins that npm marks deprecated or that core knows * to be superseded. Carries the human-readable reason. Never set on diff --git a/src/node/utils/Settings.ts b/src/node/utils/Settings.ts index 660bb2e273a..ca8e192c8c3 100644 --- a/src/node/utils/Settings.ts +++ b/src/node/utils/Settings.ts @@ -207,6 +207,7 @@ export type SettingsType = { updateCheck: boolean, pluginCatalog: boolean, }, + pluginCatalogThirdParty: string, skinName: string | null, skinVariants: string, ip: string, @@ -495,6 +496,18 @@ const settings: SettingsType = { // (installer.ts). Manual install via CLI still works. pluginCatalog: true, }, + /* + * How the admin plugin catalog treats plugins that are not published by + * the Etherpad project (see src/static/js/pluginfw/pluginTrust.ts): + * - 'label' (default): list them with a "Third-party" badge and ask for + * confirmation before installing; placeholder packages (0.0.0-* + * versions, no repository) only show up on an exact-name search. + * - 'hide': list official plugins only (empty if npm is unreachable, + * since provenance cannot then be checked). + * - 'all': list everything, placeholders included. + * Installs from the command line are never affected. + */ + pluginCatalogThirdParty: 'label', /* * Skin name. * diff --git a/src/static/js/pluginfw/installer.ts b/src/static/js/pluginfw/installer.ts index 85179ac9f23..f6e3382cf06 100644 --- a/src/static/js/pluginfw/installer.ts +++ b/src/static/js/pluginfw/installer.ts @@ -6,6 +6,7 @@ import {PackageData, PackageInfo} from "../../../node/types/PackageInfo"; import {MapArrayType} from "../../../node/types/MapType"; import path from "path"; +import semver from 'semver'; import {promises as fs} from "fs"; @@ -30,6 +31,14 @@ import { PluginDeprecatedError, } from './pluginCatalogFilter'; import {InstallerTaskQueue} from './installerTasks'; +import { + hasRepositoryField, + isListedInCatalog, + isOfficialProvenance, + isPlaceholderPackage, + normalizeThirdPartyMode, + provenanceSource, +} from './pluginTrust'; import {findEtherpadRoot} from '../../../node/utils/AbsolutePaths'; const logger = log4js.getLogger('plugins'); @@ -170,7 +179,12 @@ export const uninstall = async (pluginName: string, cb:Function|null = null) => // promise forever — without it the finished:install socket event would never // fire and the admin UI would stay spinning indefinitely. const ENGINES_PREFLIGHT_TIMEOUT_MS = 5000; -type NpmVersionMeta = {engines?: {node?: string}, deprecated?: unknown}; +type NpmVersionMeta = { + engines?: {node?: string}, + deprecated?: unknown, + repository?: unknown, + dist?: {integrity?: unknown, attestations?: {url?: unknown}}, +}; const fetchPluginVersionMeta = async ( pluginName: string, version = 'latest', @@ -189,96 +203,240 @@ const fetchPluginVersionMeta = async ( } }; -// Deprecation lookups are cached by name@version because a published version -// is immutable apart from its deprecation flag, which changes maybe once in -// a package's lifetime. Without the cache the admin plugin page would hit -// the npm registry once per listed plugin on every catalog refresh. +/** + * Whether the given published version carries npm provenance from a + * repository in the ether GitHub org (see pluginTrust.ts). Only the + * registry's own attestations endpoint is consulted; a URL pointing anywhere + * else is ignored. Returns undefined when the lookup failed, so the caller + * does not cache a transient failure as "third-party". + */ +const fetchOfficialProvenance = async ( + name: string, + ref: ProvenanceRef, + signal: AbortSignal, +): Promise => { + const {attestationsUrl: url, version, integrity} = ref; + if (typeof url !== 'string' || typeof version !== 'string') return false; + if (!url.startsWith(`${npmRegistry}/-/npm/v1/attestations/`)) return false; + try { + const res = await fetch(url, {headers, signal}); + if (res.status === 404) return false; + if (!res.ok) return undefined; + const source = provenanceSource(await res.json(), {name, version, integrity}); + return isOfficialProvenance(source); + } catch (err) { + logger.debug(`npm provenance lookup for ${name}@${version} fell through: ${err}`); + return undefined; + } +}; + +/** What is needed to look up a version's provenance without refetching its metadata. */ +type ProvenanceRef = {version?: string, integrity?: unknown, attestationsUrl?: unknown}; + +/** What the catalog learns about one published version from npm. */ +export type PluginRegistryInfo = { + /** npm deprecation message, or null when not deprecated. */ + deprecated: string | null, + /** Whether the version's package.json names a repository. */ + hasRepository: boolean, + /** + * Built and published from an ether/* repository (npm provenance). + * `undefined` when provenance was not requested or could not be checked. + */ + official?: boolean, +}; + +// Lookups are cached by name@version because a published version is +// immutable apart from its deprecation flag, which changes maybe once in a +// package's lifetime. Without the cache the admin plugin page would hit the +// npm registry once per listed plugin on every catalog refresh. Provenance +// never changes for a published version, so it is cached separately and +// without expiry: the attestation fetch happens once per version. const DEPRECATION_TTL_MS = 12 * 60 * 60 * 1000; const DEPRECATION_SWEEP_BUDGET_MS = 15000; const DEPRECATION_CONCURRENCY = 8; const DEPRECATION_CACHE_MAX = 1000; -const deprecationCache = new Map(); +type CachedRegistryInfo = { + deprecated: string | null, + hasRepository: boolean, + provenance: ProvenanceRef, +}; +const registryInfoCache = new Map(); +const provenanceCache = new Map(); // Lookups that have been started but not finished, so two concurrent sweeps // (the admin page fires `getInstalled` and `search` together) join one // request per package instead of issuing two. `undefined` means the lookup -// failed, i.e. the deprecation state is unknown. -const deprecationInFlight = new Map>(); +// failed, i.e. the state is unknown. +const registryInfoInFlight = new Map>(); +const provenanceInFlight = new Map>(); // Exported for tests; also lets an operator-triggered catalog reload pick up // a deprecation published in the last 12 hours. -export const clearDeprecationCache = () => deprecationCache.clear(); +export const clearDeprecationCache = () => { + registryInfoCache.clear(); + provenanceCache.clear(); +}; + +/** Runs `fn` over `jobs` with bounded concurrency until done or `signal` aborts. */ +const runPool = async ( + jobs: T[], signal: AbortSignal, fn: (job: T) => Promise, +) => { + let index = 0; + const worker = async () => { + while (index < jobs.length) { + if (signal.aborted) return; + await fn(jobs[index++]); + } + }; + await Promise.all( + Array.from({length: Math.min(DEPRECATION_CONCURRENCY, jobs.length)}, worker)); +}; /** - * Looks up the npm deprecation notice for each of the given packages. + * Looks up deprecation and repository for each of the given packages and, + * with `withProvenance`, whether it is official. + * + * The metadata sweep and the provenance sweep each get their own time + * budget, so a slow registry cannot starve one with the other. * - * Fail-open by design: a package whose lookup fails (offline, npm blocked by - * a firewall, 404, timeout, overall budget exceeded) is simply absent from - * the returned map, and the caller then treats it as not deprecated. An - * admin behind a firewall gets the full catalog, not an empty one. + * Fail-open by design: a package whose metadata lookup fails (offline, npm + * blocked by a firewall, 404, timeout, overall budget exceeded) is simply + * absent from the returned map, and the caller then treats it as not + * deprecated and not a placeholder. An admin behind a firewall gets the full + * catalog, not an empty one. Provenance that could not be checked is left + * `undefined` and is never treated as official. */ -export const fetchPluginDeprecations = async ( +export const fetchPluginRegistryInfo = async ( pkgs: ReadonlyArray<{name: string, version?: string}>, -): Promise> => { - const result = new Map(); + {withProvenance = true}: {withProvenance?: boolean} = {}, +): Promise> => { + const cached = new Map(); const pending: Array<{name: string, version: string, key: string}> = []; const now = Date.now(); - if (deprecationCache.size > DEPRECATION_CACHE_MAX) deprecationCache.clear(); + if (registryInfoCache.size > DEPRECATION_CACHE_MAX) registryInfoCache.clear(); + if (provenanceCache.size > DEPRECATION_CACHE_MAX) provenanceCache.clear(); for (const pkg of pkgs) { if (!pkg || typeof pkg.name !== 'string') continue; const version = typeof pkg.version === 'string' && pkg.version ? pkg.version : 'latest'; const key = `${pkg.name}@${version}`; - const cached = deprecationCache.get(key); - if (cached && cached.expires > now) { - result.set(pkg.name, cached.deprecated); + const hit = registryInfoCache.get(key); + if (hit && hit.expires > now) { + cached.set(pkg.name, hit.info); } else { pending.push({name: pkg.name, version, key}); } } - if (pending.length === 0) return result; - - // One controller for the whole sweep: if the registry is slow we give up - // on the remainder rather than making the admin page wait indefinitely. - const budget = AbortSignal.timeout(DEPRECATION_SWEEP_BUDGET_MS); - const lookup = (job: {name: string, version: string, key: string}) => { - const started = deprecationInFlight.get(job.key); - if (started) return started; - const promise = (async () => { - const meta = await fetchPluginVersionMeta(job.name, job.version, budget); - if (meta === undefined) return undefined; // unknown -> not hidden - const deprecated = normalizeDeprecation(meta.deprecated); - deprecationCache.set(job.key, {deprecated, expires: Date.now() + DEPRECATION_TTL_MS}); - return deprecated; - })().finally(() => deprecationInFlight.delete(job.key)); - deprecationInFlight.set(job.key, promise); - return promise; - }; - let index = 0; - const worker = async () => { - while (index < pending.length) { - if (budget.aborted) return; - const job = pending[index++]; - const deprecated = await lookup(job); - if (deprecated !== undefined) result.set(job.name, deprecated); + + if (pending.length > 0) { + // One controller for the whole sweep: if the registry is slow we give up + // on the remainder rather than making the admin page wait indefinitely. + const budget = AbortSignal.timeout(DEPRECATION_SWEEP_BUDGET_MS); + const lookup = (job: {name: string, version: string, key: string}) => { + const started = registryInfoInFlight.get(job.key); + if (started) return started; + const promise = (async (): Promise => { + const meta = await fetchPluginVersionMeta(job.name, job.version, budget); + if (meta === undefined) return undefined; // unknown -> not hidden + const info: CachedRegistryInfo = { + deprecated: normalizeDeprecation(meta.deprecated), + hasRepository: hasRepositoryField(meta.repository), + provenance: { + version: typeof (meta as any).version === 'string' ? (meta as any).version : undefined, + integrity: meta.dist?.integrity, + attestationsUrl: meta.dist?.attestations?.url, + }, + }; + registryInfoCache.set(job.key, {info, expires: Date.now() + DEPRECATION_TTL_MS}); + return info; + })().finally(() => registryInfoInFlight.delete(job.key)); + registryInfoInFlight.set(job.key, promise); + return promise; + }; + await runPool(pending, budget, async (job) => { + const info = await lookup(job); + if (info !== undefined) cached.set(job.name, info); + }); + if (budget.aborted && cached.size < pkgs.length) { + logger.warn('Plugin catalog: npm metadata lookup timed out; ' + + 'listing the plugins it could not check.'); + } + } + + const result = new Map(); + const needProvenance: Array<{name: string, key: string, ref: ProvenanceRef}> = []; + for (const [name, info] of cached) { + const out: PluginRegistryInfo = {deprecated: info.deprecated, hasRepository: info.hasRepository}; + if (withProvenance) { + const key = `${name}@${info.provenance.version}`; + const known = provenanceCache.get(key); + if (known !== undefined) { + out.official = known; + } else { + needProvenance.push({name, key, ref: info.provenance}); + } + } + result.set(name, out); + } + + if (needProvenance.length > 0) { + const budget = AbortSignal.timeout(DEPRECATION_SWEEP_BUDGET_MS); + const check = (job: {name: string, key: string, ref: ProvenanceRef}) => { + const started = provenanceInFlight.get(job.key); + if (started) return started; + const promise = (async () => { + const official = await fetchOfficialProvenance(job.name, job.ref, budget); + if (official !== undefined) provenanceCache.set(job.key, official); + return official; + })().finally(() => provenanceInFlight.delete(job.key)); + provenanceInFlight.set(job.key, promise); + return promise; + }; + await runPool(needProvenance, budget, async (job) => { + const official = await check(job); + if (official !== undefined) result.get(job.name)!.official = official; + }); + if (budget.aborted) { + logger.warn('Plugin catalog: npm provenance lookup timed out; the plugins it ' + + 'could not check are shown as third-party until the next refresh.'); } - }; - await Promise.all( - Array.from({length: Math.min(DEPRECATION_CONCURRENCY, pending.length)}, worker)); - if (budget.aborted && result.size < pkgs.length) { - logger.warn('Plugin catalog: npm deprecation lookup timed out; ' + - 'listing the plugins it could not check.'); } return result; }; -export const install = async (pluginName: string, cb:Function|null = null) => { +/** + * Looks up the npm deprecation notice for each of the given packages. Same + * fail-open contract as {@link fetchPluginRegistryInfo}; provenance is not + * fetched because only the deprecation is needed. + */ +export const fetchPluginDeprecations = async ( + pkgs: ReadonlyArray<{name: string, version?: string}>, +): Promise> => { + const info = await fetchPluginRegistryInfo(pkgs, {withProvenance: false}); + return new Map([...info].map(([name, i]) => [name, i.deprecated])); +}; + +/** + * Installs a plugin from npm. + * + * @param version exact version to install. The admin catalog passes the + * version it classified, so an "official" label shown for one release can + * never authorise installing a different, newer release. Omitted, the + * latest version is installed. + */ +export const install = async ( + pluginName: string, cb:Function|null = null, version?: string, +) => { cb = wrapTaskCb(cb); - logger.info(`Installing plugin ${pluginName}...`); + logger.info(`Installing plugin ${pluginName}${version ? `@${version}` : ''}...`); try { + if (version !== undefined && !semver.valid(version)) { + throw new Error(`Invalid version for ${pluginName}: ${version}`); + } // A superseded package is refused before any network call, so the block // holds even when npm is unreachable. const known = installBlockReason(pluginName); if (known) throw new PluginDeprecatedError(pluginName, known.detail); - const meta = await fetchPluginVersionMeta(pluginName); + const meta = await fetchPluginVersionMeta(pluginName, version); const compat = checkEngineCompatibility(meta?.engines?.node, process.version); if (!compat.compatible) { throw new EngineIncompatibleError(pluginName, compat.required, compat.current); @@ -289,7 +447,7 @@ export const install = async (pluginName: string, cb:Function|null = null) => { // only — an unreachable registry leaves the install to proceed. const deprecated = installBlockReason(pluginName, normalizeDeprecation(meta?.deprecated)); if (deprecated) throw new PluginDeprecatedError(pluginName, deprecated.detail); - await linkInstaller.installPlugin(pluginName); + await linkInstaller.installPlugin(pluginName, version); logger.info(`Successfully installed plugin ${pluginName}`); await hooks.aCallAll('pluginInstall', {pluginName}); cb(null); @@ -301,6 +459,11 @@ export const install = async (pluginName: string, cb:Function|null = null) => { export let availablePlugins:MapArrayType|null = null; let cacheTimestamp = 0; +// Set when the last refresh could not check provenance for some plugins. +// Such a catalog is only reused briefly, so the next search retries instead +// of showing official plugins as third-party for the full cache lifetime. +let catalogIncomplete = false; +const INCOMPLETE_CATALOG_MAX_AGE = 60; // The admin plugin page emits `getInstalled` (which checks for updates) and // `search` at the same time on load, and both end up here. Without sharing @@ -314,7 +477,9 @@ export const getAvailablePlugins = async (maxCacheAge: number | false) => { const nowTimestamp = Math.round(Date.now() / 1000); // check cache age before making any request - if (availablePlugins && maxCacheAge && (nowTimestamp - cacheTimestamp) <= maxCacheAge) { + const maxAge = maxCacheAge && catalogIncomplete + ? Math.min(maxCacheAge, INCOMPLETE_CATALOG_MAX_AGE) : maxCacheAge; + if (availablePlugins && maxAge && (nowTimestamp - cacheTimestamp) <= maxAge) { return availablePlugins; } @@ -364,13 +529,14 @@ const hideUninstallablePlugins = async ( entries: MapArrayType, ): Promise> => { const list = Object.values(entries) as unknown as CatalogEntry[]; - let deprecations = new Map(); + let registryInfo = new Map(); try { - deprecations = await fetchPluginDeprecations(list); + registryInfo = await fetchPluginRegistryInfo(list); } catch (err) { - logger.warn(`Plugin catalog: could not check npm deprecations (${err}); ` + + logger.warn(`Plugin catalog: could not check npm metadata (${err}); ` + 'listing all plugins.'); } + const deprecations = new Map([...registryInfo].map(([n, i]) => [n, i.deprecated])); const {kept, excluded, compatibilityIgnored} = filterCatalogEntries( entries as unknown as Record, deprecations); if (compatibilityIgnored) { @@ -385,7 +551,37 @@ const hideUninstallablePlugins = async ( logger.debug(`Plugin catalog: hiding ${name} (${exclusion.cause}): ${exclusion.detail}`); } } - return kept as unknown as MapArrayType; + // Classify what is left. `official` is always overwritten: the feed ships + // its own `official` flag, which core cannot verify and must not pass on. + const classified = kept as unknown as MapArrayType; + let official = 0; + let placeholders = 0; + let unknown = 0; + for (const key of Object.keys(classified)) { + const entry = classified[key]; + if (!entry) continue; + const info = registryInfo.get(entry.name); + if (info?.official === undefined) unknown++; + entry.official = info?.official === true; + entry.placeholder = !entry.official && + isPlaceholderPackage(entry.version, info?.hasRepository); + if (entry.official) official++; + if (entry.placeholder) placeholders++; + } + catalogIncomplete = unknown > 0; + logger.info(`Plugin catalog: ${official} official plugin(s), ` + + `${Object.keys(classified).length - official} third-party ` + + `(${placeholders} placeholder package(s) listed only on exact-name search).`); + if (unknown > 0) { + logger.warn(`Plugin catalog: could not check npm provenance for ${unknown} plugin(s); ` + + 'they are treated as third-party until a later refresh succeeds.'); + if (normalizeThirdPartyMode(settings.pluginCatalogThirdParty) === 'hide') { + logger.warn('Plugin catalog: pluginCatalogThirdParty is "hide", so plugins whose ' + + 'provenance could not be checked are not listed. If the catalog is ' + + 'empty, check that this server can reach registry.npmjs.org.'); + } + } + return classified; }; /** @@ -417,9 +613,27 @@ export const getInstalledPluginWarnings = async ( }; +/** + * The catalog as the admin may browse it: {@link getAvailablePlugins} with + * the `pluginCatalogThirdParty` policy applied (no search term, so + * placeholders are left out in the default mode). The unfiltered catalog is + * still used internally, e.g. for update checks. + */ +export const getBrowsablePlugins = async (maxCacheAge: number | false) => { + const all = await getAvailablePlugins(maxCacheAge); + const mode = normalizeThirdPartyMode(settings.pluginCatalogThirdParty); + const out: MapArrayType = {}; + for (const key of Object.keys(all)) { + if (all[key] && isListedInCatalog(all[key], mode)) out[key] = all[key]; + } + return out; +}; + export const search = (searchTerm: string, maxCacheAge: number) => getAvailablePlugins(maxCacheAge).then( (results: MapArrayType) => { const res:MapArrayType = {}; + const mode = normalizeThirdPartyMode(settings.pluginCatalogThirdParty); + const rawTerm = searchTerm || ''; if (searchTerm) { searchTerm = searchTerm.toLowerCase(); @@ -429,6 +643,10 @@ export const search = (searchTerm: string, maxCacheAge: number) => getAvailableP // for every available plugin // TODO: Also search in keywords here! if (pluginName.indexOf(plugins.prefix) !== 0) continue; + // Third-party / placeholder policy (pluginTrust.ts). A placeholder is + // still found by its exact name so a developer can find the package + // they just published. + if (!isListedInCatalog(results[pluginName], mode, rawTerm)) continue; if (searchTerm && !~results[pluginName].name.toLowerCase().indexOf(searchTerm) && (typeof results[pluginName].description !== 'undefined' && diff --git a/src/static/js/pluginfw/pluginTrust.ts b/src/static/js/pluginfw/pluginTrust.ts new file mode 100644 index 00000000000..6a47aa16514 --- /dev/null +++ b/src/static/js/pluginfw/pluginTrust.ts @@ -0,0 +1,156 @@ +'use strict'; + +/** + * "Official" vs "third-party" for the admin plugin catalog. + * + * Anyone can publish an `ep_*` package to npm, and the plugin feed lists + * every one of them. Etherpad cannot review them all, so the catalog labels + * the ones the Etherpad project itself publishes as official and everything + * else as third-party. + * + * What makes a plugin official here is npm provenance, not anything the + * package says about itself. The `repository` field in package.json, the + * feed's own `official` flag and the npm maintainer list can all be set by + * whoever publishes the package (`npm owner add` needs no consent from the + * added user). A provenance attestation cannot: plugins in the ether GitHub + * org publish from GitHub Actions through npm trusted publishing, and npm + * only accepts the attestation after checking its Sigstore signature against + * the GitHub OIDC identity of the workflow that built the package. Core does + * not re-verify that signature; it trusts registry.npmjs.org over TLS, which + * is the same trust it already places in the tarball it installs. + * + * The attestation is accepted only when it is about this exact package: the + * in-toto subject must name `@` and carry the same sha512 as + * the version's `dist.integrity`. The build must come from a repository + * owned by the ether org, matched both by URL and by the org's numeric + * GitHub ID, so a renamed or re-registered org name does not inherit trust. + * + * Everything in this module is pure so it can be tested without a network. + */ + +export const OFFICIAL_GITHUB_ORG = 'ether'; +/** Numeric GitHub ID of the ether org (`gh api orgs/ether --jq .id`). */ +export const OFFICIAL_GITHUB_OWNER_ID = '181731'; +export const SLSA_PROVENANCE_V1 = 'https://slsa.dev/provenance/v1'; + +const officialRepoRe = + new RegExp(`^https://github\\.com/${OFFICIAL_GITHUB_ORG}/[A-Za-z0-9._-]+$`); + +/** True for `https://github.com/ether/`, nothing looser. */ +export const isOfficialRepository = (url: unknown): boolean => + typeof url === 'string' && officialRepoRe.test(url); + +/** Converts an SRI string (`sha512-`) to the hex digest in-toto uses. */ +export const sha512HexFromIntegrity = (integrity: unknown): string | null => { + if (typeof integrity !== 'string') return null; + const m = /^sha512-([A-Za-z0-9+/=]+)$/.exec(integrity.trim()); + if (!m) return null; + const hex = Buffer.from(m[1], 'base64').toString('hex'); + return hex.length === 128 ? hex : null; +}; + +const npmPurl = (name: string, version: string) => + `pkg:npm/${name.replace(/^@/, '%40')}@${version}`; + +/** + * Pulls the source repository out of an npm attestations document + * (`GET /-/npm/v1/attestations/@`), after checking that the + * SLSA provenance statement in it is about the given package version. + * + * @returns the source repository URL and owner ID, or null when the document + * holds no provenance for this exact package. + */ +export const provenanceSource = ( + attestations: unknown, + pkg: {name: string, version: string, integrity?: unknown}, +): {repository: string, ownerId: string | null} | null => { + const list = (attestations as any)?.attestations; + if (!Array.isArray(list)) return null; + const wantDigest = sha512HexFromIntegrity(pkg.integrity); + if (!wantDigest) return null; + const wantName = npmPurl(pkg.name, pkg.version); + for (const att of list) { + if (!att || att.predicateType !== SLSA_PROVENANCE_V1) continue; + const payload = att.bundle?.dsseEnvelope?.payload; + if (typeof payload !== 'string') continue; + let statement: any; + try { + statement = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')); + } catch { + continue; + } + if (statement?.predicateType !== SLSA_PROVENANCE_V1) continue; + const subjects = Array.isArray(statement.subject) ? statement.subject : []; + const matches = subjects.some((s: any) => + s && s.name === wantName && s.digest?.sha512 === wantDigest); + if (!matches) continue; + const def = statement.predicate?.buildDefinition; + const repository = def?.externalParameters?.workflow?.repository; + if (typeof repository !== 'string') continue; + const ownerId = def?.internalParameters?.github?.repository_owner_id; + return {repository, ownerId: typeof ownerId === 'string' ? ownerId : null}; + } + return null; +}; + +/** Whether the given provenance makes a package official. */ +export const isOfficialProvenance = ( + source: {repository: string, ownerId: string | null} | null, +): boolean => !!source && isOfficialRepository(source.repository) && + source.ownerId === OFFICIAL_GITHUB_OWNER_ID; + +/** + * A package that is a name grab or a test upload rather than a plugin: a + * `0.0.0` pre-release version, or no `repository` at all. Such packages are + * left out of catalog browsing but are still found by an exact-name search, + * so a developer can find the package they just published. + * + * @param hasRepository `false` only when npm metadata was fetched and has no + * repository; `undefined` (lookup failed) does not count as a placeholder. + */ +export const isPlaceholderPackage = ( + version: unknown, + hasRepository?: boolean, +): boolean => (typeof version === 'string' && /^0\.0\.0(-|$)/.test(version.trim())) || + hasRepository === false; + +/** Whether npm version metadata names a source repository. */ +export const hasRepositoryField = (repository: unknown): boolean => { + if (typeof repository === 'string') return repository.trim() !== ''; + if (repository && typeof repository === 'object') { + const url = (repository as any).url; + return typeof url === 'string' && url.trim() !== ''; + } + return false; +}; + +/** + * `pluginCatalogThirdParty` setting: + * - `label` (default): list third-party plugins with a "Third-party" badge; + * leave placeholder packages out unless searched for by exact name. + * - `hide`: list official plugins only. + * - `all`: list everything, placeholders included (still labelled). + */ +export type ThirdPartyMode = 'label' | 'hide' | 'all'; +export const THIRD_PARTY_MODES: ReadonlyArray = ['label', 'hide', 'all']; + +export const normalizeThirdPartyMode = (raw: unknown): ThirdPartyMode => { + const v = typeof raw === 'string' ? raw.trim().toLowerCase() : ''; + return (THIRD_PARTY_MODES as ReadonlyArray).includes(v) ? v as ThirdPartyMode : 'label'; +}; + +/** + * Whether a classified catalog entry is listed for the given search. + * + * @param searchTerm what the admin typed (any case), or empty for browsing. + */ +export const isListedInCatalog = ( + entry: {name: string, official?: boolean, placeholder?: boolean}, + mode: ThirdPartyMode, + searchTerm = '', +): boolean => { + if (entry.official) return true; + if (mode === 'hide') return false; + if (mode === 'all' || !entry.placeholder) return true; + return searchTerm.trim().toLowerCase() === entry.name.toLowerCase(); +}; diff --git a/src/tests/backend/specs/pluginCatalog.ts b/src/tests/backend/specs/pluginCatalog.ts index c923dd6443d..ac167cdcc5f 100644 --- a/src/tests/backend/specs/pluginCatalog.ts +++ b/src/tests/backend/specs/pluginCatalog.ts @@ -6,9 +6,13 @@ import { clearDeprecationCache, fetchPluginDeprecations, getAvailablePlugins, + getBrowsablePlugins, getInstalledPluginWarnings, install, + linkInstaller, + search, } from '../../../static/js/pluginfw/installer'; +import {OFFICIAL_GITHUB_OWNER_ID} from '../../../static/js/pluginfw/pluginTrust'; import settings from '../../../node/utils/Settings'; /** @@ -70,10 +74,23 @@ describe(__filename, function () { type NpmBehaviour = (name: string, version: string) => unknown; - const stubFetch = (npm: NpmBehaviour) => sinon.stub(global, 'fetch') + type AttestationBehaviour = (name: string, version: string) => unknown; + + const stubFetch = ( + npm: NpmBehaviour, + {feedBody = feed as Record, attestations}: + {feedBody?: Record, attestations?: AttestationBehaviour} = {}, + ) => sinon.stub(global, 'fetch') .callsFake(async (input: any) => { const url = String(input); - if (url === feedUrl) return jsonResponse(feed) as any; + if (url === feedUrl) return jsonResponse(feedBody) as any; + const att = /\/-\/npm\/v1\/attestations\/(.+)@([^@]+)$/.exec(url); + if (att && url.startsWith(`${npmRegistry}/`)) { + const body = attestations ? attestations(att[1], att[2]) : undefined; + if (body instanceof Error) throw body; + if (body === undefined) return {ok: false, status: 404, statusText: 'Not Found'} as any; + return jsonResponse(body) as any; + } const m = url.startsWith(`${npmRegistry}/`) ? /\/([^/]+)\/([^/]+)$/.exec(url) : null; @@ -240,4 +257,205 @@ describe(__filename, function () { assert.equal(second.get('ep_stale'), 'gone'); }); }); + describe('official vs third-party (pluginTrust.ts)', function () { + // An SRI hash and the matching in-toto hex digest; any 64 bytes will do. + const bytes = Buffer.alloc(64, 7); + const integrity = `sha512-${bytes.toString('base64')}`; + const digest = bytes.toString('hex'); + + const provenance = (name: string, version: string, repository: string) => ({ + attestations: [{ + predicateType: 'https://slsa.dev/provenance/v1', + bundle: {dsseEnvelope: {payload: Buffer.from(JSON.stringify({ + _type: 'https://in-toto.io/Statement/v1', + subject: [{name: `pkg:npm/${name}@${version}`, digest: {sha512: digest}}], + predicateType: 'https://slsa.dev/provenance/v1', + predicate: {buildDefinition: { + externalParameters: {workflow: {repository}}, + internalParameters: {github: {repository_owner_id: OFFICIAL_GITHUB_OWNER_ID}}, + }}, + })).toString('base64')}}, + }], + }); + + const trustFeed = { + ep_align: {name: 'ep_align', description: 'Alignment', time: '2026-07-01', + version: '11.0.43', official: true, compatibility: 'compatible'}, + ep_liar: {name: 'ep_liar', description: 'Claims to be official', time: '2026-11-21', + version: '1.0.0', official: true, compatibility: 'compatible'}, + ep_community: {name: 'ep_community', description: 'A real third-party plugin', + time: '2026-01-01', version: '2.0.0', official: false, compatibility: 'compatible'}, + ep_nxs65012: {name: 'ep_nxs65012', description: '', time: '2026-11-21', + version: '0.0.0-stage', official: false, compatibility: 'compatible'}, + ep_norepo: {name: 'ep_norepo', description: 'no repository', time: '2026-11-21', + version: '1.0.0', official: false, compatibility: 'compatible'}, + }; + + const npmMeta = (name: string, version: string) => { + const base: any = {name, version, dist: {integrity}}; + if (name !== 'ep_norepo' && name !== 'ep_nxs65012') { + base.repository = {type: 'git', url: `git+https://github.com/ether/${name}.git`}; + } + if (name === 'ep_align' || name === 'ep_liar') { + base.dist.attestations = { + url: `${npmRegistry}/-/npm/v1/attestations/${name}@${version}`, + provenance: {predicateType: 'https://slsa.dev/provenance/v1'}, + }; + } + return base; + }; + + const attestations = (name: string, version: string) => (name === 'ep_align' + ? provenance(name, version, 'https://github.com/ether/ep_align') + // ep_liar declares an ether repository in package.json, but its + // provenance shows where it was really built. + : provenance(name, version, 'https://github.com/nx-zd/ep_liar')); + + let savedMode: string; + beforeEach(function () { + savedMode = settings.pluginCatalogThirdParty; + }); + afterEach(function () { + settings.pluginCatalogThirdParty = savedMode; + }); + + const names = (res: Record) => Object.keys(res).sort(); + + it('marks only plugins with ether provenance as official', async function () { + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + const available = await getAvailablePlugins(false); + assert.equal(available.ep_align.official, true); + assert.equal(available.ep_liar.official, false, + 'the feed flag and package.json repository must not make a plugin official'); + assert.equal(available.ep_community.official, false); + assert.equal(available.ep_nxs65012.placeholder, true); + assert.equal(available.ep_norepo.placeholder, true); + assert.equal(available.ep_community.placeholder, false); + }); + + it('caches provenance, so a refresh does not refetch attestations', async function () { + const fetchStub = stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + await getAvailablePlugins(false); + const attCalls = () => fetchStub.getCalls() + .filter((c) => String(c.args[0]).includes('/-/npm/v1/attestations/')).length; + assert.equal(attCalls(), 2); + await getAvailablePlugins(false); + assert.equal(attCalls(), 2); + }); + + it('treats every plugin as third-party when npm is unreachable', async function () { + stubFetch(() => new Error('offline'), {feedBody: trustFeed}); + const available = await getAvailablePlugins(false); + for (const entry of Object.values(available)) assert.equal(entry.official, false); + // The 0.0.0 placeholder is still recognised from the feed alone; the + // repository check needs npm, so it fails open. + assert.equal(available.ep_nxs65012.placeholder, true); + assert.equal(available.ep_norepo.placeholder, false); + }); + + it('label (default): hides placeholders from browsing, keeps third-party', async function () { + settings.pluginCatalogThirdParty = 'label'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await search('', 0)), ['ep_align', 'ep_community', 'ep_liar']); + assert.deepEqual(names(await search('nxs', 0)), []); + }); + + it('label: an exact-name search finds a placeholder', async function () { + settings.pluginCatalogThirdParty = 'label'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await search('ep_nxs65012', 0)), ['ep_nxs65012']); + assert.deepEqual(names(await search('EP_NOREPO', 0)), ['ep_norepo']); + }); + + it('hide: lists official plugins only', async function () { + settings.pluginCatalogThirdParty = 'hide'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await search('', 0)), ['ep_align']); + assert.deepEqual(names(await search('ep_community', 0)), []); + }); + + it('all: lists everything', async function () { + settings.pluginCatalogThirdParty = 'all'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await search('', 0)), Object.keys(trustFeed).sort()); + }); + it('getAvailable (browsing) applies the same policy as search', async function () { + settings.pluginCatalogThirdParty = 'label'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await getBrowsablePlugins(false)), + ['ep_align', 'ep_community', 'ep_liar']); + settings.pluginCatalogThirdParty = 'hide'; + assert.deepEqual(names(await getBrowsablePlugins(false)), ['ep_align']); + }); + + it('the deprecation-only lookup does not fetch attestations', async function () { + const fetchStub = stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + await fetchPluginDeprecations([{name: 'ep_align', version: '11.0.43'}]); + const attCalls = fetchStub.getCalls() + .filter((c) => String(c.args[0]).includes('/-/npm/v1/attestations/')); + assert.equal(attCalls.length, 0); + }); + + it('provenance fetched later reuses the cached metadata', async function () { + const fetchStub = stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + await fetchPluginDeprecations([{name: 'ep_align', version: '11.0.43'}]); + const metaCalls = () => fetchStub.getCalls() + .filter((c) => String(c.args[0]).endsWith('/ep_align/11.0.43')).length; + assert.equal(metaCalls(), 1); + const available = await getAvailablePlugins(false); + assert.equal(available.ep_align.official, true); + assert.equal(metaCalls(), 1); + }); + + it('retries a catalog whose provenance could not be checked sooner', async function () { + let attestationsDown = true; + const fetchStub = stubFetch(npmMeta, {feedBody: trustFeed, + attestations: (n, v) => (attestationsDown ? new Error('timeout') : attestations(n, v))}); + const feedCalls = () => + fetchStub.getCalls().filter((c) => String(c.args[0]) === feedUrl).length; + const first = await getAvailablePlugins(false); + assert.equal(first.ep_align.official, false, 'unknown is never official'); + const realNow = Date.now; + const start = realNow(); + try { + // Two minutes later: inside the normal 10-minute cache, past the + // 1-minute limit for a catalog with unchecked provenance. + sinon.stub(Date, 'now').returns(start + 2 * 60 * 1000); + attestationsDown = false; + const second = await getAvailablePlugins(600); + assert.equal(feedCalls(), 2, 'an incomplete catalog must be refreshed'); + assert.equal(second.ep_align.official, true); + (Date.now as sinon.SinonStub).returns(start + 4 * 60 * 1000); + await getAvailablePlugins(600); + assert.equal(feedCalls(), 2, 'a complete catalog is cached as before'); + } finally { + (Date.now as any).restore?.(); + } + }); + }); + + describe('install pins the version the catalog showed', function () { + const installOnce = (name: string, version?: string) => new Promise( + (resolve) => install(name, (err: any) => resolve(err), version)); + + it('passes the requested version to the installer and to the npm checks', async function () { + const fetchStub = stubFetch(() => ({engines: {node: '>=18'}})); + // Rejecting keeps the install from "succeeding", which would persist + // installed_plugins.json and fire the restartServer hook. + const installStub = sinon.stub(linkInstaller, 'installPlugin') + .rejects(new Error('stop here')); + const err = await installOnce('ep_align', '11.0.43'); + assert.match(String(err), /stop here/); + assert.deepEqual(installStub.firstCall.args, ['ep_align', '11.0.43']); + assert.ok(fetchStub.getCalls().some((c) => String(c.args[0]).endsWith('/ep_align/11.0.43'))); + }); + + it('refuses a version that is not a plain semver', async function () { + stubFetch(() => ({})); + const installStub = sinon.stub(linkInstaller, 'installPlugin').resolves(); + const err = await installOnce('ep_align', 'latest; rm -rf /'); + assert.match(String(err), /Invalid version/); + assert.equal(installStub.callCount, 0); + }); + }); }); diff --git a/src/tests/backend/specs/pluginTrust.ts b/src/tests/backend/specs/pluginTrust.ts new file mode 100644 index 00000000000..e8c4953e24c --- /dev/null +++ b/src/tests/backend/specs/pluginTrust.ts @@ -0,0 +1,210 @@ +'use strict'; + +import {strict as assert} from 'assert'; +import { + hasRepositoryField, + isListedInCatalog, + isOfficialProvenance, + isOfficialRepository, + isPlaceholderPackage, + normalizeThirdPartyMode, + OFFICIAL_GITHUB_OWNER_ID, + provenanceSource, + sha512HexFromIntegrity, + SLSA_PROVENANCE_V1, +} from '../../../static/js/pluginfw/pluginTrust'; + +// "Official" in the admin plugin catalog must not be something a publisher +// can claim for themselves. These tests pin the classification: only an npm +// provenance attestation for the exact package version, built in a +// repository owned by the ether GitHub org, makes a plugin official. + +// Real values from ep_align@11.0.58 on registry.npmjs.org. +const INTEGRITY = + 'sha512-gaS0jGRGYJdYBAU3cc0M2ah6tTUjmF/L3BYRPsWSrNDdC+VOl9UCSd9qSvdWOowXW4jHDtGUVUZTmhH/sXcb8w=='; +const DIGEST = '81a4b48c644660975804053771cd0cd9a87ab53523985fcbdc16113ec592acd0' + + 'dd0be54e97d50249df6a4af7563a8c175b88c70ed1945546539a11ffb1771bf3'; + +const makeAttestations = ({ + name = 'ep_align', + version = '11.0.58', + digest = DIGEST, + repository = 'https://github.com/ether/ep_align', + ownerId = OFFICIAL_GITHUB_OWNER_ID, + predicateType = SLSA_PROVENANCE_V1, +}: Partial> = {}) => { + const statement = { + _type: 'https://in-toto.io/Statement/v1', + subject: [{name: `pkg:npm/${name}@${version}`, digest: {sha512: digest}}], + predicateType, + predicate: { + buildDefinition: { + externalParameters: {workflow: {repository, ref: 'refs/heads/main'}}, + internalParameters: {github: {repository_owner_id: ownerId}}, + }, + }, + }; + return { + attestations: [ + {predicateType: 'https://github.com/npm/attestation/tree/main/specs/publish/v0.1', + bundle: {dsseEnvelope: {payload: Buffer.from('{}').toString('base64')}}}, + {predicateType, + bundle: {dsseEnvelope: {payload: Buffer.from(JSON.stringify(statement)).toString('base64')}}}, + ], + }; +}; + +describe(__filename, function () { + const pkg = {name: 'ep_align', version: '11.0.58', integrity: INTEGRITY}; + + describe('isOfficialRepository', function () { + it('accepts a repository in the ether org', function () { + assert.equal(isOfficialRepository('https://github.com/ether/ep_align'), true); + }); + for (const url of [ + 'https://github.com/etherx/ep_align', + 'https://github.com/ether/ep_align/../../evil/x', + 'https://github.com/ether/ep_align.git?x=https://github.com/ether/', + 'https://gitlab.com/ether/ep_align', + 'git+https://github.com/ether/ep_align.git', + 'https://github.com/ether', + 'https://github.com/nx-zd/ep_nxs65012', + undefined, + ]) { + it(`rejects ${url}`, function () { + assert.equal(isOfficialRepository(url), false); + }); + } + }); + + describe('sha512HexFromIntegrity', function () { + it('converts an SRI hash to the hex digest in-toto uses', function () { + assert.equal(sha512HexFromIntegrity(INTEGRITY), DIGEST); + }); + it('rejects anything that is not sha512', function () { + assert.equal(sha512HexFromIntegrity('sha1-abc'), null); + assert.equal(sha512HexFromIntegrity(undefined), null); + }); + }); + + describe('provenanceSource / isOfficialProvenance', function () { + it('treats a matching ether provenance attestation as official', function () { + const source = provenanceSource(makeAttestations(), pkg); + assert.deepEqual(source, + {repository: 'https://github.com/ether/ep_align', ownerId: OFFICIAL_GITHUB_OWNER_ID}); + assert.equal(isOfficialProvenance(source), true); + }); + + it('is third-party when the package has no provenance at all', function () { + assert.equal(provenanceSource(undefined, pkg), null); + assert.equal(provenanceSource({attestations: []}, pkg), null); + assert.equal(isOfficialProvenance(null), false); + }); + + it('is third-party when the build came from another org', function () { + const source = provenanceSource( + makeAttestations({repository: 'https://github.com/nx-zd/ep_align'}), pkg); + assert.equal(isOfficialProvenance(source), false); + }); + + it('is third-party when the repo URL says ether but the owner ID does not', function () { + // A re-registered or renamed "ether" org would carry a different ID. + const source = provenanceSource(makeAttestations({ownerId: '999'}), pkg); + assert.equal(isOfficialProvenance(source), false); + }); + + it('ignores an attestation copied from another package', function () { + assert.equal(provenanceSource(makeAttestations(), + {...pkg, name: 'ep_nxs65012'}), null); + }); + + it('ignores an attestation for another version', function () { + assert.equal(provenanceSource(makeAttestations(), {...pkg, version: '11.0.59'}), null); + }); + + it('ignores an attestation whose digest does not match the tarball', function () { + assert.equal(provenanceSource(makeAttestations({digest: 'ab'.repeat(64)}), pkg), null); + assert.equal(provenanceSource(makeAttestations(), {...pkg, integrity: undefined}), null); + }); + + it('ignores attestations that are not SLSA provenance', function () { + assert.equal(provenanceSource( + makeAttestations({predicateType: 'https://example.com/other'}), pkg), null); + }); + + it('survives a garbage payload', function () { + assert.equal(provenanceSource({attestations: [ + {predicateType: SLSA_PROVENANCE_V1, bundle: {dsseEnvelope: {payload: '!!!'}}}, + ]}, pkg), null); + }); + }); + + describe('isPlaceholderPackage', function () { + it('flags 0.0.0 pre-release versions', function () { + assert.equal(isPlaceholderPackage('0.0.0-stage'), true); + assert.equal(isPlaceholderPackage('0.0.0'), true); + }); + it('flags a package npm shows without a repository', function () { + assert.equal(isPlaceholderPackage('1.2.3', false), true); + }); + it('does not flag a real release, or one whose metadata is unknown', function () { + assert.equal(isPlaceholderPackage('0.0.1', true), false); + assert.equal(isPlaceholderPackage('0.0.10'), false); + assert.equal(isPlaceholderPackage('1.2.3', undefined), false); + }); + }); + + describe('hasRepositoryField', function () { + it('accepts the string and object forms', function () { + assert.equal(hasRepositoryField('github:ether/ep_align'), true); + assert.equal(hasRepositoryField({type: 'git', url: 'git+https://x/y.git'}), true); + }); + it('rejects missing or empty repositories', function () { + for (const v of [undefined, null, '', ' ', {}, {url: ''}]) { + assert.equal(hasRepositoryField(v), false, JSON.stringify(v)); + } + }); + }); + + describe('normalizeThirdPartyMode', function () { + it('accepts the documented values in any case', function () { + assert.equal(normalizeThirdPartyMode('hide'), 'hide'); + assert.equal(normalizeThirdPartyMode(' ALL '), 'all'); + assert.equal(normalizeThirdPartyMode('label'), 'label'); + }); + it('falls back to label for anything else', function () { + assert.equal(normalizeThirdPartyMode(undefined), 'label'); + assert.equal(normalizeThirdPartyMode('nope'), 'label'); + assert.equal(normalizeThirdPartyMode(true), 'label'); + }); + }); + + describe('isListedInCatalog', function () { + const official = {name: 'ep_align', official: true, placeholder: false}; + const thirdParty = {name: 'ep_mypads', official: false, placeholder: false}; + const placeholder = {name: 'ep_nxs65012', official: false, placeholder: true}; + + it('label: lists official and third-party, hides placeholders from browsing', function () { + assert.equal(isListedInCatalog(official, 'label'), true); + assert.equal(isListedInCatalog(thirdParty, 'label'), true); + assert.equal(isListedInCatalog(placeholder, 'label'), false); + assert.equal(isListedInCatalog(placeholder, 'label', 'nxs'), false); + }); + + it('label: an exact-name search still finds a placeholder', function () { + assert.equal(isListedInCatalog(placeholder, 'label', 'EP_NXS65012 '), true); + }); + + it('hide: lists official plugins only', function () { + assert.equal(isListedInCatalog(official, 'hide'), true); + assert.equal(isListedInCatalog(thirdParty, 'hide'), false); + assert.equal(isListedInCatalog(placeholder, 'hide', 'ep_nxs65012'), false); + }); + + it('all: lists everything', function () { + assert.equal(isListedInCatalog(placeholder, 'all'), true); + assert.equal(isListedInCatalog(thirdParty, 'all'), true); + }); + }); +}); diff --git a/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts b/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts new file mode 100644 index 00000000000..5be6ad7c7fb --- /dev/null +++ b/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts @@ -0,0 +1,120 @@ +import {expect, Page, test} from "@playwright/test"; +import {loginToAdmin} from "../helper/adminhelper"; + +// The admin catalog labels plugins published by the Etherpad project as +// "Official" and everything else as "Third-party", and asks for confirmation +// before installing a third-party plugin. Which plugin is which is decided on +// the server (pluginTrust.ts, covered by the backend specs); this spec checks +// what the admin sees. The live feed changes daily, so the search results are +// replaced with a fixture on the socket, and `install` events are recorded and +// swallowed so nothing is ever actually installed. Installs carry the +// version the catalog showed, so a label can't cover a different release. + +const NS = '/pluginfw/installer'; +const PREFIX = `42${NS},`; + +const fixture = [ + {name: 'ep_fixture_official', description: 'Official fixture plugin', + version: '1.0.0', time: '2026-11-01', official: true}, + {name: 'ep_fixture_community', description: 'Third-party fixture plugin', + version: '2.0.0', time: '2026-11-02', official: false}, +]; + +// Splits a socket.io event frame for the installer namespace into its +// optional ack id and its [event, ...args] payload. +const parseFrame = (msg: string | Buffer) => { + if (typeof msg !== 'string' || !msg.startsWith(PREFIX)) return null; + const m = /^(\d*)(\[[\s\S]*)$/.exec(msg.slice(PREFIX.length)); + if (!m) return null; + return {ack: m[1], payload: JSON.parse(m[2]) as unknown[]}; +}; + +const useFixtureCatalog = async (page: Page) => { + const installs: string[] = []; + await page.routeWebSocket(/\/socket\.io\//, (ws) => { + const server = ws.connectToServer(); + ws.onMessage((msg) => { + const frame = parseFrame(msg); + if (frame && frame.payload[0] === 'install') { + const req = frame.payload[1] as string | {name: string, version?: string}; + installs.push(typeof req === 'string' ? req : `${req.name}@${req.version}`); + return; + } + server.send(msg); + }); + server.onMessage((msg) => { + const frame = parseFrame(msg); + if (frame && frame.payload[0] === 'results:search') { + const data = frame.payload[1] as {results: unknown[]}; + data.results = fixture; + ws.send(`${PREFIX}${frame.ack}${JSON.stringify(frame.payload)}`); + return; + } + ws.send(msg); + }); + }); + return installs; +}; + +test.describe('Plugin catalog: official and third-party plugins', () => { + let installs: string[]; + + test.beforeEach(async ({page}) => { + installs = await useFixtureCatalog(page); + await loginToAdmin(page, 'admin', 'changeme1'); + await page.goto('http://localhost:9001/admin/plugins'); + await page.waitForSelector('.pm-search-input'); + await expect(page.locator('table tbody tr')).toHaveCount(fixture.length, {timeout: 30000}); + }); + + const row = (page: Page, name: string) => + page.locator('table tbody tr').filter({hasText: name}); + + test('labels official and third-party plugins', async ({page}) => { + await expect(row(page, 'ep_fixture_official').locator('.pm-tag--official')) + .toHaveText('Official'); + await expect(row(page, 'ep_fixture_official').locator('.pm-tag--third-party')) + .toHaveCount(0); + await expect(row(page, 'ep_fixture_community').locator('.pm-tag--third-party')) + .toHaveText('Third-party'); + await expect(row(page, 'ep_fixture_community').locator('.pm-tag--third-party')) + .toHaveAttribute('title', 'Not maintained by the Etherpad project. Plugins run code on your server.'); + }); + + test('installs an official plugin with one click', async ({page}) => { + await row(page, 'ep_fixture_official').getByRole('button', {name: 'Install'}).click(); + await expect(page.getByTestId('third-party-confirm')).toHaveCount(0); + await expect.poll(() => installs).toEqual(['ep_fixture_official@1.0.0']); + }); + + test('asks before installing a third-party plugin, and cancel installs nothing', + async ({page}) => { + await row(page, 'ep_fixture_community').getByRole('button', {name: 'Install'}).click(); + const dialog = page.getByTestId('third-party-confirm'); + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole('heading')).toHaveText('Install a third-party plugin?'); + await expect(dialog).toContainText( + 'ep_fixture_community is not maintained by the Etherpad project'); + await expect(dialog).toContainText('Plugins run code on your server'); + await dialog.getByRole('button', {name: 'Cancel'}).click(); + await expect(dialog).toHaveCount(0); + await expect(row(page, 'ep_fixture_community')).toHaveCount(1); + expect(installs).toEqual([]); + }); + + test('Escape dismisses the confirmation without installing', async ({page}) => { + await row(page, 'ep_fixture_community').getByRole('button', {name: 'Install'}).click(); + await expect(page.getByTestId('third-party-confirm')).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.getByTestId('third-party-confirm')).toHaveCount(0); + expect(installs).toEqual([]); + }); + + test('confirming installs the third-party plugin', async ({page}) => { + await row(page, 'ep_fixture_community').getByRole('button', {name: 'Install'}).click(); + const dialog = page.getByTestId('third-party-confirm'); + await dialog.getByRole('button', {name: 'Install'}).click(); + await expect(dialog).toHaveCount(0); + await expect.poll(() => installs).toEqual(['ep_fixture_community@2.0.0']); + }); +}); diff --git a/src/tests/frontend-new/admin-spec/adminupdateplugins.spec.ts b/src/tests/frontend-new/admin-spec/adminupdateplugins.spec.ts index 9056dc4f22d..deceba9e689 100644 --- a/src/tests/frontend-new/admin-spec/adminupdateplugins.spec.ts +++ b/src/tests/frontend-new/admin-spec/adminupdateplugins.spec.ts @@ -49,6 +49,13 @@ test.describe('Plugins page', ()=> { // Install button is in the last table cell await pluginRow.locator('td').last().locator('button').first().click() + // ep_set_title_on_pad is an official plugin and installs with one + // click, but if npm provenance could not be checked it is shown as + // third-party and the confirmation dialog appears first. + const confirm = page.getByTestId('third-party-confirm') + if (await confirm.waitFor({state: 'visible', timeout: 2000}).then(() => true, () => false)) { + await confirm.locator('.pm-btn-primary').click() + } await page.waitForSelector('.pm-installed') // Installed plugins are now in .pm-installed-row flex items (not a table).