Greg Claude Opus 4.7 (1M context) commited on
Commit
8ca1e92
·
1 Parent(s): 3263790

feat(ta-01): backend-proxy photo URLs so they stop expiring

Browse files

Frontend now receives stable /api/v1/photos/{account_id}/{user_id}/{filename}
URLs for face photos, regardless of which storage backend is active. The
serve_photo endpoint authenticates against our own JWT and streams the
bytes from disk (local) or Supabase (S3 via boto3.get_object). Browser
caches the response privately for 5 minutes so re-renders don't hit
the backend.

This eliminates the 10-min signed-URL expiry pain — the URL never changes
and never goes stale. Same behavior on the local-disk dev backend and
on Supabase in prod.

- PhotoStorage Protocol gains fetch_bytes(path) -> (bytes, content_type).
- Implemented on all three adapters (Local, InMemory, Supabase).
- serve_photo routes through the protocol; per-backend logic moves there.
- users.py response mapping and the upload endpoint return the proxied
URL instead of storage.get_url() so legacy signed URLs are gone.

Tests: 22 passed (storage + photo upload), no regressions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

backend/app/api/v1/endpoints/photos.py CHANGED
@@ -1,11 +1,10 @@
1
  import os
2
- from pathlib import Path
3
  from fastapi import APIRouter, Depends, HTTPException
4
- from fastapi.responses import FileResponse
5
  from app.dependencies.auth import get_current_user
6
  from app.middleware.rbac import RBAC
7
  from app.models.user import User
8
- from app.storage import resolved_backend
9
 
10
  router = APIRouter(prefix="/photos", tags=["photos"])
11
 
@@ -44,15 +43,22 @@ def serve_photo(
44
  filename: str,
45
  current_user: User = Depends(get_current_user),
46
  ):
47
- if os.getenv("PHOTO_STORAGE_BACKEND", "local").lower() != "local":
48
- raise HTTPException(status_code=404, detail="not served locally")
 
49
  if current_user.account_id != account_id:
50
  raise HTTPException(status_code=404, detail="not found")
51
- root = Path(os.getenv("LOCAL_PHOTO_ROOT", "/data/photos")).resolve()
52
- target = (root / str(account_id) / str(user_id) / filename).resolve()
53
- # Block path traversal (filename = "../../../etc/passwd" etc.)
54
- if not target.is_relative_to(root):
55
  raise HTTPException(status_code=400, detail="invalid path")
56
- if not target.exists():
 
 
 
 
 
57
  raise HTTPException(status_code=404, detail="not found")
58
- return FileResponse(target, media_type="image/webp")
 
 
 
 
 
1
  import os
 
2
  from fastapi import APIRouter, Depends, HTTPException
3
+ from fastapi.responses import Response
4
  from app.dependencies.auth import get_current_user
5
  from app.middleware.rbac import RBAC
6
  from app.models.user import User
7
+ from app.storage import get_storage, resolved_backend
8
 
9
  router = APIRouter(prefix="/photos", tags=["photos"])
10
 
 
43
  filename: str,
44
  current_user: User = Depends(get_current_user),
45
  ):
46
+ """Proxy bytes from whichever storage backend is active so the frontend
47
+ always sees a stable, JWT-protected URL. The image is cached by the
48
+ browser for 5 minutes (private), so re-renders don't hit the backend."""
49
  if current_user.account_id != account_id:
50
  raise HTTPException(status_code=404, detail="not found")
51
+ if "/" in filename or ".." in filename:
 
 
 
52
  raise HTTPException(status_code=400, detail="invalid path")
53
+
54
+ key = f"{account_id}/{user_id}/{filename}"
55
+ storage = get_storage()
56
+ try:
57
+ content, content_type = storage.fetch_bytes(key)
58
+ except FileNotFoundError:
59
  raise HTTPException(status_code=404, detail="not found")
60
+ return Response(
61
+ content=content,
62
+ media_type=content_type,
63
+ headers={"Cache-Control": "private, max-age=300"},
64
+ )
backend/app/api/v1/endpoints/users.py CHANGED
@@ -96,14 +96,15 @@ def list_users(
96
  )
97
  photos = {r.user_id: r.photo for r in rows}
98
 
99
- storage = get_storage()
100
  items = []
101
  for u in users:
102
  ur = UserResponse.model_validate(
103
  {c.name: getattr(u, c.name) for c in u.__table__.columns},
104
  )
105
  raw_path = photos.get(u.id)
106
- ur.face_photo = storage.get_url(raw_path) if raw_path else None
 
 
107
  items.append(ur)
108
 
109
  return PaginatedResponse(
@@ -393,7 +394,7 @@ def upload_user_photo(
393
  db.commit()
394
 
395
  return {
396
- "photo_url": storage.get_url(new_path),
397
  "encoding_extracted": encoding_str is not None,
398
  "warning": None if encoding_str else
399
  "no se detectó rostro; el reconocimiento facial no funcionará hasta resubir una foto con rostro visible",
 
96
  )
97
  photos = {r.user_id: r.photo for r in rows}
98
 
 
99
  items = []
100
  for u in users:
101
  ur = UserResponse.model_validate(
102
  {c.name: getattr(u, c.name) for c in u.__table__.columns},
103
  )
104
  raw_path = photos.get(u.id)
105
+ # Backend-proxied URL: stable across signed-URL TTLs and works
106
+ # regardless of which storage backend is active.
107
+ ur.face_photo = f"/api/v1/photos/{raw_path}" if raw_path else None
108
  items.append(ur)
109
 
110
  return PaginatedResponse(
 
394
  db.commit()
395
 
396
  return {
397
+ "photo_url": f"/api/v1/photos/{new_path}",
398
  "encoding_extracted": encoding_str is not None,
399
  "warning": None if encoding_str else
400
  "no se detectó rostro; el reconocimiento facial no funcionará hasta resubir una foto con rostro visible",
backend/app/storage/base.py CHANGED
@@ -1,4 +1,4 @@
1
- from typing import Protocol
2
 
3
 
4
  class PhotoStorage(Protocol):
@@ -11,5 +11,13 @@ class PhotoStorage(Protocol):
11
  ...
12
 
13
  def get_url(self, path_or_url: str) -> str:
14
- """Devuelve la URL pública/firmada que el frontend usa para mostrar la foto."""
 
 
 
 
 
 
 
 
15
  ...
 
1
+ from typing import Protocol, Tuple
2
 
3
 
4
  class PhotoStorage(Protocol):
 
11
  ...
12
 
13
  def get_url(self, path_or_url: str) -> str:
14
+ """URL directa (pública/firmada) al objeto. Usada cuando el frontend
15
+ puede consumir el storage directamente. La mayoría de los flujos
16
+ ahora usan `fetch_bytes` vía el backend proxy en /api/v1/photos."""
17
+ ...
18
+
19
+ def fetch_bytes(self, path_or_url: str) -> Tuple[bytes, str]:
20
+ """Devuelve (contenido, content_type). Levanta FileNotFoundError
21
+ si el objeto no existe. Usado por el endpoint serve_photo para
22
+ proxear bytes desde cualquier backend con auth de nuestro JWT."""
23
  ...
backend/app/storage/in_memory.py CHANGED
@@ -15,3 +15,8 @@ class InMemoryStorage:
15
 
16
  def get_url(self, path_or_url: str) -> str:
17
  return path_or_url
 
 
 
 
 
 
15
 
16
  def get_url(self, path_or_url: str) -> str:
17
  return path_or_url
18
+
19
+ def fetch_bytes(self, path_or_url: str) -> tuple[bytes, str]:
20
+ if path_or_url not in self.files:
21
+ raise FileNotFoundError(path_or_url)
22
+ return self.files[path_or_url], "image/webp"
backend/app/storage/local_disk.py CHANGED
@@ -30,3 +30,14 @@ class LocalDiskStorage:
30
  if path_or_url.startswith(self.url_prefix + "/"):
31
  return path_or_url
32
  return f"{self.url_prefix}/{path_or_url}"
 
 
 
 
 
 
 
 
 
 
 
 
30
  if path_or_url.startswith(self.url_prefix + "/"):
31
  return path_or_url
32
  return f"{self.url_prefix}/{path_or_url}"
33
+
34
+ def fetch_bytes(self, path_or_url: str) -> tuple[bytes, str]:
35
+ rel = path_or_url
36
+ if path_or_url.startswith(self.url_prefix + "/"):
37
+ rel = path_or_url[len(self.url_prefix) + 1:]
38
+ target = (self.root / rel).resolve()
39
+ if not target.is_relative_to(self.root.resolve()):
40
+ raise FileNotFoundError(rel) # path traversal attempt
41
+ if not target.exists():
42
+ raise FileNotFoundError(rel)
43
+ return target.read_bytes(), "image/webp"
backend/app/storage/supabase.py CHANGED
@@ -82,3 +82,15 @@ class SupabaseStorage:
82
  Params={"Bucket": self.bucket, "Key": path_or_url},
83
  ExpiresIn=self.signed_url_ttl,
84
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  Params={"Bucket": self.bucket, "Key": path_or_url},
83
  ExpiresIn=self.signed_url_ttl,
84
  )
85
+
86
+ def fetch_bytes(self, path_or_url: str) -> tuple[bytes, str]:
87
+ key = self._strip_url_prefix(path_or_url)
88
+ try:
89
+ resp = self._client.get_object(Bucket=self.bucket, Key=key)
90
+ except Exception as e:
91
+ # boto3 raises ClientError for missing objects; surface as
92
+ # FileNotFoundError to keep the serve endpoint simple.
93
+ raise FileNotFoundError(key) from e
94
+ content = resp["Body"].read()
95
+ content_type = resp.get("ContentType") or "image/webp"
96
+ return content, content_type