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
73 changes: 71 additions & 2 deletions backend/routes/feedback.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
from fastapi import APIRouter
import logging
import uuid

from db.connection import table
import httpx
from fastapi import APIRouter, File, HTTPException, Request, UploadFile

from db.connection import SUPABASE_KEY, SUPABASE_URL, table
from models import SubmitFeedbackBody, SubmitIssueReportBody
from services.auth_guard import get_session_user_id
from services.request_limits import read_within_limit

logger = logging.getLogger(__name__)

router = APIRouter()

# #231: issue-report screenshots upload here. They used to be written by the
# frontend with the public anon key; this endpoint moves the write server-side
# (service role) so the bucket can be made private.
ISSUE_BUCKET = "issues-media-files"
MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024 # 5 MB
ALLOWED_SCREENSHOT_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}


@router.post("/feedback")
def submit_feedback(body: SubmitFeedbackBody):
Expand All@@ -29,3 +44,57 @@ def submit_issue_report(body: SubmitIssueReportBody):
"screenshot_urls": body.screenshot_urls,
})
return {"ok": True}


@router.post("/issue-reports/screenshot")
async def upload_issue_screenshot(request: Request, file: UploadFile = File(...)):
"""Auth-gated, server-side upload for issue-report screenshots (#231).

Replaces the frontend's direct anon-key upload to issues-media-files so the
bucket can be made private (Phase 2b). Validates type + size (the #220/#229
pattern), uploads with the service role, and returns the storage PATH (not a
public URL); the path is stored in issue_reports.screenshot_urls and reviewed
via the dashboard / a signed URL.
"""
user_id = get_session_user_id(request) # 401 if unauthenticated
if (file.content_type or "") not in ALLOWED_SCREENSHOT_TYPES:
raise HTTPException(
status_code=415,
detail="Unsupported image type. Allowed: PNG, JPEG, WEBP, GIF.",
)
content = await read_within_limit(file, MAX_SCREENSHOT_BYTES) # 413 if oversize
if not content:
raise HTTPException(status_code=400, detail="Empty file.")
ext = (
file.filename.rsplit(".", 1)[-1]
if file.filename and "." in file.filename
else "png"
)
path = f"{user_id}/{uuid.uuid4()}.{ext}"
url = f"{SUPABASE_URL}/storage/v1/object/{ISSUE_BUCKET}/{path}"
r = httpx.put(
url,
content=content,
headers={
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": file.content_type or "application/octet-stream",
},
timeout=30.0,
)
if r.status_code not in (200, 201):
# Surface the real Supabase response so the failure is debuggable
# without server access (mirrors storage_service.upload_avatar). We
# only show the truncated upstream body — never the URL or headers
# (the latter contains the service-role key).
body_text = (r.text or "").strip()[:500]
logger.warning(
"upload_issue_screenshot: Supabase storage rejected upload "
"user=%s status=%d body=%s",
user_id, r.status_code, body_text,
)
raise HTTPException(
status_code=502,
detail=f"Screenshot upload failed (Supabase {r.status_code}): {body_text or 'no body'}",
)
return {"path": path}
75 changes: 75 additions & 0 deletions backend/tests/test_issue_screenshot_auth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
"""
Regression tests for #231 Phase 2a: POST /api/issue-reports/screenshot.

This endpoint moves issue-report screenshot uploads off the frontend's public
anon-key storage client and onto an auth-gated, service-role backend upload so
the issues-media-files bucket can be made private. The negative tests assert it
requires auth (401) and bounds type (415) / size (413); all fail on pre-fix code
(the endpoint didn't exist → 404).
"""
from unittest.mock import patch

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def _png(nbytes: int = 16):
return {"file": ("shot.png", b"\x89PNG\r\n\x1a\n" + b"0" * nbytes, "image/png")}


class TestIssueScreenshotUpload:
def test_unauthenticated_returns_401(self):
from services import auth_guard

with patch("routes.feedback.get_session_user_id", auth_guard._real_get_session_user_id), \
patch.object(auth_guard, "_decode_session", auth_guard._real_decode_session):
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 401

def test_wrong_content_type_returns_415(self):
with patch("routes.feedback.httpx") as hx:
r = client.post(
"/api/issue-reports/screenshot",
files={"file": ("notes.txt", b"hello", "text/plain")},
)
assert r.status_code == 415
hx.put.assert_not_called()

def test_oversize_returns_413(self, monkeypatch):
monkeypatch.setattr("routes.feedback.MAX_SCREENSHOT_BYTES", 100)
with patch("routes.feedback.httpx") as hx:
r = client.post("/api/issue-reports/screenshot", files=_png(nbytes=200))
assert r.status_code == 413
hx.put.assert_not_called()

def test_valid_upload_returns_path_scoped_to_user(self):
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 200
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 200
path = r.json()["path"]
# Path is scoped under the authenticated user_id (conftest stub: user_andres).
assert path.startswith("user_andres/")
assert path.endswith(".png")
hx.put.assert_called_once()

def test_supabase_failure_returns_502_not_500(self):
# When Supabase Storage rejects the upload (e.g. bucket missing /
# RLS denied), the endpoint maps it to a 502 with the truncated
# upstream body — never a generic 500. (#231 review fix.)
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 404
hx.put.return_value.text = '{"statusCode":"404","error":"Bucket not found"}'
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 502
detail = r.json()["detail"]
# Upstream status + body are surfaced for debuggability...
assert "404" in detail
assert "Bucket not found" in detail
# ...but the service-role key (in headers) and upload URL must not leak.
assert "Authorization" not in detail
assert "storage/v1/object" not in detail
hx.put.assert_called_once()
27 changes: 16 additions & 11 deletions frontend/src/components/ReportIssueFlow.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,13 +6,11 @@ import { Pill } from "./Pill";
import { useToast } from "./ToastProvider";
import { useUser } from "@/context/UserContext";
import { useBodyScrollLock } from "@/lib/useBodyScrollLock";
import { supabase } from "@/lib/supabase";
import { submitIssueReport, IS_LOCAL_MODE } from "@/lib/api";
import { submitIssueReport, IS_LOCAL_MODE, API_URL } from "@/lib/api";

const TOPICS = ["Bug", "Feature", "Polish", "Content", "Other"] as const;
type Topic = typeof TOPICS[number];

const BUCKET = "issues-media-files";
const MAX_SCREENSHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;

Expand All@@ -21,14 +19,21 @@ interface ReportIssueFlowProps {
onClose: () => void;
}

async function uploadScreenshot(userId: string, file: File): Promise<string> {
// #231: upload via the auth-gated backend endpoint (service-role) instead of the
// public anon storage client, so issues-media-files can be made private. Returns
// the storage path (stored in screenshot_urls), not a public URL.
async function uploadScreenshot(file: File): Promise<string> {
if (IS_LOCAL_MODE) return URL.createObjectURL(file);
const ext = file.name.split(".").pop() || "png";
const path = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const { error } = await supabase.storage.from(BUCKET).upload(path, file, { cacheControl: "3600", upsert: false });
if (error) throw error;
const { data } = supabase.storage.from(BUCKET).getPublicUrl(path);
return data.publicUrl;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_URL}/api/issue-reports/screenshot`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) throw new Error(`Screenshot upload failed (${res.status})`);
const data = (await res.json()) as { path: string };
return data.path;
}

export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
Expand DownExpand Up@@ -93,7 +98,7 @@ export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
setSubmitting(true);
try {
const urls = await Promise.all(
screenshots.map(s => uploadScreenshot(userId, s.file).catch(err => {
screenshots.map(s => uploadScreenshot(s.file).catch(err => {
toast.error(`Screenshot upload failed: ${err?.message || "unknown"}`);
return null;
})),
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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
73 changes: 71 additions & 2 deletions backend/routes/feedback.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
from fastapi import APIRouter
import logging
import uuid

from db.connection import table
import httpx
from fastapi import APIRouter, File, HTTPException, Request, UploadFile

from db.connection import SUPABASE_KEY, SUPABASE_URL, table
from models import SubmitFeedbackBody, SubmitIssueReportBody
from services.auth_guard import get_session_user_id
from services.request_limits import read_within_limit

logger = logging.getLogger(__name__)

router = APIRouter()

# #231: issue-report screenshots upload here. They used to be written by the
# frontend with the public anon key; this endpoint moves the write server-side
# (service role) so the bucket can be made private.
ISSUE_BUCKET = "issues-media-files"
MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024 # 5 MB
ALLOWED_SCREENSHOT_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}


@router.post("/feedback")
def submit_feedback(body: SubmitFeedbackBody):
Expand All@@ -29,3 +44,57 @@ def submit_issue_report(body: SubmitIssueReportBody):
"screenshot_urls": body.screenshot_urls,
})
return {"ok": True}


@router.post("/issue-reports/screenshot")
async def upload_issue_screenshot(request: Request, file: UploadFile = File(...)):
"""Auth-gated, server-side upload for issue-report screenshots (#231).

Replaces the frontend's direct anon-key upload to issues-media-files so the
bucket can be made private (Phase 2b). Validates type + size (the #220/#229
pattern), uploads with the service role, and returns the storage PATH (not a
public URL); the path is stored in issue_reports.screenshot_urls and reviewed
via the dashboard / a signed URL.
"""
user_id = get_session_user_id(request) # 401 if unauthenticated
if (file.content_type or "") not in ALLOWED_SCREENSHOT_TYPES:
raise HTTPException(
status_code=415,
detail="Unsupported image type. Allowed: PNG, JPEG, WEBP, GIF.",
)
content = await read_within_limit(file, MAX_SCREENSHOT_BYTES) # 413 if oversize
if not content:
raise HTTPException(status_code=400, detail="Empty file.")
ext = (
file.filename.rsplit(".", 1)[-1]
if file.filename and "." in file.filename
else "png"
)
path = f"{user_id}/{uuid.uuid4()}.{ext}"
url = f"{SUPABASE_URL}/storage/v1/object/{ISSUE_BUCKET}/{path}"
r = httpx.put(
url,
content=content,
headers={
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": file.content_type or "application/octet-stream",
},
timeout=30.0,
)
if r.status_code not in (200, 201):
# Surface the real Supabase response so the failure is debuggable
# without server access (mirrors storage_service.upload_avatar). We
# only show the truncated upstream body — never the URL or headers
# (the latter contains the service-role key).
body_text = (r.text or "").strip()[:500]
logger.warning(
"upload_issue_screenshot: Supabase storage rejected upload "
"user=%s status=%d body=%s",
user_id, r.status_code, body_text,
)
raise HTTPException(
status_code=502,
detail=f"Screenshot upload failed (Supabase {r.status_code}): {body_text or 'no body'}",
)
return {"path": path}
75 changes: 75 additions & 0 deletions backend/tests/test_issue_screenshot_auth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
"""
Regression tests for #231 Phase 2a: POST /api/issue-reports/screenshot.

This endpoint moves issue-report screenshot uploads off the frontend's public
anon-key storage client and onto an auth-gated, service-role backend upload so
the issues-media-files bucket can be made private. The negative tests assert it
requires auth (401) and bounds type (415) / size (413); all fail on pre-fix code
(the endpoint didn't exist → 404).
"""
from unittest.mock import patch

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def _png(nbytes: int = 16):
return {"file": ("shot.png", b"\x89PNG\r\n\x1a\n" + b"0" * nbytes, "image/png")}


class TestIssueScreenshotUpload:
def test_unauthenticated_returns_401(self):
from services import auth_guard

with patch("routes.feedback.get_session_user_id", auth_guard._real_get_session_user_id), \
patch.object(auth_guard, "_decode_session", auth_guard._real_decode_session):
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 401

def test_wrong_content_type_returns_415(self):
with patch("routes.feedback.httpx") as hx:
r = client.post(
"/api/issue-reports/screenshot",
files={"file": ("notes.txt", b"hello", "text/plain")},
)
assert r.status_code == 415
hx.put.assert_not_called()

def test_oversize_returns_413(self, monkeypatch):
monkeypatch.setattr("routes.feedback.MAX_SCREENSHOT_BYTES", 100)
with patch("routes.feedback.httpx") as hx:
r = client.post("/api/issue-reports/screenshot", files=_png(nbytes=200))
assert r.status_code == 413
hx.put.assert_not_called()

def test_valid_upload_returns_path_scoped_to_user(self):
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 200
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 200
path = r.json()["path"]
# Path is scoped under the authenticated user_id (conftest stub: user_andres).
assert path.startswith("user_andres/")
assert path.endswith(".png")
hx.put.assert_called_once()

def test_supabase_failure_returns_502_not_500(self):
# When Supabase Storage rejects the upload (e.g. bucket missing /
# RLS denied), the endpoint maps it to a 502 with the truncated
# upstream body — never a generic 500. (#231 review fix.)
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 404
hx.put.return_value.text = '{"statusCode":"404","error":"Bucket not found"}'
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 502
detail = r.json()["detail"]
# Upstream status + body are surfaced for debuggability...
assert "404" in detail
assert "Bucket not found" in detail
# ...but the service-role key (in headers) and upload URL must not leak.
assert "Authorization" not in detail
assert "storage/v1/object" not in detail
hx.put.assert_called_once()
27 changes: 16 additions & 11 deletions frontend/src/components/ReportIssueFlow.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,13 +6,11 @@ import { Pill } from "./Pill";
import { useToast } from "./ToastProvider";
import { useUser } from "@/context/UserContext";
import { useBodyScrollLock } from "@/lib/useBodyScrollLock";
import { supabase } from "@/lib/supabase";
import { submitIssueReport, IS_LOCAL_MODE } from "@/lib/api";
import { submitIssueReport, IS_LOCAL_MODE, API_URL } from "@/lib/api";

const TOPICS = ["Bug", "Feature", "Polish", "Content", "Other"] as const;
type Topic = typeof TOPICS[number];

const BUCKET = "issues-media-files";
const MAX_SCREENSHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;

Expand All@@ -21,14 +19,21 @@ interface ReportIssueFlowProps {
onClose: () => void;
}

async function uploadScreenshot(userId: string, file: File): Promise<string> {
// #231: upload via the auth-gated backend endpoint (service-role) instead of the
// public anon storage client, so issues-media-files can be made private. Returns
// the storage path (stored in screenshot_urls), not a public URL.
async function uploadScreenshot(file: File): Promise<string> {
if (IS_LOCAL_MODE) return URL.createObjectURL(file);
const ext = file.name.split(".").pop() || "png";
const path = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const { error } = await supabase.storage.from(BUCKET).upload(path, file, { cacheControl: "3600", upsert: false });
if (error) throw error;
const { data } = supabase.storage.from(BUCKET).getPublicUrl(path);
return data.publicUrl;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_URL}/api/issue-reports/screenshot`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) throw new Error(`Screenshot upload failed (${res.status})`);
const data = (await res.json()) as { path: string };
return data.path;
}

export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
Expand DownExpand Up@@ -93,7 +98,7 @@ export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
setSubmitting(true);
try {
const urls = await Promise.all(
screenshots.map(s => uploadScreenshot(userId, s.file).catch(err => {
screenshots.map(s => uploadScreenshot(s.file).catch(err => {
toast.error(`Screenshot upload failed: ${err?.message || "unknown"}`);
return null;
})),
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
73 changes: 71 additions & 2 deletions backend/routes/feedback.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
from fastapi import APIRouter
import logging
import uuid

from db.connection import table
import httpx
from fastapi import APIRouter, File, HTTPException, Request, UploadFile

from db.connection import SUPABASE_KEY, SUPABASE_URL, table
from models import SubmitFeedbackBody, SubmitIssueReportBody
from services.auth_guard import get_session_user_id
from services.request_limits import read_within_limit

logger = logging.getLogger(__name__)

router = APIRouter()

# #231: issue-report screenshots upload here. They used to be written by the
# frontend with the public anon key; this endpoint moves the write server-side
# (service role) so the bucket can be made private.
ISSUE_BUCKET = "issues-media-files"
MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024 # 5 MB
ALLOWED_SCREENSHOT_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}


@router.post("/feedback")
def submit_feedback(body: SubmitFeedbackBody):
Expand All@@ -29,3 +44,57 @@ def submit_issue_report(body: SubmitIssueReportBody):
"screenshot_urls": body.screenshot_urls,
})
return {"ok": True}


@router.post("/issue-reports/screenshot")
async def upload_issue_screenshot(request: Request, file: UploadFile = File(...)):
"""Auth-gated, server-side upload for issue-report screenshots (#231).

Replaces the frontend's direct anon-key upload to issues-media-files so the
bucket can be made private (Phase 2b). Validates type + size (the #220/#229
pattern), uploads with the service role, and returns the storage PATH (not a
public URL); the path is stored in issue_reports.screenshot_urls and reviewed
via the dashboard / a signed URL.
"""
user_id = get_session_user_id(request) # 401 if unauthenticated
if (file.content_type or "") not in ALLOWED_SCREENSHOT_TYPES:
raise HTTPException(
status_code=415,
detail="Unsupported image type. Allowed: PNG, JPEG, WEBP, GIF.",
)
content = await read_within_limit(file, MAX_SCREENSHOT_BYTES) # 413 if oversize
if not content:
raise HTTPException(status_code=400, detail="Empty file.")
ext = (
file.filename.rsplit(".", 1)[-1]
if file.filename and "." in file.filename
else "png"
)
path = f"{user_id}/{uuid.uuid4()}.{ext}"
url = f"{SUPABASE_URL}/storage/v1/object/{ISSUE_BUCKET}/{path}"
r = httpx.put(
url,
content=content,
headers={
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": file.content_type or "application/octet-stream",
},
timeout=30.0,
)
if r.status_code not in (200, 201):
# Surface the real Supabase response so the failure is debuggable
# without server access (mirrors storage_service.upload_avatar). We
# only show the truncated upstream body — never the URL or headers
# (the latter contains the service-role key).
body_text = (r.text or "").strip()[:500]
logger.warning(
"upload_issue_screenshot: Supabase storage rejected upload "
"user=%s status=%d body=%s",
user_id, r.status_code, body_text,
)
raise HTTPException(
status_code=502,
detail=f"Screenshot upload failed (Supabase {r.status_code}): {body_text or 'no body'}",
)
return {"path": path}
75 changes: 75 additions & 0 deletions backend/tests/test_issue_screenshot_auth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
"""
Regression tests for #231 Phase 2a: POST /api/issue-reports/screenshot.

This endpoint moves issue-report screenshot uploads off the frontend's public
anon-key storage client and onto an auth-gated, service-role backend upload so
the issues-media-files bucket can be made private. The negative tests assert it
requires auth (401) and bounds type (415) / size (413); all fail on pre-fix code
(the endpoint didn't exist → 404).
"""
from unittest.mock import patch

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def _png(nbytes: int = 16):
return {"file": ("shot.png", b"\x89PNG\r\n\x1a\n" + b"0" * nbytes, "image/png")}


class TestIssueScreenshotUpload:
def test_unauthenticated_returns_401(self):
from services import auth_guard

with patch("routes.feedback.get_session_user_id", auth_guard._real_get_session_user_id), \
patch.object(auth_guard, "_decode_session", auth_guard._real_decode_session):
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 401

def test_wrong_content_type_returns_415(self):
with patch("routes.feedback.httpx") as hx:
r = client.post(
"/api/issue-reports/screenshot",
files={"file": ("notes.txt", b"hello", "text/plain")},
)
assert r.status_code == 415
hx.put.assert_not_called()

def test_oversize_returns_413(self, monkeypatch):
monkeypatch.setattr("routes.feedback.MAX_SCREENSHOT_BYTES", 100)
with patch("routes.feedback.httpx") as hx:
r = client.post("/api/issue-reports/screenshot", files=_png(nbytes=200))
assert r.status_code == 413
hx.put.assert_not_called()

def test_valid_upload_returns_path_scoped_to_user(self):
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 200
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 200
path = r.json()["path"]
# Path is scoped under the authenticated user_id (conftest stub: user_andres).
assert path.startswith("user_andres/")
assert path.endswith(".png")
hx.put.assert_called_once()

def test_supabase_failure_returns_502_not_500(self):
# When Supabase Storage rejects the upload (e.g. bucket missing /
# RLS denied), the endpoint maps it to a 502 with the truncated
# upstream body — never a generic 500. (#231 review fix.)
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 404
hx.put.return_value.text = '{"statusCode":"404","error":"Bucket not found"}'
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 502
detail = r.json()["detail"]
# Upstream status + body are surfaced for debuggability...
assert "404" in detail
assert "Bucket not found" in detail
# ...but the service-role key (in headers) and upload URL must not leak.
assert "Authorization" not in detail
assert "storage/v1/object" not in detail
hx.put.assert_called_once()
27 changes: 16 additions & 11 deletions frontend/src/components/ReportIssueFlow.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,13 +6,11 @@ import { Pill } from "./Pill";
import { useToast } from "./ToastProvider";
import { useUser } from "@/context/UserContext";
import { useBodyScrollLock } from "@/lib/useBodyScrollLock";
import { supabase } from "@/lib/supabase";
import { submitIssueReport, IS_LOCAL_MODE } from "@/lib/api";
import { submitIssueReport, IS_LOCAL_MODE, API_URL } from "@/lib/api";

const TOPICS = ["Bug", "Feature", "Polish", "Content", "Other"] as const;
type Topic = typeof TOPICS[number];

const BUCKET = "issues-media-files";
const MAX_SCREENSHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;

Expand All@@ -21,14 +19,21 @@ interface ReportIssueFlowProps {
onClose: () => void;
}

async function uploadScreenshot(userId: string, file: File): Promise<string> {
// #231: upload via the auth-gated backend endpoint (service-role) instead of the
// public anon storage client, so issues-media-files can be made private. Returns
// the storage path (stored in screenshot_urls), not a public URL.
async function uploadScreenshot(file: File): Promise<string> {
if (IS_LOCAL_MODE) return URL.createObjectURL(file);
const ext = file.name.split(".").pop() || "png";
const path = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const { error } = await supabase.storage.from(BUCKET).upload(path, file, { cacheControl: "3600", upsert: false });
if (error) throw error;
const { data } = supabase.storage.from(BUCKET).getPublicUrl(path);
return data.publicUrl;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_URL}/api/issue-reports/screenshot`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) throw new Error(`Screenshot upload failed (${res.status})`);
const data = (await res.json()) as { path: string };
return data.path;
}

export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
Expand DownExpand Up@@ -93,7 +98,7 @@ export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
setSubmitting(true);
try {
const urls = await Promise.all(
screenshots.map(s => uploadScreenshot(userId, s.file).catch(err => {
screenshots.map(s => uploadScreenshot(s.file).catch(err => {
toast.error(`Screenshot upload failed: ${err?.message || "unknown"}`);
return null;
})),
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
73 changes: 71 additions & 2 deletions backend/routes/feedback.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
from fastapi import APIRouter
import logging
import uuid

from db.connection import table
import httpx
from fastapi import APIRouter, File, HTTPException, Request, UploadFile

from db.connection import SUPABASE_KEY, SUPABASE_URL, table
from models import SubmitFeedbackBody, SubmitIssueReportBody
from services.auth_guard import get_session_user_id
from services.request_limits import read_within_limit

logger = logging.getLogger(__name__)

router = APIRouter()

# #231: issue-report screenshots upload here. They used to be written by the
# frontend with the public anon key; this endpoint moves the write server-side
# (service role) so the bucket can be made private.
ISSUE_BUCKET = "issues-media-files"
MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024 # 5 MB
ALLOWED_SCREENSHOT_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}


@router.post("/feedback")
def submit_feedback(body: SubmitFeedbackBody):
Expand All@@ -29,3 +44,57 @@ def submit_issue_report(body: SubmitIssueReportBody):
"screenshot_urls": body.screenshot_urls,
})
return {"ok": True}


@router.post("/issue-reports/screenshot")
async def upload_issue_screenshot(request: Request, file: UploadFile = File(...)):
"""Auth-gated, server-side upload for issue-report screenshots (#231).

Replaces the frontend's direct anon-key upload to issues-media-files so the
bucket can be made private (Phase 2b). Validates type + size (the #220/#229
pattern), uploads with the service role, and returns the storage PATH (not a
public URL); the path is stored in issue_reports.screenshot_urls and reviewed
via the dashboard / a signed URL.
"""
user_id = get_session_user_id(request) # 401 if unauthenticated
if (file.content_type or "") not in ALLOWED_SCREENSHOT_TYPES:
raise HTTPException(
status_code=415,
detail="Unsupported image type. Allowed: PNG, JPEG, WEBP, GIF.",
)
content = await read_within_limit(file, MAX_SCREENSHOT_BYTES) # 413 if oversize
if not content:
raise HTTPException(status_code=400, detail="Empty file.")
ext = (
file.filename.rsplit(".", 1)[-1]
if file.filename and "." in file.filename
else "png"
)
path = f"{user_id}/{uuid.uuid4()}.{ext}"
url = f"{SUPABASE_URL}/storage/v1/object/{ISSUE_BUCKET}/{path}"
r = httpx.put(
url,
content=content,
headers={
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": file.content_type or "application/octet-stream",
},
timeout=30.0,
)
if r.status_code not in (200, 201):
# Surface the real Supabase response so the failure is debuggable
# without server access (mirrors storage_service.upload_avatar). We
# only show the truncated upstream body — never the URL or headers
# (the latter contains the service-role key).
body_text = (r.text or "").strip()[:500]
logger.warning(
"upload_issue_screenshot: Supabase storage rejected upload "
"user=%s status=%d body=%s",
user_id, r.status_code, body_text,
)
raise HTTPException(
status_code=502,
detail=f"Screenshot upload failed (Supabase {r.status_code}): {body_text or 'no body'}",
)
return {"path": path}
75 changes: 75 additions & 0 deletions backend/tests/test_issue_screenshot_auth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
"""
Regression tests for #231 Phase 2a: POST /api/issue-reports/screenshot.

This endpoint moves issue-report screenshot uploads off the frontend's public
anon-key storage client and onto an auth-gated, service-role backend upload so
the issues-media-files bucket can be made private. The negative tests assert it
requires auth (401) and bounds type (415) / size (413); all fail on pre-fix code
(the endpoint didn't exist → 404).
"""
from unittest.mock import patch

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def _png(nbytes: int = 16):
return {"file": ("shot.png", b"\x89PNG\r\n\x1a\n" + b"0" * nbytes, "image/png")}


class TestIssueScreenshotUpload:
def test_unauthenticated_returns_401(self):
from services import auth_guard

with patch("routes.feedback.get_session_user_id", auth_guard._real_get_session_user_id), \
patch.object(auth_guard, "_decode_session", auth_guard._real_decode_session):
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 401

def test_wrong_content_type_returns_415(self):
with patch("routes.feedback.httpx") as hx:
r = client.post(
"/api/issue-reports/screenshot",
files={"file": ("notes.txt", b"hello", "text/plain")},
)
assert r.status_code == 415
hx.put.assert_not_called()

def test_oversize_returns_413(self, monkeypatch):
monkeypatch.setattr("routes.feedback.MAX_SCREENSHOT_BYTES", 100)
with patch("routes.feedback.httpx") as hx:
r = client.post("/api/issue-reports/screenshot", files=_png(nbytes=200))
assert r.status_code == 413
hx.put.assert_not_called()

def test_valid_upload_returns_path_scoped_to_user(self):
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 200
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 200
path = r.json()["path"]
# Path is scoped under the authenticated user_id (conftest stub: user_andres).
assert path.startswith("user_andres/")
assert path.endswith(".png")
hx.put.assert_called_once()

def test_supabase_failure_returns_502_not_500(self):
# When Supabase Storage rejects the upload (e.g. bucket missing /
# RLS denied), the endpoint maps it to a 502 with the truncated
# upstream body — never a generic 500. (#231 review fix.)
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 404
hx.put.return_value.text = '{"statusCode":"404","error":"Bucket not found"}'
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 502
detail = r.json()["detail"]
# Upstream status + body are surfaced for debuggability...
assert "404" in detail
assert "Bucket not found" in detail
# ...but the service-role key (in headers) and upload URL must not leak.
assert "Authorization" not in detail
assert "storage/v1/object" not in detail
hx.put.assert_called_once()
27 changes: 16 additions & 11 deletions frontend/src/components/ReportIssueFlow.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,13 +6,11 @@ import { Pill } from "./Pill";
import { useToast } from "./ToastProvider";
import { useUser } from "@/context/UserContext";
import { useBodyScrollLock } from "@/lib/useBodyScrollLock";
import { supabase } from "@/lib/supabase";
import { submitIssueReport, IS_LOCAL_MODE } from "@/lib/api";
import { submitIssueReport, IS_LOCAL_MODE, API_URL } from "@/lib/api";

const TOPICS = ["Bug", "Feature", "Polish", "Content", "Other"] as const;
type Topic = typeof TOPICS[number];

const BUCKET = "issues-media-files";
const MAX_SCREENSHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;

Expand All@@ -21,14 +19,21 @@ interface ReportIssueFlowProps {
onClose: () => void;
}

async function uploadScreenshot(userId: string, file: File): Promise<string> {
// #231: upload via the auth-gated backend endpoint (service-role) instead of the
// public anon storage client, so issues-media-files can be made private. Returns
// the storage path (stored in screenshot_urls), not a public URL.
async function uploadScreenshot(file: File): Promise<string> {
if (IS_LOCAL_MODE) return URL.createObjectURL(file);
const ext = file.name.split(".").pop() || "png";
const path = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const { error } = await supabase.storage.from(BUCKET).upload(path, file, { cacheControl: "3600", upsert: false });
if (error) throw error;
const { data } = supabase.storage.from(BUCKET).getPublicUrl(path);
return data.publicUrl;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_URL}/api/issue-reports/screenshot`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) throw new Error(`Screenshot upload failed (${res.status})`);
const data = (await res.json()) as { path: string };
return data.path;
}

export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
Expand DownExpand Up@@ -93,7 +98,7 @@ export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
setSubmitting(true);
try {
const urls = await Promise.all(
screenshots.map(s => uploadScreenshot(userId, s.file).catch(err => {
screenshots.map(s => uploadScreenshot(s.file).catch(err => {
toast.error(`Screenshot upload failed: ${err?.message || "unknown"}`);
return null;
})),
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
73 changes: 71 additions & 2 deletions backend/routes/feedback.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
from fastapi import APIRouter
import logging
import uuid

from db.connection import table
import httpx
from fastapi import APIRouter, File, HTTPException, Request, UploadFile

from db.connection import SUPABASE_KEY, SUPABASE_URL, table
from models import SubmitFeedbackBody, SubmitIssueReportBody
from services.auth_guard import get_session_user_id
from services.request_limits import read_within_limit

logger = logging.getLogger(__name__)

router = APIRouter()

# #231: issue-report screenshots upload here. They used to be written by the
# frontend with the public anon key; this endpoint moves the write server-side
# (service role) so the bucket can be made private.
ISSUE_BUCKET = "issues-media-files"
MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024 # 5 MB
ALLOWED_SCREENSHOT_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}


@router.post("/feedback")
def submit_feedback(body: SubmitFeedbackBody):
Expand All@@ -29,3 +44,57 @@ def submit_issue_report(body: SubmitIssueReportBody):
"screenshot_urls": body.screenshot_urls,
})
return {"ok": True}


@router.post("/issue-reports/screenshot")
async def upload_issue_screenshot(request: Request, file: UploadFile = File(...)):
"""Auth-gated, server-side upload for issue-report screenshots (#231).

Replaces the frontend's direct anon-key upload to issues-media-files so the
bucket can be made private (Phase 2b). Validates type + size (the #220/#229
pattern), uploads with the service role, and returns the storage PATH (not a
public URL); the path is stored in issue_reports.screenshot_urls and reviewed
via the dashboard / a signed URL.
"""
user_id = get_session_user_id(request) # 401 if unauthenticated
if (file.content_type or "") not in ALLOWED_SCREENSHOT_TYPES:
raise HTTPException(
status_code=415,
detail="Unsupported image type. Allowed: PNG, JPEG, WEBP, GIF.",
)
content = await read_within_limit(file, MAX_SCREENSHOT_BYTES) # 413 if oversize
if not content:
raise HTTPException(status_code=400, detail="Empty file.")
ext = (
file.filename.rsplit(".", 1)[-1]
if file.filename and "." in file.filename
else "png"
)
path = f"{user_id}/{uuid.uuid4()}.{ext}"
url = f"{SUPABASE_URL}/storage/v1/object/{ISSUE_BUCKET}/{path}"
r = httpx.put(
url,
content=content,
headers={
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": file.content_type or "application/octet-stream",
},
timeout=30.0,
)
if r.status_code not in (200, 201):
# Surface the real Supabase response so the failure is debuggable
# without server access (mirrors storage_service.upload_avatar). We
# only show the truncated upstream body — never the URL or headers
# (the latter contains the service-role key).
body_text = (r.text or "").strip()[:500]
logger.warning(
"upload_issue_screenshot: Supabase storage rejected upload "
"user=%s status=%d body=%s",
user_id, r.status_code, body_text,
)
raise HTTPException(
status_code=502,
detail=f"Screenshot upload failed (Supabase {r.status_code}): {body_text or 'no body'}",
)
return {"path": path}
75 changes: 75 additions & 0 deletions backend/tests/test_issue_screenshot_auth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
"""
Regression tests for #231 Phase 2a: POST /api/issue-reports/screenshot.

This endpoint moves issue-report screenshot uploads off the frontend's public
anon-key storage client and onto an auth-gated, service-role backend upload so
the issues-media-files bucket can be made private. The negative tests assert it
requires auth (401) and bounds type (415) / size (413); all fail on pre-fix code
(the endpoint didn't exist → 404).
"""
from unittest.mock import patch

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def _png(nbytes: int = 16):
return {"file": ("shot.png", b"\x89PNG\r\n\x1a\n" + b"0" * nbytes, "image/png")}


class TestIssueScreenshotUpload:
def test_unauthenticated_returns_401(self):
from services import auth_guard

with patch("routes.feedback.get_session_user_id", auth_guard._real_get_session_user_id), \
patch.object(auth_guard, "_decode_session", auth_guard._real_decode_session):
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 401

def test_wrong_content_type_returns_415(self):
with patch("routes.feedback.httpx") as hx:
r = client.post(
"/api/issue-reports/screenshot",
files={"file": ("notes.txt", b"hello", "text/plain")},
)
assert r.status_code == 415
hx.put.assert_not_called()

def test_oversize_returns_413(self, monkeypatch):
monkeypatch.setattr("routes.feedback.MAX_SCREENSHOT_BYTES", 100)
with patch("routes.feedback.httpx") as hx:
r = client.post("/api/issue-reports/screenshot", files=_png(nbytes=200))
assert r.status_code == 413
hx.put.assert_not_called()

def test_valid_upload_returns_path_scoped_to_user(self):
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 200
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 200
path = r.json()["path"]
# Path is scoped under the authenticated user_id (conftest stub: user_andres).
assert path.startswith("user_andres/")
assert path.endswith(".png")
hx.put.assert_called_once()

def test_supabase_failure_returns_502_not_500(self):
# When Supabase Storage rejects the upload (e.g. bucket missing /
# RLS denied), the endpoint maps it to a 502 with the truncated
# upstream body — never a generic 500. (#231 review fix.)
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 404
hx.put.return_value.text = '{"statusCode":"404","error":"Bucket not found"}'
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 502
detail = r.json()["detail"]
# Upstream status + body are surfaced for debuggability...
assert "404" in detail
assert "Bucket not found" in detail
# ...but the service-role key (in headers) and upload URL must not leak.
assert "Authorization" not in detail
assert "storage/v1/object" not in detail
hx.put.assert_called_once()
27 changes: 16 additions & 11 deletions frontend/src/components/ReportIssueFlow.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,13 +6,11 @@ import { Pill } from "./Pill";
import { useToast } from "./ToastProvider";
import { useUser } from "@/context/UserContext";
import { useBodyScrollLock } from "@/lib/useBodyScrollLock";
import { supabase } from "@/lib/supabase";
import { submitIssueReport, IS_LOCAL_MODE } from "@/lib/api";
import { submitIssueReport, IS_LOCAL_MODE, API_URL } from "@/lib/api";

const TOPICS = ["Bug", "Feature", "Polish", "Content", "Other"] as const;
type Topic = typeof TOPICS[number];

const BUCKET = "issues-media-files";
const MAX_SCREENSHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;

Expand All@@ -21,14 +19,21 @@ interface ReportIssueFlowProps {
onClose: () => void;
}

async function uploadScreenshot(userId: string, file: File): Promise<string> {
// #231: upload via the auth-gated backend endpoint (service-role) instead of the
// public anon storage client, so issues-media-files can be made private. Returns
// the storage path (stored in screenshot_urls), not a public URL.
async function uploadScreenshot(file: File): Promise<string> {
if (IS_LOCAL_MODE) return URL.createObjectURL(file);
const ext = file.name.split(".").pop() || "png";
const path = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const { error } = await supabase.storage.from(BUCKET).upload(path, file, { cacheControl: "3600", upsert: false });
if (error) throw error;
const { data } = supabase.storage.from(BUCKET).getPublicUrl(path);
return data.publicUrl;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_URL}/api/issue-reports/screenshot`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) throw new Error(`Screenshot upload failed (${res.status})`);
const data = (await res.json()) as { path: string };
return data.path;
}

export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
Expand DownExpand Up@@ -93,7 +98,7 @@ export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
setSubmitting(true);
try {
const urls = await Promise.all(
screenshots.map(s => uploadScreenshot(userId, s.file).catch(err => {
screenshots.map(s => uploadScreenshot(s.file).catch(err => {
toast.error(`Screenshot upload failed: ${err?.message || "unknown"}`);
return null;
})),
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
73 changes: 71 additions & 2 deletions backend/routes/feedback.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
from fastapi import APIRouter
import logging
import uuid

from db.connection import table
import httpx
from fastapi import APIRouter, File, HTTPException, Request, UploadFile

from db.connection import SUPABASE_KEY, SUPABASE_URL, table
from models import SubmitFeedbackBody, SubmitIssueReportBody
from services.auth_guard import get_session_user_id
from services.request_limits import read_within_limit

logger = logging.getLogger(__name__)

router = APIRouter()

# #231: issue-report screenshots upload here. They used to be written by the
# frontend with the public anon key; this endpoint moves the write server-side
# (service role) so the bucket can be made private.
ISSUE_BUCKET = "issues-media-files"
MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024 # 5 MB
ALLOWED_SCREENSHOT_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}


@router.post("/feedback")
def submit_feedback(body: SubmitFeedbackBody):
Expand All@@ -29,3 +44,57 @@ def submit_issue_report(body: SubmitIssueReportBody):
"screenshot_urls": body.screenshot_urls,
})
return {"ok": True}


@router.post("/issue-reports/screenshot")
async def upload_issue_screenshot(request: Request, file: UploadFile = File(...)):
"""Auth-gated, server-side upload for issue-report screenshots (#231).

Replaces the frontend's direct anon-key upload to issues-media-files so the
bucket can be made private (Phase 2b). Validates type + size (the #220/#229
pattern), uploads with the service role, and returns the storage PATH (not a
public URL); the path is stored in issue_reports.screenshot_urls and reviewed
via the dashboard / a signed URL.
"""
user_id = get_session_user_id(request) # 401 if unauthenticated
if (file.content_type or "") not in ALLOWED_SCREENSHOT_TYPES:
raise HTTPException(
status_code=415,
detail="Unsupported image type. Allowed: PNG, JPEG, WEBP, GIF.",
)
content = await read_within_limit(file, MAX_SCREENSHOT_BYTES) # 413 if oversize
if not content:
raise HTTPException(status_code=400, detail="Empty file.")
ext = (
file.filename.rsplit(".", 1)[-1]
if file.filename and "." in file.filename
else "png"
)
path = f"{user_id}/{uuid.uuid4()}.{ext}"
url = f"{SUPABASE_URL}/storage/v1/object/{ISSUE_BUCKET}/{path}"
r = httpx.put(
url,
content=content,
headers={
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": file.content_type or "application/octet-stream",
},
timeout=30.0,
)
if r.status_code not in (200, 201):
# Surface the real Supabase response so the failure is debuggable
# without server access (mirrors storage_service.upload_avatar). We
# only show the truncated upstream body — never the URL or headers
# (the latter contains the service-role key).
body_text = (r.text or "").strip()[:500]
logger.warning(
"upload_issue_screenshot: Supabase storage rejected upload "
"user=%s status=%d body=%s",
user_id, r.status_code, body_text,
)
raise HTTPException(
status_code=502,
detail=f"Screenshot upload failed (Supabase {r.status_code}): {body_text or 'no body'}",
)
return {"path": path}
75 changes: 75 additions & 0 deletions backend/tests/test_issue_screenshot_auth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
"""
Regression tests for #231 Phase 2a: POST /api/issue-reports/screenshot.

This endpoint moves issue-report screenshot uploads off the frontend's public
anon-key storage client and onto an auth-gated, service-role backend upload so
the issues-media-files bucket can be made private. The negative tests assert it
requires auth (401) and bounds type (415) / size (413); all fail on pre-fix code
(the endpoint didn't exist → 404).
"""
from unittest.mock import patch

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def _png(nbytes: int = 16):
return {"file": ("shot.png", b"\x89PNG\r\n\x1a\n" + b"0" * nbytes, "image/png")}


class TestIssueScreenshotUpload:
def test_unauthenticated_returns_401(self):
from services import auth_guard

with patch("routes.feedback.get_session_user_id", auth_guard._real_get_session_user_id), \
patch.object(auth_guard, "_decode_session", auth_guard._real_decode_session):
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 401

def test_wrong_content_type_returns_415(self):
with patch("routes.feedback.httpx") as hx:
r = client.post(
"/api/issue-reports/screenshot",
files={"file": ("notes.txt", b"hello", "text/plain")},
)
assert r.status_code == 415
hx.put.assert_not_called()

def test_oversize_returns_413(self, monkeypatch):
monkeypatch.setattr("routes.feedback.MAX_SCREENSHOT_BYTES", 100)
with patch("routes.feedback.httpx") as hx:
r = client.post("/api/issue-reports/screenshot", files=_png(nbytes=200))
assert r.status_code == 413
hx.put.assert_not_called()

def test_valid_upload_returns_path_scoped_to_user(self):
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 200
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 200
path = r.json()["path"]
# Path is scoped under the authenticated user_id (conftest stub: user_andres).
assert path.startswith("user_andres/")
assert path.endswith(".png")
hx.put.assert_called_once()

def test_supabase_failure_returns_502_not_500(self):
# When Supabase Storage rejects the upload (e.g. bucket missing /
# RLS denied), the endpoint maps it to a 502 with the truncated
# upstream body — never a generic 500. (#231 review fix.)
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 404
hx.put.return_value.text = '{"statusCode":"404","error":"Bucket not found"}'
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 502
detail = r.json()["detail"]
# Upstream status + body are surfaced for debuggability...
assert "404" in detail
assert "Bucket not found" in detail
# ...but the service-role key (in headers) and upload URL must not leak.
assert "Authorization" not in detail
assert "storage/v1/object" not in detail
hx.put.assert_called_once()
27 changes: 16 additions & 11 deletions frontend/src/components/ReportIssueFlow.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,13 +6,11 @@ import { Pill } from "./Pill";
import { useToast } from "./ToastProvider";
import { useUser } from "@/context/UserContext";
import { useBodyScrollLock } from "@/lib/useBodyScrollLock";
import { supabase } from "@/lib/supabase";
import { submitIssueReport, IS_LOCAL_MODE } from "@/lib/api";
import { submitIssueReport, IS_LOCAL_MODE, API_URL } from "@/lib/api";

const TOPICS = ["Bug", "Feature", "Polish", "Content", "Other"] as const;
type Topic = typeof TOPICS[number];

const BUCKET = "issues-media-files";
const MAX_SCREENSHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;

Expand All@@ -21,14 +19,21 @@ interface ReportIssueFlowProps {
onClose: () => void;
}

async function uploadScreenshot(userId: string, file: File): Promise<string> {
// #231: upload via the auth-gated backend endpoint (service-role) instead of the
// public anon storage client, so issues-media-files can be made private. Returns
// the storage path (stored in screenshot_urls), not a public URL.
async function uploadScreenshot(file: File): Promise<string> {
if (IS_LOCAL_MODE) return URL.createObjectURL(file);
const ext = file.name.split(".").pop() || "png";
const path = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const { error } = await supabase.storage.from(BUCKET).upload(path, file, { cacheControl: "3600", upsert: false });
if (error) throw error;
const { data } = supabase.storage.from(BUCKET).getPublicUrl(path);
return data.publicUrl;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_URL}/api/issue-reports/screenshot`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) throw new Error(`Screenshot upload failed (${res.status})`);
const data = (await res.json()) as { path: string };
return data.path;
}

export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
Expand DownExpand Up@@ -93,7 +98,7 @@ export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
setSubmitting(true);
try {
const urls = await Promise.all(
screenshots.map(s => uploadScreenshot(userId, s.file).catch(err => {
screenshots.map(s => uploadScreenshot(s.file).catch(err => {
toast.error(`Screenshot upload failed: ${err?.message || "unknown"}`);
return null;
})),
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
73 changes: 71 additions & 2 deletions backend/routes/feedback.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
from fastapi import APIRouter
import logging
import uuid

from db.connection import table
import httpx
from fastapi import APIRouter, File, HTTPException, Request, UploadFile

from db.connection import SUPABASE_KEY, SUPABASE_URL, table
from models import SubmitFeedbackBody, SubmitIssueReportBody
from services.auth_guard import get_session_user_id
from services.request_limits import read_within_limit

logger = logging.getLogger(__name__)

router = APIRouter()

# #231: issue-report screenshots upload here. They used to be written by the
# frontend with the public anon key; this endpoint moves the write server-side
# (service role) so the bucket can be made private.
ISSUE_BUCKET = "issues-media-files"
MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024 # 5 MB
ALLOWED_SCREENSHOT_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}


@router.post("/feedback")
def submit_feedback(body: SubmitFeedbackBody):
Expand All@@ -29,3 +44,57 @@ def submit_issue_report(body: SubmitIssueReportBody):
"screenshot_urls": body.screenshot_urls,
})
return {"ok": True}


@router.post("/issue-reports/screenshot")
async def upload_issue_screenshot(request: Request, file: UploadFile = File(...)):
"""Auth-gated, server-side upload for issue-report screenshots (#231).

Replaces the frontend's direct anon-key upload to issues-media-files so the
bucket can be made private (Phase 2b). Validates type + size (the #220/#229
pattern), uploads with the service role, and returns the storage PATH (not a
public URL); the path is stored in issue_reports.screenshot_urls and reviewed
via the dashboard / a signed URL.
"""
user_id = get_session_user_id(request) # 401 if unauthenticated
if (file.content_type or "") not in ALLOWED_SCREENSHOT_TYPES:
raise HTTPException(
status_code=415,
detail="Unsupported image type. Allowed: PNG, JPEG, WEBP, GIF.",
)
content = await read_within_limit(file, MAX_SCREENSHOT_BYTES) # 413 if oversize
if not content:
raise HTTPException(status_code=400, detail="Empty file.")
ext = (
file.filename.rsplit(".", 1)[-1]
if file.filename and "." in file.filename
else "png"
)
path = f"{user_id}/{uuid.uuid4()}.{ext}"
url = f"{SUPABASE_URL}/storage/v1/object/{ISSUE_BUCKET}/{path}"
r = httpx.put(
url,
content=content,
headers={
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": file.content_type or "application/octet-stream",
},
timeout=30.0,
)
if r.status_code not in (200, 201):
# Surface the real Supabase response so the failure is debuggable
# without server access (mirrors storage_service.upload_avatar). We
# only show the truncated upstream body — never the URL or headers
# (the latter contains the service-role key).
body_text = (r.text or "").strip()[:500]
logger.warning(
"upload_issue_screenshot: Supabase storage rejected upload "
"user=%s status=%d body=%s",
user_id, r.status_code, body_text,
)
raise HTTPException(
status_code=502,
detail=f"Screenshot upload failed (Supabase {r.status_code}): {body_text or 'no body'}",
)
return {"path": path}
75 changes: 75 additions & 0 deletions backend/tests/test_issue_screenshot_auth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
"""
Regression tests for #231 Phase 2a: POST /api/issue-reports/screenshot.

This endpoint moves issue-report screenshot uploads off the frontend's public
anon-key storage client and onto an auth-gated, service-role backend upload so
the issues-media-files bucket can be made private. The negative tests assert it
requires auth (401) and bounds type (415) / size (413); all fail on pre-fix code
(the endpoint didn't exist → 404).
"""
from unittest.mock import patch

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def _png(nbytes: int = 16):
return {"file": ("shot.png", b"\x89PNG\r\n\x1a\n" + b"0" * nbytes, "image/png")}


class TestIssueScreenshotUpload:
def test_unauthenticated_returns_401(self):
from services import auth_guard

with patch("routes.feedback.get_session_user_id", auth_guard._real_get_session_user_id), \
patch.object(auth_guard, "_decode_session", auth_guard._real_decode_session):
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 401

def test_wrong_content_type_returns_415(self):
with patch("routes.feedback.httpx") as hx:
r = client.post(
"/api/issue-reports/screenshot",
files={"file": ("notes.txt", b"hello", "text/plain")},
)
assert r.status_code == 415
hx.put.assert_not_called()

def test_oversize_returns_413(self, monkeypatch):
monkeypatch.setattr("routes.feedback.MAX_SCREENSHOT_BYTES", 100)
with patch("routes.feedback.httpx") as hx:
r = client.post("/api/issue-reports/screenshot", files=_png(nbytes=200))
assert r.status_code == 413
hx.put.assert_not_called()

def test_valid_upload_returns_path_scoped_to_user(self):
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 200
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 200
path = r.json()["path"]
# Path is scoped under the authenticated user_id (conftest stub: user_andres).
assert path.startswith("user_andres/")
assert path.endswith(".png")
hx.put.assert_called_once()

def test_supabase_failure_returns_502_not_500(self):
# When Supabase Storage rejects the upload (e.g. bucket missing /
# RLS denied), the endpoint maps it to a 502 with the truncated
# upstream body — never a generic 500. (#231 review fix.)
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 404
hx.put.return_value.text = '{"statusCode":"404","error":"Bucket not found"}'
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 502
detail = r.json()["detail"]
# Upstream status + body are surfaced for debuggability...
assert "404" in detail
assert "Bucket not found" in detail
# ...but the service-role key (in headers) and upload URL must not leak.
assert "Authorization" not in detail
assert "storage/v1/object" not in detail
hx.put.assert_called_once()
27 changes: 16 additions & 11 deletions frontend/src/components/ReportIssueFlow.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,13 +6,11 @@ import { Pill } from "./Pill";
import { useToast } from "./ToastProvider";
import { useUser } from "@/context/UserContext";
import { useBodyScrollLock } from "@/lib/useBodyScrollLock";
import { supabase } from "@/lib/supabase";
import { submitIssueReport, IS_LOCAL_MODE } from "@/lib/api";
import { submitIssueReport, IS_LOCAL_MODE, API_URL } from "@/lib/api";

const TOPICS = ["Bug", "Feature", "Polish", "Content", "Other"] as const;
type Topic = typeof TOPICS[number];

const BUCKET = "issues-media-files";
const MAX_SCREENSHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;

Expand All@@ -21,14 +19,21 @@ interface ReportIssueFlowProps {
onClose: () => void;
}

async function uploadScreenshot(userId: string, file: File): Promise<string> {
// #231: upload via the auth-gated backend endpoint (service-role) instead of the
// public anon storage client, so issues-media-files can be made private. Returns
// the storage path (stored in screenshot_urls), not a public URL.
async function uploadScreenshot(file: File): Promise<string> {
if (IS_LOCAL_MODE) return URL.createObjectURL(file);
const ext = file.name.split(".").pop() || "png";
const path = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const { error } = await supabase.storage.from(BUCKET).upload(path, file, { cacheControl: "3600", upsert: false });
if (error) throw error;
const { data } = supabase.storage.from(BUCKET).getPublicUrl(path);
return data.publicUrl;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_URL}/api/issue-reports/screenshot`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) throw new Error(`Screenshot upload failed (${res.status})`);
const data = (await res.json()) as { path: string };
return data.path;
}

export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
Expand DownExpand Up@@ -93,7 +98,7 @@ export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
setSubmitting(true);
try {
const urls = await Promise.all(
screenshots.map(s => uploadScreenshot(userId, s.file).catch(err => {
screenshots.map(s => uploadScreenshot(s.file).catch(err => {
toast.error(`Screenshot upload failed: ${err?.message || "unknown"}`);
return null;
})),
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
73 changes: 71 additions & 2 deletions backend/routes/feedback.py
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,25 @@
from fastapi import APIRouter
import logging
import uuid

from db.connection import table
import httpx
from fastapi import APIRouter, File, HTTPException, Request, UploadFile

from db.connection import SUPABASE_KEY, SUPABASE_URL, table
from models import SubmitFeedbackBody, SubmitIssueReportBody
from services.auth_guard import get_session_user_id
from services.request_limits import read_within_limit

logger = logging.getLogger(__name__)

router = APIRouter()

# #231: issue-report screenshots upload here. They used to be written by the
# frontend with the public anon key; this endpoint moves the write server-side
# (service role) so the bucket can be made private.
ISSUE_BUCKET = "issues-media-files"
MAX_SCREENSHOT_BYTES = 5 * 1024 * 1024 # 5 MB
ALLOWED_SCREENSHOT_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}


@router.post("/feedback")
def submit_feedback(body: SubmitFeedbackBody):
Expand All@@ -29,3 +44,57 @@ def submit_issue_report(body: SubmitIssueReportBody):
"screenshot_urls": body.screenshot_urls,
})
return {"ok": True}


@router.post("/issue-reports/screenshot")
async def upload_issue_screenshot(request: Request, file: UploadFile = File(...)):
"""Auth-gated, server-side upload for issue-report screenshots (#231).

Replaces the frontend's direct anon-key upload to issues-media-files so the
bucket can be made private (Phase 2b). Validates type + size (the #220/#229
pattern), uploads with the service role, and returns the storage PATH (not a
public URL); the path is stored in issue_reports.screenshot_urls and reviewed
via the dashboard / a signed URL.
"""
user_id = get_session_user_id(request) # 401 if unauthenticated
if (file.content_type or "") not in ALLOWED_SCREENSHOT_TYPES:
raise HTTPException(
status_code=415,
detail="Unsupported image type. Allowed: PNG, JPEG, WEBP, GIF.",
)
content = await read_within_limit(file, MAX_SCREENSHOT_BYTES) # 413 if oversize
if not content:
raise HTTPException(status_code=400, detail="Empty file.")
ext = (
file.filename.rsplit(".", 1)[-1]
if file.filename and "." in file.filename
else "png"
)
path = f"{user_id}/{uuid.uuid4()}.{ext}"
url = f"{SUPABASE_URL}/storage/v1/object/{ISSUE_BUCKET}/{path}"
r = httpx.put(
url,
content=content,
headers={
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": file.content_type or "application/octet-stream",
},
timeout=30.0,
)
if r.status_code not in (200, 201):
# Surface the real Supabase response so the failure is debuggable
# without server access (mirrors storage_service.upload_avatar). We
# only show the truncated upstream body — never the URL or headers
# (the latter contains the service-role key).
body_text = (r.text or "").strip()[:500]
logger.warning(
"upload_issue_screenshot: Supabase storage rejected upload "
"user=%s status=%d body=%s",
user_id, r.status_code, body_text,
)
raise HTTPException(
status_code=502,
detail=f"Screenshot upload failed (Supabase {r.status_code}): {body_text or 'no body'}",
)
return {"path": path}
75 changes: 75 additions & 0 deletions backend/tests/test_issue_screenshot_auth.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
"""
Regression tests for #231 Phase 2a: POST /api/issue-reports/screenshot.

This endpoint moves issue-report screenshot uploads off the frontend's public
anon-key storage client and onto an auth-gated, service-role backend upload so
the issues-media-files bucket can be made private. The negative tests assert it
requires auth (401) and bounds type (415) / size (413); all fail on pre-fix code
(the endpoint didn't exist → 404).
"""
from unittest.mock import patch

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def _png(nbytes: int = 16):
return {"file": ("shot.png", b"\x89PNG\r\n\x1a\n" + b"0" * nbytes, "image/png")}


class TestIssueScreenshotUpload:
def test_unauthenticated_returns_401(self):
from services import auth_guard

with patch("routes.feedback.get_session_user_id", auth_guard._real_get_session_user_id), \
patch.object(auth_guard, "_decode_session", auth_guard._real_decode_session):
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 401

def test_wrong_content_type_returns_415(self):
with patch("routes.feedback.httpx") as hx:
r = client.post(
"/api/issue-reports/screenshot",
files={"file": ("notes.txt", b"hello", "text/plain")},
)
assert r.status_code == 415
hx.put.assert_not_called()

def test_oversize_returns_413(self, monkeypatch):
monkeypatch.setattr("routes.feedback.MAX_SCREENSHOT_BYTES", 100)
with patch("routes.feedback.httpx") as hx:
r = client.post("/api/issue-reports/screenshot", files=_png(nbytes=200))
assert r.status_code == 413
hx.put.assert_not_called()

def test_valid_upload_returns_path_scoped_to_user(self):
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 200
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 200
path = r.json()["path"]
# Path is scoped under the authenticated user_id (conftest stub: user_andres).
assert path.startswith("user_andres/")
assert path.endswith(".png")
hx.put.assert_called_once()

def test_supabase_failure_returns_502_not_500(self):
# When Supabase Storage rejects the upload (e.g. bucket missing /
# RLS denied), the endpoint maps it to a 502 with the truncated
# upstream body — never a generic 500. (#231 review fix.)
with patch("routes.feedback.httpx") as hx:
hx.put.return_value.status_code = 404
hx.put.return_value.text = '{"statusCode":"404","error":"Bucket not found"}'
r = client.post("/api/issue-reports/screenshot", files=_png())
assert r.status_code == 502
detail = r.json()["detail"]
# Upstream status + body are surfaced for debuggability...
assert "404" in detail
assert "Bucket not found" in detail
# ...but the service-role key (in headers) and upload URL must not leak.
assert "Authorization" not in detail
assert "storage/v1/object" not in detail
hx.put.assert_called_once()
27 changes: 16 additions & 11 deletions frontend/src/components/ReportIssueFlow.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,13 +6,11 @@ import { Pill } from "./Pill";
import { useToast } from "./ToastProvider";
import { useUser } from "@/context/UserContext";
import { useBodyScrollLock } from "@/lib/useBodyScrollLock";
import { supabase } from "@/lib/supabase";
import { submitIssueReport, IS_LOCAL_MODE } from "@/lib/api";
import { submitIssueReport, IS_LOCAL_MODE, API_URL } from "@/lib/api";

const TOPICS = ["Bug", "Feature", "Polish", "Content", "Other"] as const;
type Topic = typeof TOPICS[number];

const BUCKET = "issues-media-files";
const MAX_SCREENSHOTS = 5;
const MAX_BYTES = 5 * 1024 * 1024;

Expand All@@ -21,14 +19,21 @@ interface ReportIssueFlowProps {
onClose: () => void;
}

async function uploadScreenshot(userId: string, file: File): Promise<string> {
// #231: upload via the auth-gated backend endpoint (service-role) instead of the
// public anon storage client, so issues-media-files can be made private. Returns
// the storage path (stored in screenshot_urls), not a public URL.
async function uploadScreenshot(file: File): Promise<string> {
if (IS_LOCAL_MODE) return URL.createObjectURL(file);
const ext = file.name.split(".").pop() || "png";
const path = `${userId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
const { error } = await supabase.storage.from(BUCKET).upload(path, file, { cacheControl: "3600", upsert: false });
if (error) throw error;
const { data } = supabase.storage.from(BUCKET).getPublicUrl(path);
return data.publicUrl;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_URL}/api/issue-reports/screenshot`, {
method: "POST",
credentials: "include",
body: form,
});
if (!res.ok) throw new Error(`Screenshot upload failed (${res.status})`);
const data = (await res.json()) as { path: string };
return data.path;
}

export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
Expand DownExpand Up@@ -93,7 +98,7 @@ export function ReportIssueFlow({ open, onClose }: ReportIssueFlowProps) {
setSubmitting(true);
try {
const urls = await Promise.all(
screenshots.map(s => uploadScreenshot(userId, s.file).catch(err => {
screenshots.map(s => uploadScreenshot(s.file).catch(err => {
toast.error(`Screenshot upload failed: ${err?.message || "unknown"}`);
return null;
})),
Expand Down
Loading