Repository navigation
feat(agent): let a service renew its own registration token #5674
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+487
−11
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d0c2cf1
feat(agent): let a service renew its own registration token
kojiwakayama 25e81eb
test(agent): use shimmed FakeTime import and schema test setup
kojiwakayama b545899
fix(agent): honor token lifetime and caller aborts in token renewal
kojiwakayama 32b3758
refactor(agent): reuse awaitAbortable for token waits
kojiwakayama cec94cc
fix(agent): bound token responses and document client-credential regi…
kojiwakayama 7ddc563
docs(agent): keep the API key registration sentence the guide contrac…
kojiwakayama File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,263 @@ | ||
| import "#veryfront/schemas/_test-setup.ts"; | ||
| import { assert, assertEquals, assertRejects } from "#veryfront/testing/assert.ts"; | ||
| import { describe, it } from "#veryfront/testing/bdd.ts"; | ||
| import { FakeTime } from "#std/testing/time"; | ||
| import { createClientCredentialsFetch } from "./registration-credentials.ts"; | ||
| import { | ||
| createAgentServiceRegistrationLifecycle, | ||
| resolveAgentServiceRegistrationInput, | ||
| } from "./registration.ts"; | ||
|
|
||
| const credentials = { clientId: "agent", clientSecret: "secret-value" }; | ||
| const API = "https://api.example.com"; | ||
|
|
||
| function jwtExpiringIn(seconds: number, id: string): string { | ||
| const claims = btoa(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + seconds, jti: id })); | ||
| return `h.${claims.replace(/=+$/, "")}.s`; | ||
| } | ||
|
|
||
| function fakeApi(options: { refuse?: (token: string) => boolean; tokenStatus?: number } = {}) { | ||
| const state = { issued: [] as string[], used: [] as string[], tokenInits: [] as RequestInit[] }; | ||
| const fetch: typeof globalThis.fetch = (input, init) => { | ||
| if (input.toString().endsWith("/auth/token")) { | ||
| state.tokenInits.push(init as RequestInit); | ||
| if (options.tokenStatus) { | ||
| return Promise.resolve(new Response("no", { status: options.tokenStatus })); | ||
| } | ||
| const token = jwtExpiringIn(900, String(state.issued.length)); | ||
| state.issued.push(token); | ||
| return Promise.resolve(Response.json({ access_token: token })); | ||
| } | ||
| const token = new Headers((init as RequestInit).headers).get("Authorization")!.slice(7); | ||
| state.used.push(token); | ||
| return Promise.resolve( | ||
| new Response("{}", { status: options.refuse?.(token) ? 401 : 200 }), | ||
| ); | ||
| }; | ||
| return { | ||
| state, | ||
| fetch, | ||
| client: createClientCredentialsFetch({ apiUrl: API, credentials, fetch }), | ||
| }; | ||
| } | ||
|
|
||
| describe("agent/service/registration-credentials", () => { | ||
| it("reuses one token, and sends the secret only to the token endpoint", async () => { | ||
| const { state, client } = fakeApi(); | ||
| await client(`${API}/a`, { method: "POST" }); | ||
| await client(`${API}/b`, { method: "POST" }); | ||
| assertEquals(state.issued.length, 1); | ||
| assertEquals(state.used, [state.issued[0], state.issued[0]]); | ||
| assertEquals(state.tokenInits[0]?.redirect, "error"); | ||
| assertEquals(JSON.parse(String(state.tokenInits[0]?.body)), { | ||
| grant_type: "client_credentials", | ||
| client_id: "agent", | ||
| client_secret: "secret-value", | ||
| }); | ||
| }); | ||
|
|
||
| it("renews before the token expires", async () => { | ||
| using time = new FakeTime(); | ||
| const { state, client } = fakeApi(); | ||
| await client(`${API}/a`); | ||
| await time.tickAsync(839_000); | ||
| await client(`${API}/a`); | ||
| assertEquals(state.issued.length, 1); | ||
| await time.tickAsync(2_000); | ||
| await client(`${API}/a`); | ||
| assertEquals(state.issued.length, 2); | ||
| }); | ||
|
|
||
| it("renews an opaque token before the lifetime the API states", async () => { | ||
| using time = new FakeTime(); | ||
| let issued = 0; | ||
| const client = createClientCredentialsFetch({ | ||
| apiUrl: API, | ||
| credentials, | ||
| fetch: (input) => | ||
| Promise.resolve( | ||
| input.toString().endsWith("/auth/token") | ||
| ? Response.json({ access_token: `opaque-${++issued}`, expires_in: 120 }) | ||
| : new Response("{}"), | ||
| ), | ||
| }); | ||
| await client(`${API}/a`); | ||
| await time.tickAsync(59_000); | ||
| await client(`${API}/a`); | ||
| assertEquals(issued, 1); | ||
| await time.tickAsync(2_000); | ||
| await client(`${API}/a`); | ||
| assertEquals(issued, 2); | ||
| }); | ||
|
|
||
| it("stops waiting for a token when the caller aborts", async () => { | ||
| let answer: ((response: Response) => void) | undefined; | ||
| const client = createClientCredentialsFetch({ | ||
| apiUrl: API, | ||
| credentials, | ||
| fetch: (input) => | ||
| input.toString().endsWith("/auth/token") | ||
| ? new Promise((resolve) => (answer = resolve)) | ||
| : Promise.resolve(new Response("{}")), | ||
| }); | ||
| const controller = new AbortController(); | ||
| const waiting = client(`${API}/a`, { signal: controller.signal }); | ||
| controller.abort(new Error("stopped")); | ||
| const error = await assertRejects(() => waiting); | ||
| assertEquals((error as Error).message, "stopped"); | ||
| // The shared request still completes and serves the next caller. | ||
| answer!(Response.json({ access_token: "late" })); | ||
| assertEquals((await client(`${API}/b`)).status, 200); | ||
| }); | ||
|
|
||
| it("refuses an oversized token response or token", async () => { | ||
| for ( | ||
| const body of [ | ||
| JSON.stringify({ access_token: "a", pad: "x".repeat(200 * 1024) }), | ||
| JSON.stringify({ access_token: "a".repeat(70 * 1024) }), | ||
| ] | ||
| ) { | ||
| const client = createClientCredentialsFetch({ | ||
| apiUrl: API, | ||
| credentials, | ||
| fetch: (input) => | ||
| Promise.resolve( | ||
| input.toString().endsWith("/auth/token") | ||
| ? new Response(body, { headers: { "content-type": "application/json" } }) | ||
| : new Response("{}"), | ||
| ), | ||
| }); | ||
| await assertRejects(() => client(`${API}/a`)); | ||
| } | ||
| }); | ||
|
|
||
| it("renews once when the API refuses the token", async () => { | ||
| let first: string | undefined; | ||
| const { state, client } = fakeApi({ refuse: (token) => token === (first ??= token) }); | ||
| assertEquals((await client(`${API}/a`)).status, 200); | ||
| assertEquals(state.issued.length, 2); | ||
| }); | ||
|
|
||
| it("stops after one renewal when the API keeps refusing", async () => { | ||
| const { state, client } = fakeApi({ refuse: () => true }); | ||
| assertEquals((await client(`${API}/a`)).status, 401); | ||
| assertEquals(state.used.length, 2); | ||
| }); | ||
|
|
||
| it("asks once for concurrent requests", async () => { | ||
| const { state, client } = fakeApi(); | ||
| await Promise.all([client(`${API}/a`), client(`${API}/b`), client(`${API}/c`)]); | ||
| assertEquals(state.issued.length, 1); | ||
| }); | ||
|
|
||
| it("reports a refused login without the secret", async () => { | ||
| const { state, client } = fakeApi({ tokenStatus: 400 }); | ||
| const error = await assertRejects(() => client(`${API}/a`)); | ||
| assert(error instanceof Error); | ||
| assert(error.message.includes("HTTP 400")); | ||
| assert(!error.message.includes("secret-value")); | ||
| assertEquals(state.used.length, 0); | ||
| }); | ||
|
|
||
| it("asks again after a failed token request", async () => { | ||
| let down = true; | ||
| const { fetch } = fakeApi(); | ||
| const client = createClientCredentialsFetch({ | ||
| apiUrl: API, | ||
| credentials, | ||
| fetch: (input, init) => down ? Promise.reject(new TypeError("down")) : fetch(input, init), | ||
| }); | ||
| await assertRejects(() => client(`${API}/a`)); | ||
| down = false; | ||
| assertEquals((await client(`${API}/a`)).status, 200); | ||
| }); | ||
|
|
||
| it("refuses a token response without a usable token", async () => { | ||
| const client = createClientCredentialsFetch({ | ||
| apiUrl: API, | ||
| credentials, | ||
| fetch: () => Promise.resolve(Response.json({ access_token: "a\r\nb" })), | ||
| }); | ||
| await assertRejects(() => client(`${API}/a`)); | ||
| }); | ||
|
|
||
| const config = { | ||
| VERYFRONT_API_URL: API, | ||
| VERYFRONT_AGENT_SERVICE_URL: "https://agent.example.com", | ||
| VERYFRONT_AGENT_SERVICE_REGISTRATION: "enabled" as const, | ||
| VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: 30_000, | ||
| }; | ||
|
|
||
| it("resolves client credentials without a fixed token, and prefers them", async () => { | ||
| const input = await resolveAgentServiceRegistrationInput({ | ||
| config: { | ||
| ...config, | ||
| VERYFRONT_API_TOKEN: "fixed", | ||
| VERYFRONT_AGENT_SERVICE_CLIENT_ID: "agent", | ||
| VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: "secret-value", | ||
| }, | ||
| serviceName: "docs-agent", | ||
| }); | ||
| assertEquals(input?.clientCredentials, credentials); | ||
| assertEquals(input?.authToken, undefined); | ||
| }); | ||
|
|
||
| it("refuses half of the client credentials", async () => { | ||
| for (const half of ["ID", "SECRET"]) { | ||
| await assertRejects(() => | ||
| resolveAgentServiceRegistrationInput({ | ||
| config: { ...config, [`VERYFRONT_AGENT_SERVICE_CLIENT_${half}`]: "x" }, | ||
| serviceName: "docs-agent", | ||
| }) | ||
| ); | ||
| } | ||
| }); | ||
|
|
||
| it("registers and heartbeats with renewed tokens", async () => { | ||
| const used: (string | null)[] = []; | ||
| let issued = 0; | ||
| const service = { | ||
| id: "22222222-2222-4222-8222-222222222222", | ||
| service_name: "docs-agent", | ||
| service_key: "k", | ||
| scope_kind: "global", | ||
| scope_key: "global", | ||
| project_id: null, | ||
| agent_id: null, | ||
| base_url: "https://agent.example.com", | ||
| invoke_url: "https://agent.example.com/api/runs", | ||
| status: "active", | ||
| version: null, | ||
| runtime: null, | ||
| region: null, | ||
| capabilities: null, | ||
| metadata: null, | ||
| last_heartbeat_at: null, | ||
| created_at: "2026-05-13T00:00:00.000Z", | ||
| updated_at: "2026-05-13T00:00:00.000Z", | ||
| }; | ||
| const lifecycle = await createAgentServiceRegistrationLifecycle({ | ||
| apiUrl: API, | ||
| clientCredentials: credentials, | ||
| serviceName: "docs-agent", | ||
| serviceKey: "k", | ||
| scopeKind: "global", | ||
| baseUrl: "https://agent.example.com", | ||
| invokeUrl: "https://agent.example.com/api/runs", | ||
| heartbeatIntervalMs: 60_000, | ||
| fetch: (input, init) => { | ||
| if (input.toString().endsWith("/auth/token")) { | ||
| return Promise.resolve(Response.json({ access_token: `token-${++issued}` })); | ||
| } | ||
| const header = new Headers((init as RequestInit).headers).get("Authorization"); | ||
| used.push(header); | ||
| // The first token is refused at the heartbeat, as after a revocation. | ||
| const refused = input.toString().endsWith("/heartbeat") && header === "Bearer token-1"; | ||
| return Promise.resolve(Response.json({ service }, { status: refused ? 401 : 200 })); | ||
| }, | ||
| }); | ||
| await lifecycle.heartbeat(); | ||
| lifecycle.stop(); | ||
| assertEquals(used, ["Bearer token-1", "Bearer token-1", "Bearer token-2"]); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.