fix(server): renew service keys on the next request and stop sending expired ones

An expired key is no longer sent; the request goes through the shared pool
while a due key, or an expired one within its grace, is renewed in the
background. Refusals in one burst count once, a refused renewal counts like
a refused search, and a Places request whose key is refused is sent once
more without it.
This commit is contained in:
Maurice
2026-10-29 09:13:26 +01:00
committed by Maurice
parent b53751344b
commit 476dbef7dc
6 changed files with 263 additions and 51 deletions
@@ -0,0 +1,36 @@
/**
* RefusalStreak: when the refusals of a key add up to giving it up. Three at
* moments apart do; a burst counts once, and an acceptance starts over.
*/
import { RefusalStreak } from '../../../../src/nest/service-identity/refusal-streak';
import { describe, expect, it } from 'vitest';
const MINUTE = 60_000;
describe('RefusalStreak', () => {
it('SISTREAK-001: completes on the third refusal ten minutes apart, then starts over', () => {
const streak = new RefusalStreak();
expect(streak.hit(0)).toBe(false);
expect(streak.hit(10 * MINUTE)).toBe(false);
expect(streak.hit(20 * MINUTE)).toBe(true);
expect(streak.hit(30 * MINUTE)).toBe(false);
});
it('SISTREAK-002: refusals closer together than ten minutes are one', () => {
const streak = new RefusalStreak();
for (let i = 0; i < 9; i++) expect(streak.hit(i * MINUTE)).toBe(false);
expect(streak.hit(10 * MINUTE)).toBe(false);
expect(streak.hit(20 * MINUTE)).toBe(true);
});
it('SISTREAK-003: an acceptance clears what was counted', () => {
const streak = new RefusalStreak();
streak.hit(0);
streak.hit(10 * MINUTE);
streak.clear();
expect(streak.hit(11 * MINUTE)).toBe(false);
expect(streak.hit(21 * MINUTE)).toBe(false);
expect(streak.hit(31 * MINUTE)).toBe(true);
});
});
@@ -252,14 +252,21 @@ describe('refusals', () => {
return built;
}
const tenMinutesLater = () => vi.setSystemTime(Date.now() + 10 * 60_000);
it('SIKEYS-020: gives the key up only on the third 401 in a row, and asks again within six hours', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const { keys, store, issuer } = await registered();
keys.noteInvalid();
tenMinutesLater();
keys.noteInvalid();
keys.noteAccepted();
tenMinutesLater();
keys.noteInvalid();
tenMinutesLater();
keys.noteInvalid();
expect(store.dropKey).not.toHaveBeenCalled();
tenMinutesLater();
const before = Date.now();
keys.noteInvalid();
await settled(keys);
@@ -306,6 +313,17 @@ describe('refusals', () => {
const off = await build({ config: { mode: 'off' } });
await expect(off.keys.regenerate()).rejects.toMatchObject({ status: 409 });
});
it('SIKEYS-024: the refusals of one page full of searches count once', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const { keys, store } = await registered();
for (let i = 0; i < 6; i++) keys.noteInvalid();
tenMinutesLater();
for (let i = 0; i < 6; i++) keys.noteInvalid();
await settled(keys);
expect(store.dropKey).not.toHaveBeenCalled();
expect(keys.bearer()).toBe(KEY);
});
});
describe('renewal', () => {
@@ -345,12 +363,20 @@ describe('renewal', () => {
expect(issuer.renew).toHaveBeenCalledTimes(1);
});
it('SIKEYS-033: a refused renewal drops the key, a revoked one freezes it, a network failure changes nothing', async () => {
it('SIKEYS-033: a refused renewal counts like a refused search, a revoked one freezes it, a network failure changes nothing', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const refused = fakeIssuer();
refused.renew.mockRejectedValueOnce(new IssuerError(401, null, null));
refused.renew.mockRejectedValue(new IssuerError(401, null, null));
const first = await build({ store: stored(), issuer: refused });
await first.keys.renewIfDue();
await first.keys.renewIfDue();
expect(first.store.dropKey).not.toHaveBeenCalled();
for (let i = 0; i < 2; i++) {
vi.setSystemTime(Date.now() + 10 * 60_000);
await first.keys.renewIfDue();
}
expect(first.store.dropKey).toHaveBeenCalledTimes(1);
vi.useRealTimers();
await t?.close();
const revoked = fakeIssuer();
@@ -390,4 +416,47 @@ describe('renewal', () => {
await keys.renewIfDue();
expect(issuer.renew).not.toHaveBeenCalled();
});
it('SIKEYS-036: a due key is renewed on the next request, not only by the daily check', async () => {
const store = stored();
const { keys, issuer } = await build({ store });
expect(keys.bearer()).toBe(oldKey);
await settled(keys);
expect(issuer.renew).toHaveBeenCalledWith(oldKey);
expect(keys.bearer()).toBe(RENEWED_KEY);
});
it('SIKEYS-037: an expired key within its grace stays home, and the next request renews it', async () => {
const expired = serviceKeyTokenFor({ i: 'installation-a', iat: now() - 95 * DAY, exp: now() - 5 * DAY });
const store = fakeStore({
key: {
token: expired,
kid: 'test',
payload: { i: 'installation-a', iat: now() - 95 * DAY, exp: now() - 5 * DAY, q: 'std' },
},
});
const { keys, issuer } = await build({ store });
expect(keys.bearer()).toBeNull();
await settled(keys);
expect(issuer.renew).toHaveBeenCalledWith(expired);
expect(issuer.register).not.toHaveBeenCalled();
expect(keys.bearer()).toBe(RENEWED_KEY);
});
it('SIKEYS-038: after a failed renewal the requests wait for the backoff instead of asking again', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const issuer = fakeIssuer();
issuer.renew.mockRejectedValueOnce(new Error('fetch failed'));
const { keys } = await build({ store: stored(), issuer });
keys.bearer();
await settled(keys);
keys.bearer();
await settled(keys);
expect(issuer.renew).toHaveBeenCalledTimes(1);
vi.setSystemTime(Date.now() + 5 * 60_000);
keys.bearer();
await settled(keys);
expect(issuer.renew).toHaveBeenCalledTimes(2);
expect(keys.bearer()).toBe(RENEWED_KEY);
});
});
@@ -504,6 +504,40 @@ describe('the installation identity', () => {
}
});
it('asks once more through the shared pool when the key is refused, and shows the identity only the refusal', async () => {
const port = {
headersFor: vi.fn(() => ({ 'User-Agent': 'TREK/test', Authorization: 'Bearer installation-key' })),
observe: vi.fn(),
};
serviceIdentitySlot.install(port);
try {
calls = [];
let answered = 0;
vi.stubGlobal(
'fetch',
vi.fn(async (url: URL | string, init?: RequestInit) => {
calls.push({ url: String(url), init });
answered += 1;
const status = answered === 1 ? 401 : 200;
return {
ok: status === 200,
status,
body: null,
text: async () => JSON.stringify({ query: 'x', results: [PLACE] }),
} as unknown as Response;
}),
);
await expect(trekPlacesSearch('x')).resolves.toHaveLength(1);
expect(calls).toHaveLength(2);
expect(calls[1].init?.headers).not.toHaveProperty('Authorization');
expect(calls[1].init?.headers).toMatchObject({ 'User-Agent': 'TREK/test' });
expect(port.observe).toHaveBeenCalledTimes(1);
expect(port.observe.mock.calls[0][1]).toMatchObject({ status: 401 });
} finally {
serviceIdentitySlot.release(port);
}
});
it('sends what it always sent while no identity is installed', async () => {
stubFetch({ query: 'x', results: [] });
await trekPlacesSearch('x');