Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/selfhost/redis-token-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,21 @@ export function createRedisTokenCache(redis: Redis): InstallationTokenStore {
1,
Math.floor((value.expiresAtMs - Date.now()) / 1000),
);
await redis.set(
keyFor(installationId),
JSON.stringify(value),
"EX",
ttlSeconds,
);
// Fail open on a connection error, same contract as get() above: the caller (github/app.ts's
// createInstallationToken, right after successfully minting a fresh token) has no try/catch of its own,
// so an uncaught error here would turn an otherwise-successful mint into a hard failure over a transient
// cache-write hiccup. The token was already obtained from GitHub before this call, so a write failure
// just costs one extra real mint next time -- never the caller's job to fail.
try {
await redis.set(
keyFor(installationId),
JSON.stringify(value),
"EX",
ttlSeconds,
);
} catch {
recordTokenCacheMetric("error");
}
},
};
}
28 changes: 28 additions & 0 deletions test/unit/github-app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import type { Advisory } from "../../src/types";
import { createTestEnv } from "../helpers/d1";
import { getInstallation, listLatestGitHubRateLimitObservations, upsertInstallation } from "../../src/db/repositories";
import { clockSkewSecondsSample, resetClockSkewForTest } from "../../src/selfhost/clock-skew";
import { createRedisTokenCache } from "../../src/selfhost/redis-token-cache";
import type { Redis } from "ioredis";

beforeEach(() => {
clearInstallationTokenCacheForTest();
Expand Down Expand Up @@ -2713,6 +2715,32 @@ describe("self-host Redis token store + GitHub GET response cache", () => {
await expect(getAppInstallation(env, 99)).rejects.toThrow();
expect(store.size).toBe(0); // non-200 not cached
});

it("REGRESSION (#6999): a Redis write failure never fails an otherwise-successful token mint", async () => {
// The real createRedisTokenCache implementation (not a hand-rolled store), wired to a Redis stand-in whose
// set() always throws -- pins that the fail-open fix actually reaches createInstallationToken's uncaught
// writeCachedToken call, not just the unit-level contract on redis-token-cache.ts's own set().
const throwingRedis = {
get: async () => null,
set: async () => {
throw new Error("connection refused");
},
} as unknown as Redis;
setInstallationTokenStore(createRedisTokenCache(throwingRedis));
const privateKey = await generatePrivateKeyPem();
vi.stubGlobal("fetch", async (input: RequestInfo | URL) => {
if (input.toString().includes("/access_tokens")) {
return Response.json({
token: "minted-despite-cache-failure",
expires_at: new Date(Date.now() + 60 * 60_000).toISOString(),
});
}
return new Response("not found", { status: 404 });
});

const env = createTestEnv({ GITHUB_APP_PRIVATE_KEY: privateKey });
await expect(createInstallationToken(env, 888)).resolves.toBe("minted-despite-cache-failure");
});
});

describe("GitHub rate-limit handling (#ratelimit-resilience)", () => {
Expand Down
18 changes: 17 additions & 1 deletion test/unit/selfhost-redis-token-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { renderMetrics, resetMetrics } from "../../src/selfhost/metrics";
import { createRedisTokenCache } from "../../src/selfhost/redis-token-cache";

/** Minimal ioredis stand-in that records the TTL passed to set(). */
function fakeRedis(options: { getThrows?: boolean } = {}): {
function fakeRedis(options: { getThrows?: boolean; setThrows?: boolean } = {}): {
redis: Redis;
store: Map<string, string>;
ttl: () => number;
Expand All @@ -17,6 +17,7 @@ function fakeRedis(options: { getThrows?: boolean } = {}): {
return store.get(k) ?? null;
},
async set(k: string, v: string, _ex: "EX", ttl: number) {
if (options.setThrows) throw new Error("connection refused");
store.set(k, v);
lastTtl = ttl;
return "OK";
Expand Down Expand Up @@ -110,4 +111,19 @@ describe("createRedisTokenCache (#perf installation-token persistence)", () => {
'loopover_redis_token_cache_total{result="error"} 1',
);
});

it("regression: set() fails open (does not throw) and records an error metric on a Redis connection failure (#6999)", async () => {
// The token was already successfully minted from GitHub before set() is called (github/app.ts's
// createInstallationToken has no try/catch around this write), so a transient cache-write failure must
// never surface as a token-mint failure -- same fail-open contract as get()'s own regression test above.
const { redis, store } = fakeRedis({ setThrows: true });
await expect(
createRedisTokenCache(redis).set(9, { token: "sensitive-value", expiresAtMs: Date.now() + 60_000 }),
).resolves.toBeUndefined();

expect(store.has("gh:insttoken:9")).toBe(false); // the write never actually landed
const metrics = await renderMetrics();
expect(metrics).toContain('loopover_redis_token_cache_total{result="error"} 1');
expect(metrics).not.toContain("sensitive-value");
});
});
Loading