Files
magpie/internal/gui/tests/gateway-key-own-rotate.test.cjs
T
yetone d136d0fe98 gateway-key: rotating a key can give it a value of the user's own (isaac_bai)
isaac_bai on Discord: a gateway key's value is random, and only rotate
changes it, to another random one; they want to set one easy to pass on.
Adding a key could take an own value since 6b6113aa; an existing key
couldn't.

- access: rotate-key takes Change.Secret. Given, it is checked as an
  added key's own value (ownSecret: 8-256 printable ASCII, no space, not
  sk-magpie-, no other key's value; its own current value is allowed);
  empty, magpie makes one as before. The key keeps its id, name, limits,
  models and accounts, and Named counts a request from this computer
  with it as that key.
- ownSecret now refuses a value that is one of the user's provider keys
  (a provider's Key or any of its Keys, constant-time), for add-key too:
  a client sending it would spend that provider directly.
- CLI: `magpie gateway-key rotate <id> --key <value|->`; docs/reference.md.
- GUI (plugins/gateway/keys.js, outside the core budget): the Rotate key
  dialog has a hidden "Your own key (optional)" field; Enter rotates,
  Escape cancels; an own value says "Gateway key changed. Clients that
  send this key reach magpie now." Strings in zh, zh-TW, ja, de.

Tests: TestRotateToOwnValue (bad values refused, old value still works
after a refusal, trimmed own value authenticates as the same key, is
Named, listed masked; empty makes a new key; add-key refuses a provider
key). TestRotatedOwnValueKeepsTheKeysLimit: after rotating to an own
value the old one is 401 from another computer, the own one 200 from
another computer and from 127.0.0.1, and a 700-token day limit stops
the third request from either (429), every record under the key.
gateway-key-own-rotate.test.cjs: chromium and webkit, en/zh/zh-TW/ja/de,
1000 and 400px.

Run (mote): at the pushed head: TestCoreScriptBudget ok, ./internal/access ok, the
own-key/caller-key gateway tests ok. At f37742e14 with this change (no file the rebase touched):
gofmt -l clean; go vet GOOS=linux and windows (./internal/access ./internal/gateway, cli with
-tags nogui on linux) ok; ./internal/cli red on TestEveryRouteHasACommandOrIsNamed only,
/api/context/reply (#5026, 0872bc2a0, the same at main); GUI: gateway-key-own-rotate 20/20,
every gateway-key-*, redact-*, masking-*, privacy-* file and i18n-keys pass.
Broken by hand: the rotate own-value path off made TestRotateToOwnValue and
TestRotatedOwnValueKeepsTheKeysLimit red (401 from another computer); the provider-key check off
made TestRotateToOwnValue red ("accepted upstream-first-key").
Not run: the whole GUI suite (two runs lost: one to another run of this tree, one to mote
rebooting mid-run); it runs after the push. Not tried: a real client on another computer with
the own value, the real app.
2026-11-03 20:17:00 +08:00

78 lines
5.9 KiB
JavaScript

// Rotating a gateway key can give it a value of the user's own in place of
// the one magpie makes (isaac_bai on Discord: one easy to remember and
// pass on), typed hidden, checked as a new key's is; left empty, magpie
// makes one as before.
const assert = require("node:assert/strict");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture, keyAction } = require("./fixtures/caller-keys.cjs");
const words = {
en: { rotate: "Rotate key", own: "Gateway key value", placeholder: "Your own key (optional)", label: "Gateway key", changed: "Gateway key changed. Clients that send this key reach magpie now.", rotated: "Gateway key rotated. Update clients on other computers.", short: "Use a key between 8 and 256 characters" },
zh: { rotate: "轮换密钥", own: "网关密钥的值", placeholder: "自定义密钥(可选)", label: "网关密钥", changed: "网关密钥已修改,发送这个密钥的客户端现在就能连接 magpie。", rotated: "网关密钥已轮换,请更新其他电脑上的客户端。", short: "密钥长度需在 8 到 256 个字符之间" },
"zh-TW": { rotate: "輪換金鑰", own: "閘道金鑰的值", placeholder: "自定義金鑰(可選)", label: "閘道金鑰", changed: "閘道金鑰已修改,傳送這個金鑰的用戶端現在就能連線 magpie。", rotated: "閘道金鑰已輪換,請更新其他電腦上的用戶端。", short: "金鑰長度需在 8 到 256 個字元之間" },
ja: { rotate: "キーを再発行", own: "ゲートウェイキーの値", placeholder: "独自のキー(任意)", label: "ゲートウェイキー", changed: "ゲートウェイキーを変更しました。このキーを送るクライアントはそのまま magpie に接続できます。", rotated: "ゲートウェイキーを更新しました。他のコンピュータのクライアントを更新してください。", short: "キーは 8〜256 文字にしてください" },
de: { rotate: "Schlüssel erneuern", own: "Wert des Zugangsschlüssels", placeholder: "Eigener Schlüssel (optional)", label: "Zugangsschlüssel", changed: "Zugangsschlüssel geändert. Clients, die diesen Schlüssel senden, erreichen magpie jetzt.", rotated: "Zugangsschlüssel erneuert. Aktualisieren Sie die Clients auf anderen Computern.", short: "Der Schlüssel muss 8 bis 256 Zeichen lang sein" },
};
const said = (page, m) => page.waitForFunction((m) => document.body.textContent.includes(m), m);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
for (const width of [1000, 400]) {
test(`${engine} ${lang} ${width}px: rotate a gateway key to a value of one's own`, async (t) => {
const w = words[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const events = [], errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, "light", events, { lan: true }));
await page.goto("http://magpie.test/?view=gateway");
const row = page.locator('#gatewayKeys .acc[data-key="laptop"]');
await row.waitFor();
await keyAction(page, row, w.rotate);
const modal = page.locator("#modal");
const own = modal.locator('input[type="password"]');
await own.waitFor();
assert.equal(await own.getAttribute("placeholder"), w.placeholder);
assert.equal(await own.getAttribute("aria-label"), w.own);
assert.equal(await modal.locator(".editor .ebody > label").textContent(), w.label);
// the field fits the dialog, wide enough to type in, at either width
const box = await own.boundingBox(), dlg = await modal.locator(".editor").boundingBox();
assert(box.width >= 140, `field ${box.width}px wide`);
assert(box.x >= dlg.x && box.x + box.width <= dlg.x + dlg.width + 0.5, "field inside the dialog");
// a short value is refused and the dialog stays, with what was typed
await own.fill("short");
await own.press("Enter");
await said(page, w.short);
assert(await modal.isVisible(), "the dialog stays");
assert.equal(await own.inputValue(), "short");
assert.equal(events.filter((e) => e.action === "rotate-key").length, 1);
await own.fill("family-easy-to-share");
await modal.getByRole("button", { name: w.rotate, exact: true }).click();
await modal.waitFor({ state: "hidden" });
assert.deepEqual(events.filter((e) => e.action === "rotate-key").at(-1).body, { key: "laptop", secret: "family-easy-to-share" });
await said(page, w.changed);
await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="laptop"]')?.textContent.includes("…hare"));
assert.doesNotMatch(await page.locator("#gatewayKeys").textContent(), /family-easy/);
// the next rotation starts empty: magpie makes the key
await keyAction(page, row, w.rotate);
assert.equal(await own.inputValue(), "");
await modal.getByRole("button", { name: w.rotate, exact: true }).click();
await modal.waitFor({ state: "hidden" });
assert.deepEqual(events.filter((e) => e.action === "rotate-key").at(-1).body, { key: "laptop" });
await said(page, w.rotated);
// Remove asks with no field
await row.locator(".gw-key-more").click();
await page.locator(".row-menu [role=menuitem]").last().click();
await modal.locator(".editor").waitFor();
assert.equal(await modal.locator("input").count(), 0);
assert.deepEqual(errors, []);
});
}
}
}