Greg Claude Opus 4.7 (1M context) commited on
Commit
ea91fea
·
1 Parent(s): 5e480e2

feat(ta-01): implement SupabaseStorage adapter with signed URLs

Browse files

- SupabaseStorage uploads to {account_id}/{user_id}/{uuid}.{ext} inside the
configured bucket via supabase-py. get_url() returns a short-lived signed
URL (default 10 min TTL) so private buckets stay private.
- _strip_url_prefix normalizes inputs so delete() works whether given a
relative path or a full Supabase URL (with or without query token).
- supabase>=2.0 added to requirements; SDK is lazily imported so the local
backend (PHOTO_STORAGE_BACKEND=local) doesn't pay the cost.
- AuthImage now passes http(s):// URLs through directly (Supabase signed
URLs are already authenticated via the token query param).
- Tests updated to cover credential check, prefix stripping for relative
paths and signed URLs.

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

backend/app/storage/supabase.py CHANGED
@@ -1,22 +1,78 @@
1
- class SupabaseStorage:
2
- """Stub. Se implementa cuando lleguen credenciales de Supabase."""
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- def __init__(self, url: str, key: str, bucket: str) -> None:
 
 
 
 
 
5
  self.url = url
6
  self.key = key
7
  self.bucket = bucket
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
10
- raise NotImplementedError(
11
- "SupabaseStorage upload todavía no implementado — usar PHOTO_STORAGE_BACKEND=local"
 
 
 
 
 
 
 
12
  )
 
13
 
14
  def delete(self, path_or_url: str) -> None:
15
- raise NotImplementedError(
16
- "SupabaseStorage delete todavía no implementado"
17
- )
 
 
18
 
19
  def get_url(self, path_or_url: str) -> str:
20
- raise NotImplementedError(
21
- "SupabaseStorage get_url todavía no implementado"
 
 
 
 
 
 
 
22
  )
 
 
 
 
 
1
+ """Supabase Storage adapter.
2
+
3
+ Uploads photos to a Supabase Storage bucket (assumed private). Returns the
4
+ relative object path as the canonical id (stored in `face_encodings.photo`),
5
+ and produces short-lived signed URLs for frontend consumption.
6
+
7
+ If the bucket is public, signed-URL generation still works but anyone with
8
+ the URL can fetch the file. Keep the bucket private and rely on signed URLs.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import uuid
13
+ from typing import Any
14
+
15
 
16
+ class SupabaseStorage:
17
+ def __init__(self, url: str, key: str, bucket: str, signed_url_ttl: int = 600) -> None:
18
+ if not url or not key:
19
+ raise RuntimeError(
20
+ "SupabaseStorage requires SUPABASE_URL and SUPABASE_SERVICE_KEY"
21
+ )
22
  self.url = url
23
  self.key = key
24
  self.bucket = bucket
25
+ self.signed_url_ttl = signed_url_ttl
26
+ # Lazy import: avoids pulling the supabase SDK when the backend
27
+ # runs with PHOTO_STORAGE_BACKEND=local.
28
+ from supabase import create_client
29
+ self._client = create_client(url, key)
30
+
31
+ def _strip_url_prefix(self, path_or_url: str) -> str:
32
+ """Accept either a relative object path or a full Supabase URL and
33
+ return just the object path inside the bucket."""
34
+ marker = f"/storage/v1/object/"
35
+ if marker in path_or_url:
36
+ # Strip ".../storage/v1/object/{public|sign|auth}/{bucket}/"
37
+ tail = path_or_url.split(marker, 1)[1]
38
+ # tail: "{kind}/{bucket}/{rest...}"
39
+ parts = tail.split("/", 2)
40
+ if len(parts) == 3:
41
+ return parts[2].split("?", 1)[0] # drop query (signed token)
42
+ return path_or_url
43
 
44
  def upload(self, account_id: int, user_id: int, content: bytes, ext: str) -> str:
45
+ path = f"{account_id}/{user_id}/{uuid.uuid4()}.{ext}"
46
+ # `upsert` avoids collision errors on retry.
47
+ self._client.storage.from_(self.bucket).upload(
48
+ path,
49
+ content,
50
+ file_options={
51
+ "content-type": f"image/{ext}",
52
+ "upsert": "true",
53
+ },
54
  )
55
+ return path
56
 
57
  def delete(self, path_or_url: str) -> None:
58
+ path = self._strip_url_prefix(path_or_url)
59
+ try:
60
+ self._client.storage.from_(self.bucket).remove([path])
61
+ except Exception:
62
+ pass
63
 
64
  def get_url(self, path_or_url: str) -> str:
65
+ """Return a short-lived signed URL (default 10 min) for the object.
66
+
67
+ Pass-through if `path_or_url` already looks like an http(s) URL.
68
+ """
69
+ if path_or_url.startswith("http://") or path_or_url.startswith("https://"):
70
+ return path_or_url
71
+ path = self._strip_url_prefix(path_or_url)
72
+ res: Any = self._client.storage.from_(self.bucket).create_signed_url(
73
+ path, self.signed_url_ttl,
74
  )
75
+ # supabase-py 2.x returns {"signedURL": "..."} or {"signed_url": "..."}
76
+ if isinstance(res, dict):
77
+ return res.get("signedURL") or res.get("signed_url") or ""
78
+ return getattr(res, "signed_url", "") or getattr(res, "signedURL", "")
backend/requirements.txt CHANGED
@@ -20,3 +20,4 @@ openpyxl==3.1.5
20
  Pillow>=10.0.0
21
  python-magic>=0.4.27
22
  pytest>=9.0.0
 
 
20
  Pillow>=10.0.0
21
  python-magic>=0.4.27
22
  pytest>=9.0.0
23
+ supabase>=2.0.0
backend/tests/storage/test_supabase.py CHANGED
@@ -2,12 +2,37 @@ import pytest
2
  from app.storage.supabase import SupabaseStorage
3
 
4
 
5
- def test_upload_raises_until_credentials_arrive():
6
- storage = SupabaseStorage(url="", key="", bucket="user-photos")
7
- with pytest.raises(NotImplementedError, match="Supabase"):
8
- storage.upload(1, 1, b"x", "webp")
9
 
10
 
11
- def test_constructor_stores_config_without_calling_network():
 
 
 
 
 
12
  s = SupabaseStorage(url="https://example.supabase.co", key="k", bucket="b")
13
  assert s.bucket == "b"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from app.storage.supabase import SupabaseStorage
3
 
4
 
5
+ def test_constructor_rejects_missing_credentials():
6
+ with pytest.raises(RuntimeError, match="SUPABASE_URL"):
7
+ SupabaseStorage(url="", key="", bucket="user-photos")
 
8
 
9
 
10
+ def test_constructor_with_credentials_stores_config(monkeypatch):
11
+ # Avoid importing the real supabase SDK in unit tests by stubbing create_client.
12
+ import sys, types
13
+ fake = types.ModuleType("supabase")
14
+ fake.create_client = lambda url, key: object() # type: ignore[attr-defined]
15
+ monkeypatch.setitem(sys.modules, "supabase", fake)
16
  s = SupabaseStorage(url="https://example.supabase.co", key="k", bucket="b")
17
  assert s.bucket == "b"
18
+ assert s.url == "https://example.supabase.co"
19
+ assert s.signed_url_ttl == 600
20
+
21
+
22
+ def test_strip_url_prefix_handles_relative_path(monkeypatch):
23
+ import sys, types
24
+ fake = types.ModuleType("supabase")
25
+ fake.create_client = lambda url, key: object() # type: ignore[attr-defined]
26
+ monkeypatch.setitem(sys.modules, "supabase", fake)
27
+ s = SupabaseStorage(url="https://x.supabase.co", key="k", bucket="user-photos")
28
+ assert s._strip_url_prefix("1/2/abc.webp") == "1/2/abc.webp"
29
+
30
+
31
+ def test_strip_url_prefix_extracts_path_from_signed_url(monkeypatch):
32
+ import sys, types
33
+ fake = types.ModuleType("supabase")
34
+ fake.create_client = lambda url, key: object() # type: ignore[attr-defined]
35
+ monkeypatch.setitem(sys.modules, "supabase", fake)
36
+ s = SupabaseStorage(url="https://x.supabase.co", key="k", bucket="user-photos")
37
+ full = "https://x.supabase.co/storage/v1/object/sign/user-photos/1/2/abc.webp?token=xyz"
38
+ assert s._strip_url_prefix(full) == "1/2/abc.webp"
frontend/src/components/AuthImage.tsx CHANGED
@@ -27,8 +27,15 @@ export default function AuthImage({ src, fallback = null, ...imgProps }: AuthIma
27
  return;
28
  }
29
 
30
- // Pass-through for data: and blob: URLs.
31
- if (src.startsWith('data:') || src.startsWith('blob:')) {
 
 
 
 
 
 
 
32
  setBlobUrl(src);
33
  setError(false);
34
  return;
 
27
  return;
28
  }
29
 
30
+ // Pass-through for data: and blob: URLs, and for absolute http(s) URLs
31
+ // (e.g. Supabase signed URLs already carry their own auth token in the
32
+ // query string and are fetchable directly by the browser).
33
+ if (
34
+ src.startsWith('data:') ||
35
+ src.startsWith('blob:') ||
36
+ src.startsWith('http://') ||
37
+ src.startsWith('https://')
38
+ ) {
39
  setBlobUrl(src);
40
  setError(false);
41
  return;