Skip to content

Commit 3cfb625

Browse files
authored
mail edge function: only authorize backend (#2490)
* Update filters-defaults.ts hotfix * mail edge function: only authorize backend * create a Middleware to ensure the request originates from a trusted backend service. * Update middlewares.ts explicit return
1 parent 150a014 commit 3cfb625

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

supabase/functions/_shared/middlewares.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
import { Context, Next } from "hono";
12
import { NextFunction, Request, Response } from "npm:express";
2-
import { createSupabaseClient } from "./supabase-self-hosted.ts";
3+
import { createSupabaseClient } from "./supabase.ts";
4+
5+
const serviceRoleKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY");
36

47
export async function authorizeUser(
58
req: Request,
@@ -15,3 +18,20 @@ export async function authorizeUser(
1518
res.locals.user = user;
1619
return next();
1720
}
21+
22+
/**
23+
* Middleware to ensure the request originates from a trusted backend service.
24+
*/
25+
export async function verifyServiceRole(c: Context, next: Next) {
26+
const authHeader = c.req.header("authorization");
27+
if (!authHeader) {
28+
return c.json({ error: "Missing authorization header" }, 401);
29+
}
30+
31+
const token = authHeader.split(" ")[1];
32+
if (!token || token !== serviceRoleKey) {
33+
return c.json({ error: "Forbidden" }, 403);
34+
}
35+
36+
return await next();
37+
}

supabase/functions/mail/index.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import { Context, Hono } from "hono";
2+
import { verifyServiceRole } from "../_shared/middlewares.ts";
23
import mailMiningComplete from "./mining-complete/index.ts";
34

45
const functionName = "mail";
56
const app = new Hono().basePath(`/${functionName}`);
67

8+
app.use("*", verifyServiceRole);
9+
710
app.post("/mining-complete", async (c: Context) => {
811
const { miningId } = await c.req.json();
912

@@ -20,6 +23,4 @@ app.post("/mining-complete", async (c: Context) => {
2023
}
2124
});
2225

23-
Deno.serve((req) => {
24-
return app.fetch(req);
25-
});
26+
Deno.serve((req) => app.fetch(req));

0 commit comments

Comments
 (0)