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
1 change: 1 addition & 0 deletions supabase/functions/ai/debate-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { UNTRUSTED_CONTENT_RULES } from "../_shared/prompts.ts";

const environment = {
SUPABASE_URL: "https://supabase.test",
SUPABASE_ANON_KEY: "test-anon-key",
SUPABASE_SERVICE_ROLE_KEY: "test-service-role-key",
SPARRING_INTEGRITY_SECRET: "test-sparring-secret",
EXA_API_KEY: "test-exa-key",
Expand Down
1 change: 1 addition & 0 deletions supabase/functions/ai/generate-honesty_test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const environment = {
SUPABASE_URL: "https://supabase.test",
SUPABASE_ANON_KEY: "test-anon-key",
SUPABASE_SERVICE_ROLE_KEY: "test-service-role-key",
EXA_API_KEY: "test-exa-key",
OPENROUTER_API_KEY: "test-openrouter-key",
Expand Down
46 changes: 46 additions & 0 deletions supabase/functions/ai/handler-research.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ function jsonResponse(body: unknown, status = 200): Response {

const environment = {
SUPABASE_URL: "https://supabase.test",
SUPABASE_ANON_KEY: "test-anon-key",
SUPABASE_SERVICE_ROLE_KEY: "test-service-role-key",
SPARRING_INTEGRITY_SECRET: "test-sparring-secret",
EXA_API_KEY: "test-exa-key",
Expand Down Expand Up @@ -123,6 +124,51 @@ Deno.test("AI handlers reject malformed controls before quota or provider work",
}
});

Deno.test("AI handler rejects missing, empty, and invalid bearer tokens with the shared auth errors", async () => {
const originalFetch = globalThis.fetch;
const calls: string[] = [];

globalThis.fetch = (async (input: Request | URL | string) => {
const url = new URL(input instanceof Request ? input.url : String(input));
calls.push(url.href);
if (url.origin === "https://supabase.test" && url.pathname === "/auth/v1/user") {
return jsonResponse({ code: 401, msg: "invalid JWT" }, 401);
}
throw new Error(`Rejected auth reached unexpected work: ${url}`);
}) as typeof fetch;

const send = (authorization?: string) =>
handleRequest(new Request("http://127.0.0.1/functions/v1/ai", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(authorization === undefined ? {} : { Authorization: authorization }),
},
body: JSON.stringify({
feature: "ask",
model: "openai/gpt-5.6-luna",
input: { message: "Question", mode: "general" },
}),
}));

try {
for (const [label, authorization, expectedError, expectedCalls] of [
["missing header", undefined, "Authentication required", 0],
["empty bearer token", "Bearer ", "Authentication required", 0],
["rejected token", "Bearer expired-token", "Invalid authentication token", 1],
] as const) {
calls.length = 0;
const response = await send(authorization);
if (response.status !== 401) throw new Error(`${label} returned ${response.status}`);
const body = await response.json() as { error?: unknown };
if (body.error !== expectedError) throw new Error(`${label} returned error ${JSON.stringify(body.error)}`);
if (calls.length !== expectedCalls) throw new Error(`${label} made remote calls: ${calls.join(", ")}`);
}
} finally {
globalThis.fetch = originalFetch;
}
});

Deno.test("factoids handler carries Exa filters and consulted-source metadata across the request boundary", async () => {
const originalFetch = globalThis.fetch;
const exaSearchBodies: Array<Record<string, unknown>> = [];
Expand Down
27 changes: 8 additions & 19 deletions supabase/functions/ai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
type ResearchContext,
type ResearchDeps,
} from "../_shared/research.ts";
import { HttpError, jsonError, requireUser } from "../_shared/auth.ts";
import { getCorsHeaders } from "../_shared/cors.ts";
import {
checkRateLimit,
Expand Down Expand Up @@ -274,26 +275,14 @@ export async function handleRequest(req: Request): Promise<Response> {
// Require a valid user session for all AI requests.
// The frontend already enforces auth; this protects the endpoint even when
// gateway JWT verification is disabled.
const authHeader = req.headers.get("authorization");
if (!authHeader?.startsWith("Bearer ")) {
log(requestId, "WARN", "Missing authorization header");
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 401,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}

const token = authHeader.slice(7);
const { data: { user }, error: authError } = await supabase.auth.getUser(token);
if (authError || !user) {
log(requestId, "WARN", "Auth token validation failed", { error: authError?.message });
return new Response(JSON.stringify({ error: "Invalid token" }), {
status: 401,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
let userId: string;
try {
userId = (await requireUser(req)).user.id;
} catch (error) {
if (!(error instanceof HttpError)) throw error;
log(requestId, "WARN", "Authentication rejected", { error: error.message });
return jsonError(error, corsHeaders);
}

const userId: string = user.id;
log(requestId, "INFO", "User authenticated", { userId });

if (debateContextRequest) {
Expand Down
1 change: 1 addition & 0 deletions supabase/functions/ai/voice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

const environment = {
SUPABASE_URL: "https://supabase.test",
SUPABASE_ANON_KEY: "test-anon-key",
SUPABASE_SERVICE_ROLE_KEY: "test-service-role-key",
SPARRING_INTEGRITY_SECRET: "test-sparring-secret",
OPENROUTER_API_KEY: "test-openrouter-key",
Expand Down
Loading