From de9f305e94e019737c18703e4f310e17e73c9f94 Mon Sep 17 00:00:00 2001 From: Tim Schipper Date: Sat, 14 Nov 2026 13:17:50 +0100 Subject: [PATCH 1/4] fix: require publish permission to manage scheduled actions Every admin user could reach the admin routes for publisher actions. So users without the Content Manager publish permission could still schedule, change or delete (un)publish dates (#212). closes #212 --- CLAUDE.md | 4 +- README.md | 6 + package.json | 2 +- playground/scripts/smoke-test.js | 234 ------------------ playground/scripts/smoke-test/index.js | 47 ++++ playground/scripts/smoke-test/lib/app.js | 98 ++++++++ playground/scripts/smoke-test/lib/client.js | 71 ++++++ playground/scripts/smoke-test/lib/config.js | 58 +++++ playground/scripts/smoke-test/lib/fixtures.js | 83 +++++++ .../scripts/smoke-test/tests/endpoints.js | 20 ++ .../scripts/smoke-test/tests/permissions.js | 133 ++++++++++ .../scripts/smoke-test/tests/scheduling.js | 80 ++++++ scripts/consumer-test.js | 4 +- server/index.js | 4 + server/middlewares/index.js | 8 +- .../limit-to-readable-content-types.js | 27 ++ server/policies/can-manage-action.js | 45 ++++ server/policies/index.js | 5 + server/routes/admin/action-routes.js | 8 + server/services/index.js | 2 + server/services/permission-service.js | 84 +++++++ 21 files changed, 782 insertions(+), 241 deletions(-) delete mode 100644 playground/scripts/smoke-test.js create mode 100644 playground/scripts/smoke-test/index.js create mode 100644 playground/scripts/smoke-test/lib/app.js create mode 100644 playground/scripts/smoke-test/lib/client.js create mode 100644 playground/scripts/smoke-test/lib/config.js create mode 100644 playground/scripts/smoke-test/lib/fixtures.js create mode 100644 playground/scripts/smoke-test/tests/endpoints.js create mode 100644 playground/scripts/smoke-test/tests/permissions.js create mode 100644 playground/scripts/smoke-test/tests/scheduling.js create mode 100644 server/middlewares/limit-to-readable-content-types.js create mode 100644 server/policies/can-manage-action.js create mode 100644 server/policies/index.js create mode 100644 server/services/permission-service.js diff --git a/CLAUDE.md b/CLAUDE.md index 9fc6ef6..add485b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ Use **Yarn 4** (`.yarn/releases`, `nodeLinker: node-modules`; a global Yarn 1 de - `yarn playground:strapi ` — run any Strapi CLI command in the playground - `yarn verify` — `strapi-plugin verify`: checks the built package before publishing - `yarn consumer-test --dir [--strapi minimum|current|] [--clean] [--tarball ]` — packs the plugin, creates a fresh Strapi app with its own npm-installed `node_modules` (plugin from the tarball, playground config/content types, `npm install --before` = 7-day cooldown) and runs the smoke test against it; catches packaging, undeclared-dependency and Strapi-version issues the playground can't -- `yarn playground:smoke [--skip-build] [--app ]` — end-to-end smoke test (needs `yarn build`): builds the playground admin, starts it on port 1339 with its own DB (`playground/.tmp/smoke-test.db`) and admin, schedules publish/unpublish actions for Article and Homepage and asserts they run, are removed and call all four hooks +- `yarn playground:smoke [--skip-build] [--app ]` — end-to-end smoke test (needs `yarn build`; `playground/scripts/smoke-test/`, Node's built-in `node:test`): builds the playground admin, starts it once on port 1339 with its own DB (`playground/.tmp/smoke-test.db`) and admin, then runs `tests/endpoints.js`, `tests/scheduling.js` (publish/unpublish actions for Article and Homepage run, are removed and call all four hooks) and `tests/permissions.js` (issue #212: a user without publish permission gets 403s and a filtered list; a non-super-admin who may publish articles can manage article actions but not homepage actions). Shared helpers live in `lib/` (`config`, `app` = build/start/stop, `client` = HTTP, `fixtures`). Test files are required from `index.js` instead of run with `node --test`, so Strapi starts only once. Run part of it with `node --test-reporter=spec --test-name-pattern="Permissions" playground/scripts/smoke-test` There is no unit test suite. CI (`.github/workflows/ci.yml`) runs `yarn install --immutable`, lint, build, `verify`, `npm pack`, the playground smoke test and the consumer test (Node 20 + Strapi minimum, Node 24 + Strapi current) on every PR. The publish workflow uses `npm version`/`npm publish` (Yarn 4 has no `yarn publish`). @@ -43,7 +43,7 @@ Two halves, each built by `@strapi/sdk-plugin` from the entry points in `package ### Server: how a scheduled action flows 1. **Storage** — Each schedule is an `action` document (`server/content-types/action-content-type`, table `actions`, hidden from Content Manager/CTB) with `executeAt`, `mode` (`publish` | `unpublish`), `entityId` (target `documentId`), `entitySlug` (target UID). -2. **API** — Admin and content-api routes both expose CRUD on `/actions` using the core controller (`factories.createCoreController`). Admin also has `GET /settings` returning the plugin config (used by the admin UI for `contentTypes` whitelist and date picker options). +2. **API** — Admin and content-api routes both expose CRUD on `/actions` using the core controller (`factories.createCoreController`). Content-api access is managed by Users & Permissions / API tokens. Admin routes are open to every admin user, so they are restricted to the user's Content Manager permissions on the target content type (issue #212): the policy `plugin::publisher.can-manage-action` (`server/policies`) requires **publish** permission (incl. conditions and the action's locale) for POST/PUT/DELETE, and the route middleware `plugin::publisher.limit-to-readable-content-types` limits GET to content types the user can read. Both use `permissionService`. Admin also has `GET /settings` returning the plugin config (used by the admin UI for `contentTypes` whitelist and date picker options). 3. **Validation before scheduling** — `server/register.js` registers a **Document Service middleware** (`server/middlewares/validate-before-scheduling.js`). On create/update of a `publish` action it loads the target draft (deep-populated) and runs Strapi's entity validator plus a custom required-media/relation/component/dynamic-zone check, throwing a `ValidationError` so the admin can show field errors *at scheduling time* rather than failing silently later. 4. **Scheduling** — `server/services/action-service.js` extends the core service: `create`/`update`/`delete` add/replace/remove a one-off `strapi.cron` job named `publisherAction_` that fires at `executeAt`. On boot, `server/config/cron-tasks.js` (called from `bootstrap`, deferred with `setImmediate`) loads all actions, immediately executes overdue ones, and schedules future ones. The `actions.syncFrequency` config option is still in the defaults/schema but is no longer used by this per-action mechanism. 5. **Execution** — `publicationService.toggle(record, mode)` compares published vs draft versions (publishes if never published or draft is newer; unpublishes if published), then **deletes the action**. `publish`/`unpublish` call the user's `before*` hooks (returning `false` aborts), use `strapi.documents(uid).publish/unpublish`, optionally overwrite `publishedAt` with `executeAt` via `strapi.db.query`, emit `entry.publish`/`entry.unpublish` on the eventHub (`emitService`, so webhooks fire), then call `after*` hooks. Errors are logged, not thrown. diff --git a/README.md b/README.md index 7265b92..d1e3ee5 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,12 @@ Once the plugin has been installed, configured and enabled a `Publisher` section > If the Publisher section does not appear in the admin after the plugin is enabled then a clean rebuild of the admin is required. This can be done by deleting the generated `.cache` and `build` folders and then re-running the `develop` command. +### Permissions + +Scheduling, editing and deleting a (un)publish date requires the same permission as publishing directly: the Content Manager `Publish` permission for that content type (including its conditions and locales) on the user's role. Users without it can't manage scheduled dates through the admin API either, and only see the scheduled dates of content types they are allowed to read. + +The Content API routes (`/api/publisher/actions`) are not affected by this; access to them is managed with the Users & Permissions plugin or API token permissions. + ### Single Content Type ![Sample single content type publisher section](https://github.com/PluginPal/strapi-plugin-publisher/blob/master/assets/single.png?raw=true) diff --git a/package.json b/package.json index 56b0e14..2e7e9c6 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "playground:strapi": "cd playground && strapi", "playground:reset": "node -e \"require('fs').rmSync('playground/.tmp', { recursive: true, force: true })\"", "check:lockfile-age": "node scripts/check-lockfile-age.js", - "playground:smoke": "node playground/scripts/smoke-test.js", + "playground:smoke": "node --test-reporter=spec playground/scripts/smoke-test", "consumer-test": "node scripts/consumer-test.js" }, "exports": { diff --git a/playground/scripts/smoke-test.js b/playground/scripts/smoke-test.js deleted file mode 100644 index 99f252f..0000000 --- a/playground/scripts/smoke-test.js +++ /dev/null @@ -1,234 +0,0 @@ -/** - * End-to-end smoke test for the plugin, run against the playground or another Strapi app. - * - * node playground/scripts/smoke-test.js [--skip-build] [--app ] - * - * Without --app it tests the playground, which needs a built plugin in dist/ (`yarn build`). - * With --app it tests a separate app that has the plugin installed from npm (or a packed - * tarball) and is set up like the playground; see scripts/consumer-test.js. The script: - * 1. builds the app's admin panel with the plugin (skip with --skip-build); - * 2. starts the playground with a fresh, separate database; - * 3. checks the health endpoint, the admin panel and the plugin settings endpoint; - * 4. schedules publish actions for a collection type and a single type, and an unpublish - * action, and waits until the plugin has executed them; - * 5. checks that the executed actions were removed and that all publisher hooks ran. - * - * Environment: - * SMOKE_PORT Port to run the playground on (default 1339) - * - * It never touches your own playground database or admin user (playground/.tmp/data.db). - */ -const fs = require('fs'); -const path = require('path'); -const { spawn, spawnSync } = require('child_process'); - -const repoRoot = path.resolve(__dirname, '..', '..'); -const playgroundDir = path.resolve(__dirname, '..'); -const appArgIndex = process.argv.indexOf('--app'); -const appDir = appArgIndex > -1 ? path.resolve(process.argv[appArgIndex + 1]) : playgroundDir; -const isPlayground = appDir === playgroundDir; -// The playground uses the repository's node_modules; a separate app has its own. -const strapiBin = path.join(isPlayground ? repoRoot : appDir, 'node_modules', '.bin', process.platform === 'win32' ? 'strapi.cmd' : 'strapi'); - -const PORT = Number(process.env.SMOKE_PORT || 1339); -const BASE_URL = `http://127.0.0.1:${PORT}`; -const DATABASE_FILENAME = '.tmp/smoke-test.db'; -// The smoke test uses its own database, so this admin is created on startup by -// playground/src/index.js. Passing it explicitly overrides values in playground/.env. -const ADMIN = { - email: 'smoke-test@playground.test', - password: 'SmokeTest123!', -}; -const ARTICLE_UID = 'api::article.article'; -const HOMEPAGE_UID = 'api::homepage.homepage'; -const ACTION_DELAY_MS = 5000; -const TIMEOUT_MS = 60000; - -const env = { - ...process.env, - HOST: '127.0.0.1', - PORT: String(PORT), - DATABASE_FILENAME, - PLAYGROUND_ADMIN_EMAIL: ADMIN.email, - PLAYGROUND_ADMIN_PASSWORD: ADMIN.password, - STRAPI_TELEMETRY_DISABLED: 'true', -}; - -const step = (message) => console.log(`\n▶ ${message}`); -const ok = (message) => console.log(` ✔ ${message}`); -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - -const assert = (condition, message) => { - if (!condition) { - throw new Error(message); - } -}; - -const waitFor = async (description, check, timeout = TIMEOUT_MS) => { - const deadline = Date.now() + timeout; - let lastError; - while (Date.now() < deadline) { - try { - const result = await check(); - if (result) { - return result; - } - } catch (error) { - lastError = error; - } - await sleep(1000); - } - throw new Error(`Timed out waiting for ${description}${lastError ? ` (${lastError.message})` : ''}`); -}; - -let token; -const api = async (method, url, body) => { - const response = await fetch(`${BASE_URL}${url}`, { - method, - headers: { - 'Content-Type': 'application/json', - ...(token ? { Authorization: `Bearer ${token}` } : {}), - }, - body: body ? JSON.stringify(body) : undefined, - }); - const text = await response.text(); - let json; - try { - json = text ? JSON.parse(text) : null; - } catch { - json = null; - } - if (!response.ok) { - throw new Error(`${method} ${url} returned ${response.status}: ${text.slice(0, 300)}`); - } - return json; -}; - -const scheduleAction = async (mode, entityId, entitySlug) => { - const executeAt = new Date(Date.now() + ACTION_DELAY_MS).toISOString(); - const { data } = await api('POST', '/publisher/actions', { data: { mode, entityId, entitySlug, executeAt } }); - assert(data?.documentId, `Creating a ${mode} action for ${entitySlug} did not return a documentId`); - return data; -}; - -const getArticleStatus = async (documentId) => { - const { results } = await api('GET', `/content-manager/collection-types/${ARTICLE_UID}?pageSize=100`); - return results.find((article) => article.documentId === documentId)?.status; -}; - -const run = async (logs) => { - if (isPlayground) { - assert(fs.existsSync(path.join(repoRoot, 'dist', 'server', 'index.js')), 'The plugin is not built. Run `yarn build` first.'); - } - assert(fs.existsSync(strapiBin), `Strapi is not installed in ${appDir}`); - - fs.rmSync(path.join(appDir, DATABASE_FILENAME), { force: true }); - - if (!process.argv.includes('--skip-build')) { - step(`Building the admin panel of ${isPlayground ? 'the playground' : appDir} with the plugin`); - const build = spawnSync(strapiBin, ['build'], { cwd: appDir, env, stdio: 'inherit' }); - assert(build.status === 0, '`strapi build` failed'); - ok('Admin panel built'); - } - - step(`Starting ${isPlayground ? 'the playground' : appDir} on ${BASE_URL}`); - const strapi = spawn(strapiBin, ['start'], { cwd: appDir, env, detached: process.platform !== 'win32' }); - strapi.stdout.on('data', (chunk) => logs.push(chunk.toString())); - strapi.stderr.on('data', (chunk) => logs.push(chunk.toString())); - let exited = false; - strapi.on('exit', () => { - exited = true; - }); - - const stop = () => { - if (exited) return; - try { - if (process.platform === 'win32') strapi.kill(); - else process.kill(-strapi.pid, 'SIGTERM'); - } catch { - // already stopped - } - }; - - try { - await waitFor('the health endpoint', async () => { - assert(!exited, 'Strapi exited during startup'); - const response = await fetch(`${BASE_URL}/_health`); - return response.status === 204; - }, 120000); - ok('Health endpoint responds'); - - const admin = await fetch(`${BASE_URL}/admin`); - assert(admin.ok && (await admin.text()).includes(' entry.status === 'draft'); - assert(article, 'No draft article found to publish (the playground seed should create one)'); - - const { data: homepage } = await api('GET', `/content-manager/single-types/${HOMEPAGE_UID}`); - assert(homepage?.documentId, 'No homepage draft found (the playground seed should create one)'); - - const articleAction = await scheduleAction('publish', article.documentId, ARTICLE_UID); - const homepageAction = await scheduleAction('publish', homepage.documentId, HOMEPAGE_UID); - ok(`Scheduled article ${article.documentId} and homepage ${homepage.documentId}`); - - await waitFor('the article to be published', async () => (await getArticleStatus(article.documentId)) === 'published'); - ok('Article was published on schedule'); - - await waitFor('the homepage to be published', async () => { - const { data } = await api('GET', `/content-manager/single-types/${HOMEPAGE_UID}?status=published`); - return Boolean(data?.publishedAt); - }); - ok('Homepage (single type) was published on schedule'); - - const { data: remaining } = await api('GET', '/publisher/actions'); - const leftOver = remaining.filter((action) => [articleAction.documentId, homepageAction.documentId].includes(action.documentId)); - assert(leftOver.length === 0, 'Executed publish actions were not removed'); - ok('Executed actions were removed'); - - step('Scheduling an unpublish action'); - await scheduleAction('unpublish', article.documentId, ARTICLE_UID); - await waitFor('the article to be unpublished', async () => (await getArticleStatus(article.documentId)) === 'draft'); - ok('Article was unpublished on schedule'); - - step('Checking that the publisher hooks ran'); - // afterUnpublish runs just after the status change, so give the log line a moment to arrive. - const hooks = ['beforePublish', 'afterPublish', 'beforeUnpublish', 'afterUnpublish']; - const missingHooks = () => hooks.filter((hook) => !logs.join('').includes(`[playground] ${hook}`)); - try { - await waitFor('the publisher hooks to log', () => missingHooks().length === 0, 10000); - } catch { - throw new Error(`These hooks did not run: ${missingHooks().join(', ')}`); - } - ok('beforePublish, afterPublish, beforeUnpublish and afterUnpublish ran'); - } finally { - stop(); - } -}; - -const logs = []; -run(logs) - .then(() => { - console.log('\n✅ Smoke test passed'); - process.exit(0); - }) - .catch((error) => { - console.error(`\n❌ Smoke test failed: ${error.message}`); - if (logs.length) { - console.error('\n--- Strapi output ---'); - console.error(logs.join('').split('\n').slice(-80).join('\n')); - } - process.exit(1); - }); diff --git a/playground/scripts/smoke-test/index.js b/playground/scripts/smoke-test/index.js new file mode 100644 index 0000000..69f8906 --- /dev/null +++ b/playground/scripts/smoke-test/index.js @@ -0,0 +1,47 @@ +/** + * End-to-end smoke test for the plugin, run against the playground or another Strapi app. + * + * node --test-reporter=spec playground/scripts/smoke-test [--skip-build] [--app ] + * (or `yarn playground:smoke`; add --test-name-pattern="Permissions" to run part of it) + * + * Without --app it tests the playground, which needs a built plugin in dist/ (`yarn build`). + * With --app it tests a separate app that has the plugin installed from npm (or a packed + * tarball) and is set up like the playground; see scripts/consumer-test.js. + * + * Before the tests it builds the app's admin panel (skip with --skip-build) and starts the app + * once, with a fresh, separate database. The tests use node:test and live in tests/: + * - endpoints: the admin panel and the plugin settings endpoint; + * - scheduling: publish and unpublish actions for a collection type and a single type run on + * schedule, are removed and call all publisher hooks; + * - permissions: admin users can only manage actions of content types they may publish, and + * only see actions of content types they may read (issue #212). + * + * The test files are loaded here rather than run with `node --test`, which would start a separate + * process, and so a separate Strapi app, for every file. + * + * Environment: + * SMOKE_PORT Port to run the app on (default 1339) + * + * It never touches your own playground database or admin user (playground/.tmp/data.db). + */ +const { before, after } = require('node:test'); +const app = require('./lib/app'); +const { loginAsAdmin } = require('./lib/client'); + +before(async () => { + app.checkPrerequisites(); + app.buildAdmin(); + await app.start(); + await loginAsAdmin(); +}); + +after(() => app.stop()); + +// node:test sets a failing exit code once all tests have run; show what Strapi logged. +process.on('exit', (code) => { + if (code !== 0) app.printLogs(); +}); + +require('./tests/endpoints'); +require('./tests/scheduling'); +require('./tests/permissions'); diff --git a/playground/scripts/smoke-test/lib/app.js b/playground/scripts/smoke-test/lib/app.js new file mode 100644 index 0000000..3c12ca1 --- /dev/null +++ b/playground/scripts/smoke-test/lib/app.js @@ -0,0 +1,98 @@ +/** + * Builds, starts and stops the Strapi app under test, and keeps its output for when a test fails. + */ +const fs = require('fs'); +const path = require('path'); +const { spawn, spawnSync } = require('child_process'); +const config = require('./config'); +const { waitFor } = require('./client'); + +const logs = []; +let strapi; +let exited = false; + +const progress = (message) => console.log(`▶ ${message}`); + +const checkPrerequisites = () => { + if ( + config.isPlayground && + !fs.existsSync(path.join(config.repoRoot, 'dist', 'server', 'index.js')) + ) { + throw new Error('The plugin is not built. Run `yarn build` first.'); + } + if (!fs.existsSync(config.strapiBin)) { + throw new Error(`Strapi is not installed in ${config.appDir}`); + } +}; + +const buildAdmin = () => { + if (config.skipBuild) { + // `strapi develop` empties the admin build folder and serves the admin from Vite instead. + if (!fs.existsSync(path.join(config.appDir, 'build', 'index.html'))) { + throw new Error( + `The admin panel of ${config.appName} is not built (\`strapi develop\` removes build/). Run without --skip-build.` + ); + } + return; + } + + progress(`Building the admin panel of ${config.appName} with the plugin`); + const build = spawnSync(config.strapiBin, ['build'], { + cwd: config.appDir, + env: config.env, + stdio: 'inherit', + }); + if (build.status !== 0) { + throw new Error('`strapi build` failed'); + } +}; + +/** Starts the app with a fresh, separate database and waits until it responds. */ +const start = async () => { + fs.rmSync(path.join(config.appDir, config.DATABASE_FILENAME), { force: true }); + + progress(`Starting ${config.appName} on ${config.BASE_URL}`); + strapi = spawn(config.strapiBin, ['start'], { + cwd: config.appDir, + env: config.env, + detached: process.platform !== 'win32', + }); + strapi.stdout.on('data', (chunk) => logs.push(chunk.toString())); + strapi.stderr.on('data', (chunk) => logs.push(chunk.toString())); + strapi.on('exit', () => { + exited = true; + }); + + await waitFor( + 'the health endpoint', + async () => { + if (exited) { + throw new Error('Strapi exited during startup'); + } + const response = await fetch(`${config.BASE_URL}/_health`); + return response.status === 204; + }, + 120000 + ); +}; + +const stop = () => { + if (!strapi || exited) return; + try { + if (process.platform === 'win32') strapi.kill(); + else process.kill(-strapi.pid, 'SIGTERM'); + } catch { + // already stopped + } +}; + +/** Everything Strapi has written to stdout and stderr so far. */ +const getLogs = () => logs.join(''); + +const printLogs = () => { + if (!logs.length) return; + console.error('\n--- Strapi output ---'); + console.error(getLogs().split('\n').slice(-80).join('\n')); +}; + +module.exports = { checkPrerequisites, buildAdmin, start, stop, getLogs, printLogs }; diff --git a/playground/scripts/smoke-test/lib/client.js b/playground/scripts/smoke-test/lib/client.js new file mode 100644 index 0000000..49c2ca8 --- /dev/null +++ b/playground/scripts/smoke-test/lib/client.js @@ -0,0 +1,71 @@ +/** + * HTTP helpers for the Strapi app under test. Requests use the super admin's token unless another + * token is passed. + */ +const { BASE_URL, ADMIN } = require('./config'); + +const TIMEOUT_MS = 60000; + +let adminToken; + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Calls `check` every second until it returns something truthy, and returns that. */ +const waitFor = async (description, check, timeout = TIMEOUT_MS) => { + const deadline = Date.now() + timeout; + let lastError; + while (Date.now() < deadline) { + try { + const result = await check(); + if (result) { + return result; + } + } catch (error) { + lastError = error; + } + await sleep(1000); + } + throw new Error( + `Timed out waiting for ${description}${lastError ? ` (${lastError.message})` : ''}` + ); +}; + +/** Sends a request and returns the status and body, whatever the status is. */ +const request = async (method, url, body, token = adminToken) => { + const response = await fetch(`${BASE_URL}${url}`, { + method, + headers: { + 'Content-Type': 'application/json', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body ? JSON.stringify(body) : undefined, + }); + const text = await response.text(); + let json; + try { + json = text ? JSON.parse(text) : null; + } catch { + json = null; + } + return { status: response.status, ok: response.ok, json, text }; +}; + +/** Sends a request that must succeed and returns the JSON body. */ +const api = async (method, url, body, token) => { + const { ok, status, json, text } = await request(method, url, body, token); + if (!ok) { + throw new Error(`${method} ${url} returned ${status}: ${text.slice(0, 300)}`); + } + return json; +}; + +/** Logs in as the smoke test's super admin; later requests use this token by default. */ +const loginAsAdmin = async () => { + const login = await api('POST', '/admin/login', ADMIN); + adminToken = login?.data?.token; + if (!adminToken) { + throw new Error(`Logging in as ${ADMIN.email} did not return a token`); + } +}; + +module.exports = { waitFor, request, api, loginAsAdmin }; diff --git a/playground/scripts/smoke-test/lib/config.js b/playground/scripts/smoke-test/lib/config.js new file mode 100644 index 0000000..410f9c8 --- /dev/null +++ b/playground/scripts/smoke-test/lib/config.js @@ -0,0 +1,58 @@ +/** + * Settings of the smoke test: which app it runs against, on which port, and the users it uses. + */ +const path = require('path'); + +const repoRoot = path.resolve(__dirname, '..', '..', '..', '..'); +const playgroundDir = path.join(repoRoot, 'playground'); +const appArgIndex = process.argv.indexOf('--app'); +const appDir = appArgIndex > -1 ? path.resolve(process.argv[appArgIndex + 1]) : playgroundDir; +const isPlayground = appDir === playgroundDir; + +const PORT = Number(process.env.SMOKE_PORT || 1339); +const DATABASE_FILENAME = '.tmp/smoke-test.db'; + +// The smoke test uses its own database, so this admin is created on startup by +// playground/src/index.js. Passing it explicitly overrides values in playground/.env. +const ADMIN = { + email: 'smoke-test@playground.test', + password: 'SmokeTest123!', +}; + +module.exports = { + repoRoot, + appDir, + isPlayground, + appName: isPlayground ? 'the playground' : appDir, + skipBuild: process.argv.includes('--skip-build'), + // The playground uses the repository's node_modules; a separate app has its own. + strapiBin: path.join( + isPlayground ? repoRoot : appDir, + 'node_modules', + '.bin', + process.platform === 'win32' ? 'strapi.cmd' : 'strapi' + ), + BASE_URL: `http://127.0.0.1:${PORT}`, + DATABASE_FILENAME, + ADMIN, + // Created by the permission tests to check users who aren't super admins (issue #212). + NO_PUBLISH_USER: { + email: 'smoke-test-no-publish@playground.test', + password: 'SmokeTestNoPublish123!', + }, + PUBLISHER_USER: { + email: 'smoke-test-publisher@playground.test', + password: 'SmokeTestPublisher123!', + }, + ARTICLE_UID: 'api::article.article', + HOMEPAGE_UID: 'api::homepage.homepage', + env: { + ...process.env, + HOST: '127.0.0.1', + PORT: String(PORT), + DATABASE_FILENAME, + PLAYGROUND_ADMIN_EMAIL: ADMIN.email, + PLAYGROUND_ADMIN_PASSWORD: ADMIN.password, + STRAPI_TELEMETRY_DISABLED: 'true', + }, +}; diff --git a/playground/scripts/smoke-test/lib/fixtures.js b/playground/scripts/smoke-test/lib/fixtures.js new file mode 100644 index 0000000..ab533d0 --- /dev/null +++ b/playground/scripts/smoke-test/lib/fixtures.js @@ -0,0 +1,83 @@ +/** + * Test data: entries seeded by playground/src/index.js, scheduled actions and limited admin users. + */ +const assert = require('node:assert/strict'); +const { ARTICLE_UID, HOMEPAGE_UID } = require('./config'); +const { api } = require('./client'); + +/** A date far in the future, so the action doesn't run during the test. */ +const futureExecuteAt = () => new Date(Date.now() + 60 * 60 * 1000).toISOString(); + +/** Request body for POST /publisher/actions, executed after `delayMs` (default: far in the future). */ +const actionData = (mode, entityId, entitySlug, delayMs) => ({ + data: { + mode, + entityId, + entitySlug, + executeAt: + delayMs === undefined ? futureExecuteAt() : new Date(Date.now() + delayMs).toISOString(), + }, +}); + +const getArticles = async () => { + const { results } = await api( + 'GET', + `/content-manager/collection-types/${ARTICLE_UID}?pageSize=100` + ); + return results; +}; + +const getDraftArticle = async () => { + const article = (await getArticles()).find((entry) => entry.status === 'draft'); + assert.ok(article, 'No draft article found (the playground seed should create one)'); + return article; +}; + +const getArticleStatus = async (documentId) => + (await getArticles()).find((article) => article.documentId === documentId)?.status; + +const getHomepage = async () => { + const { data: homepage } = await api('GET', `/content-manager/single-types/${HOMEPAGE_UID}`); + assert.ok(homepage?.documentId, 'No homepage found (the playground seed should create one)'); + return homepage; +}; + +/** + * Creates and registers an admin user with a new role that has the given Content Manager actions + * on articles only, and returns their token. + */ +const createArticleUser = async ({ email, password }, roleName, actions) => { + const { data: role } = await api('POST', '/admin/roles', { + name: roleName, + description: 'Smoke test', + }); + await api('PUT', `/admin/roles/${role.id}/permissions`, { + permissions: actions.map((action) => ({ + action: `plugin::content-manager.explorer.${action}`, + subject: ARTICLE_UID, + properties: action === 'publish' ? {} : { fields: ['title', 'content'] }, + conditions: [], + })), + }); + const { data: user } = await api('POST', '/admin/users', { + email, + firstname: 'Smoke', + lastname: 'Test', + roles: [role.id], + }); + const { data: registration } = await api('POST', '/admin/register', { + registrationToken: user.registrationToken, + userInfo: { firstname: 'Smoke', lastname: 'Test', password }, + }); + assert.ok(registration?.token, `Registering ${email} did not return a token`); + return registration.token; +}; + +module.exports = { + futureExecuteAt, + actionData, + getDraftArticle, + getArticleStatus, + getHomepage, + createArticleUser, +}; diff --git a/playground/scripts/smoke-test/tests/endpoints.js b/playground/scripts/smoke-test/tests/endpoints.js new file mode 100644 index 0000000..f69a431 --- /dev/null +++ b/playground/scripts/smoke-test/tests/endpoints.js @@ -0,0 +1,20 @@ +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); +const { BASE_URL } = require('../lib/config'); +const { api } = require('../lib/client'); + +describe('Endpoints', () => { + it('serves the admin panel', async () => { + const response = await fetch(`${BASE_URL}/admin`); + assert.ok(response.ok, `GET /admin returned ${response.status}`); + assert.match(await response.text(), /