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
20 changes: 19 additions & 1 deletion docs/guides/agent-service-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ HTTP 200 SSE responses. Error responses omit it.
`VERYFRONT_PROJECT_ID` or `VERYFRONT_PROJECT_SLUG`, and a publicly
reachable `VERYFRONT_AGENT_SERVICE_URL`. See
[Configuration](./configuration.md) for the full list.
- For an installation whose API gives the service its own login: set
`VERYFRONT_AGENT_SERVICE_CLIENT_ID` and
`VERYFRONT_AGENT_SERVICE_CLIENT_SECRET` instead of a key or token.
- Immutable deployment metadata for `runtimeSource` when the control plane
invokes the service.
- An immutable deployment artifact tag when release qualification needs the
Expand Down Expand Up @@ -147,7 +150,12 @@ For non-standard project layouts, configure discovery paths in

Control-plane registration is convention-first. In `auto` mode, the service
registers only when `VERYFRONT_API_KEY` and
`VERYFRONT_AGENT_SERVICE_URL` are present. Leave `VERYFRONT_API_TOKEN_FILE`
`VERYFRONT_AGENT_SERVICE_URL` are present, or when `VERYFRONT_AGENT_SERVICE_URL`
and both `VERYFRONT_AGENT_SERVICE_CLIENT_ID` and
`VERYFRONT_AGENT_SERVICE_CLIENT_SECRET` are present. With the client ID and
secret, the service gets its own token from `/auth/token`, renews it before it
expires, and ignores `VERYFRONT_API_KEY`. Setting only one of the two is a
startup error. Leave `VERYFRONT_API_TOKEN_FILE`
unset: when it is set, even to an empty value, the service does not read
`VERYFRONT_API_KEY`, so `auto` mode skips registration and `enabled` mode fails
at startup. Registration also requires the immutable `runtimeSource` binding
Expand All @@ -161,6 +169,16 @@ VERYFRONT_AGENT_SERVICE_URL=https://agent.example.com
VERYFRONT_AGENT_SERVICE_REGISTRATION=auto
```

With the service's own login instead of a key:

```bash
VERYFRONT_API_URL=https://api.example.com
VERYFRONT_AGENT_SERVICE_CLIENT_ID=<CLIENT_ID>
VERYFRONT_AGENT_SERVICE_CLIENT_SECRET=<CLIENT_SECRET>
VERYFRONT_AGENT_SERVICE_URL=https://agent.example.com
VERYFRONT_AGENT_SERVICE_REGISTRATION=auto
```

When an agent service keeps control-plane traffic on an internal HTTP service
URL, set `VERYFRONT_PUBLIC_API_BASE_URL` to the environment's HTTPS API origin.
Run-scoped inference credentials use that public origin for provider gateway
Expand Down
4 changes: 3 additions & 1 deletion docs/guides/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,9 @@ Common groups:
- **Agent services**: `VERYFRONT_AGENT_SERVICE_NAME`,
`VERYFRONT_AGENT_SERVICE_URL`, `VERYFRONT_AGENT_SERVICE_KEY`,
`VERYFRONT_AGENT_SERVICE_REGISTRATION`, and
`VERYFRONT_AGENT_SERVICE_REGION`.
`VERYFRONT_AGENT_SERVICE_REGION`. Set `VERYFRONT_AGENT_SERVICE_CLIENT_ID` and
`VERYFRONT_AGENT_SERVICE_CLIENT_SECRET` together to let the service obtain and
renew its own registration token.
Comment thread
kojiwakayama marked this conversation as resolved.
Resolved
- **Provider keys**: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY`,
and provider-specific base URLs.
- **Runtime**: `PORT`, `NODE_ENV`, `REDIS_URL` (backs the SSR transform cache,
Expand Down
11 changes: 11 additions & 0 deletions src/agent/service/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@ describe("agent/agent-service-config", () => {
assertEquals(config.VERYFRONT_MCP_URL, "https://api.example.com/mcp");
});

it("reads the registration client credentials, blank as unset", () => {
const set = parseHostedAgentServiceConfig({
VERYFRONT_AGENT_SERVICE_CLIENT_ID: "agent",
VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: "secret",
});
assertEquals(set.VERYFRONT_AGENT_SERVICE_CLIENT_ID, "agent");
assertEquals(set.VERYFRONT_AGENT_SERVICE_CLIENT_SECRET, "secret");
const blank = parseHostedAgentServiceConfig({ VERYFRONT_AGENT_SERVICE_CLIENT_ID: " " });
assertEquals(blank.VERYFRONT_AGENT_SERVICE_CLIENT_ID, undefined);
});

it("builds agent service config defaults", () => {
const config = parseHostedAgentServiceConfig({});

Expand Down
6 changes: 6 additions & 0 deletions src/agent/service/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export type AgentServiceConfig = {
VERYFRONT_PROJECT_ID?: string;
VERYFRONT_AGENT_SERVICE_URL?: string;
VERYFRONT_AGENT_SERVICE_KEY?: string;
VERYFRONT_AGENT_SERVICE_CLIENT_ID?: string;
VERYFRONT_AGENT_SERVICE_CLIENT_SECRET?: string;
VERYFRONT_AGENT_SERVICE_REGISTRATION: AgentServiceRegistrationMode;
VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: number;
VERYFRONT_AGENT_SERVICE_REGION?: string;
Expand Down Expand Up @@ -95,6 +97,8 @@ const getAgentServiceConfigSchema = defineSchema<AgentServiceConfig>((v) => {
VERYFRONT_PROJECT_ID: v.string().min(1).optional(),
VERYFRONT_AGENT_SERVICE_URL: v.string().url().optional(),
VERYFRONT_AGENT_SERVICE_KEY: v.string().min(1).max(128).optional(),
VERYFRONT_AGENT_SERVICE_CLIENT_ID: v.string().optional(),
VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: v.string().optional(),
VERYFRONT_AGENT_SERVICE_REGISTRATION: agentServiceRegistrationModeInputSchema,
VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS: v.coerce.number().positive().default(30_000),
VERYFRONT_AGENT_SERVICE_REGION: v.string().min(1).max(128).optional(),
Expand Down Expand Up @@ -148,6 +152,8 @@ const getAgentServiceConfigSchema = defineSchema<AgentServiceConfig>((v) => {
VERYFRONT_PROJECT_ID: env.VERYFRONT_PROJECT_ID,
VERYFRONT_AGENT_SERVICE_URL: env.VERYFRONT_AGENT_SERVICE_URL,
VERYFRONT_AGENT_SERVICE_KEY: env.VERYFRONT_AGENT_SERVICE_KEY,
VERYFRONT_AGENT_SERVICE_CLIENT_ID: present(env.VERYFRONT_AGENT_SERVICE_CLIENT_ID),
VERYFRONT_AGENT_SERVICE_CLIENT_SECRET: present(env.VERYFRONT_AGENT_SERVICE_CLIENT_SECRET),
VERYFRONT_AGENT_SERVICE_REGISTRATION: env.VERYFRONT_AGENT_SERVICE_REGISTRATION,
VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS:
env.VERYFRONT_AGENT_SERVICE_HEARTBEAT_INTERVAL_MS,
Expand Down
263 changes: 263 additions & 0 deletions src/agent/service/registration-credentials.test.ts
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"]);
});
});
Loading
Loading