model-request-security.test.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { describe, expect, it, vi } from "vitest";
  2. import { generateText } from "ai";
  3. import { AiSdkModelExecution } from "../src/model/model-execution.js";
  4. import type { ModelRequestSecurityState } from "../src/model/request-security.js";
  5. describe("model request security boundary", () => {
  6. it("creates one execution scope and passes final model requests through the injected port", async () => {
  7. const wrapped = vi.fn<typeof fetch>(async (input, init) => {
  8. const request = new Request(input, init);
  9. expect(new URL(request.url).pathname).toBe("/v1/chat/completions");
  10. expect((await request.json()).model).toBe("example-model");
  11. return Response.json({
  12. id: "example",
  13. object: "chat.completion",
  14. created: 1,
  15. model: "example-model",
  16. choices: [
  17. { index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" },
  18. ],
  19. usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
  20. });
  21. });
  22. const protectTransport = vi.fn(() => wrapped);
  23. const take = vi.fn(() => []);
  24. const createExecution = vi.fn(() => ({ protectTransport, take }));
  25. const state: ModelRequestSecurityState = { createExecution };
  26. const execution = new AiSdkModelExecution({}, { requestSecurityState: state });
  27. const bound = execution.bindModel({
  28. providerId: "example",
  29. modelId: "example-model",
  30. supportsJsonSchemaOutput: false,
  31. optionSpecs: { reasoningLevel: { map: "{}" }, maxOutputTokens: { map: "{}" } },
  32. providerConfig: {
  33. api: { type: "openai-chat-completions", baseUrl: "https://provider.example.test/v1" },
  34. access: { type: "api-key", apiKey: "example-key" },
  35. },
  36. });
  37. const resolved = bound.resolveRequest({
  38. options: { reasoningLevel: "disabled", maxOutputTokens: 32 },
  39. });
  40. expect((await generateText({ model: resolved.model, prompt: "hello" })).text).toBe("ok");
  41. expect(createExecution).toHaveBeenCalledOnce();
  42. expect(protectTransport).toHaveBeenCalledWith(
  43. expect.objectContaining({
  44. providerId: "example",
  45. providerConfig: expect.objectContaining({ apiKey: "example-key" }),
  46. }),
  47. );
  48. expect(wrapped).toHaveBeenCalledOnce();
  49. expect(resolved.requestObservations).toBe(createExecution.mock.results[0]?.value);
  50. });
  51. });