diff --git a/.github/scripts/check-removed-pages.mjs b/.github/scripts/check-removed-pages.mjs new file mode 100644 index 00000000..3bf99280 --- /dev/null +++ b/.github/scripts/check-removed-pages.mjs @@ -0,0 +1,232 @@ +#!/usr/bin/env node +// Fails when a change removes a page from https://smallstep.com/docs without +// leaving a redirect behind in redirects.json. +// +// A page is served when manifest.json has a route for it and the route's file +// exists. Deleting or renaming the file, or dropping or repointing the route, +// takes the URL away. This script compares the URLs served at the base ref +// with the URLs served by the working tree. +// +// Usage: node .github/scripts/check-removed-pages.mjs [base-ref] +// base-ref defaults to origin/main. + +import { execFileSync } from 'node:child_process' +import { existsSync, readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +export const MANIFEST_FILE = 'manifest.json' +export const REDIRECTS_FILE = 'redirects.json' + +/** + * Converts a manifest route path to its URL. Mirrors convertPathToSlug in + * smallstep.com's lib/next-docs: drop the .mdx extension and README segments. + */ +export function pathToUrl(path) { + const segments = path + .replace(/\.mdx$/, '') + .replace(/^\//, '') + .split('/') + .filter((segment) => segment !== 'README' && segment !== '') + return segments.length ? `/docs/${segments.join('/')}` : '/docs' +} + +/** Strips the query, the fragment and trailing slashes. */ +export function normalizeUrl(url) { + const bare = url.replace(/[?#].*$/, '').replace(/\/+$/, '') + return bare === '' ? '/' : bare +} + +function isDocsUrl(url) { + return url === '/docs' || url.startsWith('/docs/') +} + +/** + * Returns the set of URLs a manifest serves. + * @param {object} manifest - Parsed manifest.json + * @param {(file: string) => boolean} hasFile - Whether a repo-relative file exists + */ +export function liveUrls(manifest, hasFile) { + const urls = new Set() + const walk = (routes) => { + for (const route of routes ?? []) { + if (route.path && hasFile(route.path.replace(/^\//, ''))) { + urls.add(pathToUrl(route.path)) + } + walk(route.routes) + } + } + walk(manifest.routes) + return urls +} + +/** + * Reads the redirect entries out of a parsed redirects.json. + * @returns {{ entries: { from: string, to: string }[], errors: string[] }} + */ +export function parseRedirects(data) { + const errors = [] + const entries = [] + if (!data || !Array.isArray(data.redirects)) { + return { + entries, + errors: [`${REDIRECTS_FILE} must be an object with a "redirects" array.`] + } + } + data.redirects.forEach((entry, index) => { + if (typeof entry?.from !== 'string' || typeof entry?.to !== 'string') { + errors.push( + `${REDIRECTS_FILE}: entry ${index + 1} needs string "from" and "to" fields.` + ) + return + } + entries.push({ from: entry.from, to: entry.to }) + }) + return { entries, errors } +} + +/** + * Compares the base and head states. + * @param {object} state + * @param {Set} state.baseUrls - URLs served at the base ref + * @param {Set} state.headUrls - URLs served by the change + * @param {{ from: string, to: string }[]} state.baseRedirects + * @param {{ from: string, to: string }[]} state.headRedirects + * @returns {string[]} One message per problem; empty when the change is fine + */ +export function check({ baseUrls, headUrls, baseRedirects, headRedirects }) { + const errors = [] + const redirected = new Set() + + for (const { from, to } of headRedirects) { + if (!isDocsUrl(from) || from !== normalizeUrl(from)) { + errors.push( + `${REDIRECTS_FILE}: "from" must be a /docs path with no trailing slash, query or fragment: ${from}` + ) + continue + } + if (redirected.has(from)) { + errors.push(`${REDIRECTS_FILE}: more than one redirect from ${from}`) + continue + } + redirected.add(from) + + if (headUrls.has(from)) { + errors.push( + `${REDIRECTS_FILE}: ${from} is a live page, so its redirect would never apply. Remove the redirect or the page.` + ) + } + + if (to.startsWith('https://')) continue + if (!to.startsWith('/')) { + errors.push( + `${REDIRECTS_FILE}: "to" must be a site path or an https:// URL: ${to} (redirect from ${from})` + ) + continue + } + const target = normalizeUrl(to) + if (isDocsUrl(target) && !headUrls.has(target)) { + errors.push( + `${REDIRECTS_FILE}: ${from} redirects to ${to}, which isn't a live docs page.` + ) + } + } + + for (const url of [...baseUrls].sort()) { + if (!headUrls.has(url) && !redirected.has(url)) { + errors.push( + `${url} is removed by this change and has no redirect. Add { "from": "${url}", "to": "" } to ${REDIRECTS_FILE}, or restore the page.` + ) + } + } + + for (const { from } of baseRedirects) { + if (!redirected.has(from) && !headUrls.has(from)) { + errors.push( + `The redirect from ${from} is removed by this change, and no page is served there. Restore the redirect.` + ) + } + } + + return errors +} + +function git(...args) { + return execFileSync('git', args, { + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024 + }) +} + +function readBaseState(baseRef) { + const base = git('merge-base', baseRef, 'HEAD').trim() + const files = new Set( + git('ls-tree', '-r', '--name-only', '-z', base).split('\0') + ) + const manifest = JSON.parse(git('show', `${base}:${MANIFEST_FILE}`)) + const redirects = files.has(REDIRECTS_FILE) + ? parseRedirects(JSON.parse(git('show', `${base}:${REDIRECTS_FILE}`))) + .entries + : [] + return { + base, + urls: liveUrls(manifest, (file) => files.has(file)), + redirects + } +} + +function readHeadState(root) { + const manifest = JSON.parse( + readFileSync(resolve(root, MANIFEST_FILE), 'utf8') + ) + const redirectsPath = resolve(root, REDIRECTS_FILE) + const redirects = existsSync(redirectsPath) + ? parseRedirects(JSON.parse(readFileSync(redirectsPath, 'utf8'))) + : { entries: [], errors: [] } + return { + urls: liveUrls(manifest, (file) => existsSync(resolve(root, file))), + redirects + } +} + +function main() { + const baseRef = process.argv[2] || 'origin/main' + const root = git('rev-parse', '--show-toplevel').trim() + const base = readBaseState(baseRef) + const head = readHeadState(root) + + const errors = [ + ...head.redirects.errors, + ...check({ + baseUrls: base.urls, + headUrls: head.urls, + baseRedirects: base.redirects, + headRedirects: head.redirects.entries + }) + ] + + if (errors.length === 0) { + console.log( + `No docs pages removed without a redirect (compared with ${base.base.slice(0, 9)}; ${head.urls.size} pages served).` + ) + return + } + + const annotate = process.env.GITHUB_ACTIONS === 'true' + for (const message of errors) { + console.error( + annotate ? `::error file=${REDIRECTS_FILE}::${message}` : `- ${message}` + ) + } + console.error( + `\n${errors.length} problem(s). See "Removing or renaming a page" in CONTRIBUTING.md.` + ) + process.exitCode = 1 +} + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + main() +} diff --git a/.github/scripts/check-removed-pages.test.mjs b/.github/scripts/check-removed-pages.test.mjs new file mode 100644 index 00000000..fcb02688 --- /dev/null +++ b/.github/scripts/check-removed-pages.test.mjs @@ -0,0 +1,155 @@ +import assert from 'node:assert/strict' +import { test } from 'node:test' + +import { + check, + liveUrls, + normalizeUrl, + parseRedirects, + pathToUrl +} from './check-removed-pages.mjs' + +const state = (overrides = {}) => ({ + baseUrls: new Set(['/docs/a', '/docs/b']), + headUrls: new Set(['/docs/a', '/docs/b']), + baseRedirects: [], + headRedirects: [], + ...overrides +}) + +test('pathToUrl drops the extension and README segments', () => { + assert.equal(pathToUrl('/README.mdx'), '/docs') + assert.equal(pathToUrl('/platform/README.mdx'), '/docs/platform') + assert.equal(pathToUrl('/tutorials/wifi.mdx'), '/docs/tutorials/wifi') +}) + +test('normalizeUrl strips the fragment, query and trailing slash', () => { + assert.equal(normalizeUrl('/docs/a/#section'), '/docs/a') + assert.equal(normalizeUrl('/docs/a?x=1'), '/docs/a') + assert.equal(normalizeUrl('/'), '/') +}) + +test('liveUrls needs both a manifest route and its file', () => { + const manifest = { + routes: [ + { title: 'Group', routes: [{ path: '/a.mdx' }, { path: '/gone.mdx' }] }, + { heading: true, title: 'Heading' }, + { path: '/b/README.mdx', routes: [{ path: '/b/c.mdx' }] } + ] + } + const files = new Set(['a.mdx', 'b/README.mdx', 'b/c.mdx', 'unlisted.mdx']) + assert.deepEqual( + [...liveUrls(manifest, (file) => files.has(file))].sort(), + ['/docs/a', '/docs/b', '/docs/b/c'] + ) +}) + +test('parseRedirects rejects a malformed file and malformed entries', () => { + assert.equal(parseRedirects([]).errors.length, 1) + const { entries, errors } = parseRedirects({ + redirects: [{ from: '/docs/a', to: '/docs/b' }, { from: '/docs/c' }] + }) + assert.equal(entries.length, 1) + assert.equal(errors.length, 1) +}) + +test('an unchanged set of pages passes', () => { + assert.deepEqual(check(state()), []) +}) + +test('a removed page without a redirect fails', () => { + const errors = check(state({ headUrls: new Set(['/docs/a']) })) + assert.equal(errors.length, 1) + assert.match(errors[0], /^\/docs\/b is removed/) +}) + +test('a removed page with a redirect passes', () => { + const errors = check( + state({ + headUrls: new Set(['/docs/a']), + headRedirects: [{ from: '/docs/b', to: '/docs/a/#moved' }] + }) + ) + assert.deepEqual(errors, []) +}) + +test('a redirect to a page that is not live fails', () => { + const errors = check( + state({ + headUrls: new Set(['/docs/a']), + headRedirects: [{ from: '/docs/b', to: '/docs/nowhere' }] + }) + ) + assert.equal(errors.length, 1) + assert.match(errors[0], /isn't a live docs page/) +}) + +test('a redirect chain fails because the target is not a live page', () => { + const errors = check( + state({ + baseUrls: new Set(['/docs/a']), + headUrls: new Set(['/docs/a']), + headRedirects: [ + { from: '/docs/x', to: '/docs/y' }, + { from: '/docs/y', to: '/docs/a' } + ] + }) + ) + assert.equal(errors.length, 1) + assert.match(errors[0], /\/docs\/x redirects to \/docs\/y/) +}) + +test('redirects off the docs site are allowed', () => { + const headUrls = new Set(['/docs/a']) + assert.deepEqual( + check( + state({ + headUrls, + headRedirects: [{ from: '/docs/b', to: 'https://example.com/b' }] + }) + ), + [] + ) + assert.deepEqual( + check( + state({ headUrls, headRedirects: [{ from: '/docs/b', to: '/blog/b/' }] }) + ), + [] + ) +}) + +test('a redirect from a live page fails', () => { + const errors = check( + state({ headRedirects: [{ from: '/docs/a', to: '/docs/b' }] }) + ) + assert.equal(errors.length, 1) + assert.match(errors[0], /is a live page/) +}) + +test('a non-canonical or duplicate "from" fails', () => { + const errors = check( + state({ + headRedirects: [ + { from: '/docs/old/', to: '/docs/a' }, + { from: '/blog/old', to: '/docs/a' }, + { from: '/docs/dup', to: '/docs/a' }, + { from: '/docs/dup', to: '/docs/b' } + ] + }) + ) + assert.equal(errors.length, 3) +}) + +test('removing a redirect fails unless a page is served there again', () => { + const baseRedirects = [{ from: '/docs/old', to: '/docs/a' }] + assert.equal(check(state({ baseRedirects })).length, 1) + assert.deepEqual( + check( + state({ + baseRedirects, + headUrls: new Set(['/docs/a', '/docs/b', '/docs/old']) + }) + ), + [] + ) +}) diff --git a/.github/workflows/removed-pages.yml b/.github/workflows/removed-pages.yml new file mode 100644 index 00000000..4b903fee --- /dev/null +++ b/.github/workflows/removed-pages.yml @@ -0,0 +1,25 @@ +name: Check for removed pages + +on: + pull_request: + +permissions: + contents: read + +jobs: + removed-pages: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: '20' + - name: Test the check + run: node --test .github/scripts/check-removed-pages.test.mjs + - name: Check that removed pages have redirects + env: + BASE_REF: ${{ github.base_ref }} + run: node .github/scripts/check-removed-pages.mjs "origin/$BASE_REF" diff --git a/.github/workflows/trigger-algolia-index.yml b/.github/workflows/trigger-algolia-index.yml index c5c9b9eb..fbbf3b69 100644 --- a/.github/workflows/trigger-algolia-index.yml +++ b/.github/workflows/trigger-algolia-index.yml @@ -8,6 +8,7 @@ on: paths: - '**.mdx' - 'manifest.json' + - 'redirects.json' jobs: trigger: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc12afc9..7199c6b9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,6 +39,31 @@ The Practical Zero Trust articles are a bit different. They are templated, rather than freeform Markdown. Look at existing examples in [`src/pzt`](src/pzt) for reference. +## Removing or renaming a page + +A page is served at `https://smallstep.com/docs/...` when `manifest.json` has a route for it and the route's file exists. +Deleting or renaming the file, or removing or changing the route, takes the old URL away. +Other sites, search engines, and the Smallstep product link to these URLs, so every removed URL needs a redirect. + +Add the redirect to [`redirects.json`](redirects.json) in the same pull request: + +```json +{ + "from": "/docs/tutorials/old-page", + "to": "/docs/tutorials/new-page" +} +``` + +- `from` is the old URL, starting with `/docs`, with no trailing slash. +- `to` is a live docs page, another path on smallstep.com, or an `https://` URL. A docs page can include a `#fragment`. +- Don't remove an entry from `redirects.json` unless a page is served at its `from` URL again. + +A pull request check enforces these rules. To run it locally, you need [Node.js](https://nodejs.org/) 20 or later: + +```bash +node .github/scripts/check-removed-pages.mjs +``` + ## Prose linting with vale We use [Vale](https://vale.sh/) to enforce consistent prose style. diff --git a/redirects.json b/redirects.json new file mode 100644 index 00000000..1fdd0050 --- /dev/null +++ b/redirects.json @@ -0,0 +1,80 @@ +{ + "redirects": [ + { + "from": "/docs/tutorials/wifi-setup-guide", + "to": "/docs/tutorials/protect-wireless-networks" + }, + { + "from": "/docs/tutorials/intune-mdm-setup-guide", + "to": "/docs/tutorials/protect-wireless-networks" + }, + { + "from": "/docs/tutorials/apple-mdm-jamf-setup-guide", + "to": "/docs/tutorials/protect-wireless-networks" + }, + { + "from": "/docs/tutorials/wifi-authentication-webhooks", + "to": "/docs/tutorials/protect-wireless-networks" + }, + { + "from": "/docs/tutorials/mutual-tls-aws", + "to": "/docs/mtls" + }, + { + "from": "/docs/tutorials/acme-challenge", + "to": "/docs/tutorials/acme-protocol-acme-clients" + }, + { + "from": "/docs/step-ca/ssh", + "to": "/docs/ssh" + }, + { + "from": "/docs/step-ca/technology/ssh", + "to": "/docs/ssh" + }, + { + "from": "/docs/step-certificates/kubernetes", + "to": "/docs/certificate-manager/kubernetes-tls" + }, + { + "from": "/docs/design-doc.html", + "to": "/docs/design-document" + }, + { + "from": "/docs/cli-installation", + "to": "/docs/step-cli/installation" + }, + { + "from": "/docs/cli/install", + "to": "/docs/step-cli/installation" + }, + { + "from": "/docs/step-cli/i", + "to": "/docs/step-cli/installation" + }, + { + "from": "/docs/step-cli/reference/ca/sign/acme-www", + "to": "/docs/step-cli/reference/ca/sign" + }, + { + "from": "/docs/step-cli/reference/ca/policy/acme/x509/smallstep.com/rss/feed.xml", + "to": "/docs/step-cli/reference/ca/policy/acme/x509" + }, + { + "from": "/docs/platform/smallstep-agent/step-agent.nix", + "to": "/docs/platform/smallstep-agent" + }, + { + "from": "/docs/step-ca/path/to/file.tpl", + "to": "/docs/step-ca/templates" + }, + { + "from": "/docs/tutorials/protect-wired-networks/Device/Vendor/MSFT/WiredNetwork/LanXML", + "to": "/docs/tutorials/protect-wired-networks" + }, + { + "from": "/docs/tutorials/protect-wired-networks/protect-wireless-networks.mdx", + "to": "/docs/tutorials/protect-wireless-networks" + } + ] +}