Spaces:
Runtime error

File size: 7,297 Bytes
de8b836
5cb387e
 
de8b836
f2fc66c
5cb387e
f2fc66c
5eeb2b8
f2fc66c
f3518c5
 
cd70b5d
f3518c5
5cb387e
f3518c5
 
 
5cb387e
de8b836
d4a9626
 
5cb387e
 
 
d4a9626
 
 
5eeb2b8
 
 
 
d4a9626
 
 
 
 
 
 
 
5cb387e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eeb2b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94102a3
5eeb2b8
94102a3
5eeb2b8
 
 
 
 
 
 
 
 
94102a3
5eeb2b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94102a3
5eeb2b8
 
 
 
 
 
 
 
 
5cb387e
d4a9626
5cb387e
 
 
d4a9626
5cb387e
 
 
 
 
d4a9626
 
 
 
 
 
 
 
 
 
 
 
 
 
5cb387e
 
 
 
 
f3518c5
 
f2fc66c
cd70b5d
f2fc66c
 
 
 
cd70b5d
77830e0
 
f3518c5
 
 
de8b836
 
 
 
 
f2fc66c
 
 
 
d4a9626
 
 
 
 
 
f2fc66c
 
f3518c5
5eeb2b8
f3518c5
 
4f6a1a5
 
 
5eeb2b8
 
 
 
 
f3518c5
f6e5c22
 
 
5eeb2b8
 
f3518c5
5eeb2b8
f3518c5
 
 
 
 
 
 
6c09e56
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import asyncio
import hashlib
import hmac
import os
import tempfile
import time
from pathlib import Path
from urllib.parse import unquote

from fastapi import Depends, FastAPI, HTTPException, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import ORJSONResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from loguru import logger

from ..utils import g_config

# Persistent directory for storing generated images
# Support environment variable override for Docker/HF deployments
# Directory will be created on first access to avoid import-time failures
_IMAGE_STORE_DIR: Path | None = None


def get_image_store_dir() -> Path:
    """Returns a persistent directory for storing images. Creates it if it doesn't exist."""
    global _IMAGE_STORE_DIR
    if _IMAGE_STORE_DIR is None:
        _IMAGE_STORE_DIR = (
            Path(os.getenv("GEMINI_IMAGE_STORE_PATH", tempfile.gettempdir()))
            / "ai_generated_images"
        )
        try:
            _IMAGE_STORE_DIR.mkdir(parents=True, exist_ok=True)
        except OSError as e:
            logger.error(f"Failed to create image store directory at {_IMAGE_STORE_DIR}: {e}")
            logger.warning("Falling back to system temp directory")
            _IMAGE_STORE_DIR = Path(tempfile.gettempdir()) / "ai_generated_images"
            _IMAGE_STORE_DIR.mkdir(parents=True, exist_ok=True)
    return _IMAGE_STORE_DIR


def get_image_token(filename: str) -> str:
    """Generate a HMAC-SHA256 token for a filename using the API key."""
    secret = g_config.server.api_key
    if not secret:
        return ""

    msg = filename.encode("utf-8")
    secret_bytes = secret.encode("utf-8")
    return hmac.new(secret_bytes, msg, hashlib.sha256).hexdigest()


def verify_image_token(filename: str, token: str | None) -> bool:
    """Verify the provided token against the filename."""
    expected = get_image_token(filename)
    if not expected:
        return True  # No auth required
    if not token:
        return False
    return hmac.compare_digest(token, expected)


def get_frontend_session_secret() -> str:
    """
    Return the secret used to sign built-in frontend session tokens.

    Priority:
    1. Explicit environment override
    2. API key (if configured)
    3. Empty string (frontend session auth disabled)
    """
    explicit_secret = os.getenv("GEMINI_FRONTEND_SESSION_SECRET", "").strip()
    if explicit_secret:
        return explicit_secret

    return g_config.server.api_key or ""


def create_frontend_session_token(user_agent: str | None = None) -> str:
    """
    Create a signed session token for the built-in frontend.

    The token format is:
        <session-id>.<signature>

    The signature is HMAC-SHA256 over the session id only.
    """
    secret = get_frontend_session_secret()
    if not secret:
        return ""

    session_id = hashlib.sha256(
        f"{time.time_ns()}:{os.getpid()}:{tempfile.gettempdir()}".encode("utf-8")
    ).hexdigest()

    payload = session_id.encode("utf-8")
    signature = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
    return f"{session_id}.{signature}"


def verify_frontend_session_token(token: str | None, user_agent: str | None = None) -> bool:
    """
    Verify a built-in frontend session token.

    If no secret is configured, this verifier returns False so callers can decide
    whether to require frontend-session auth explicitly.
    """
    secret = get_frontend_session_secret()
    if not secret or not token:
        return False

    raw_token = unquote(token).strip()
    if "." not in raw_token:
        return False

    session_id, provided_signature = raw_token.split(".", 1)
    if not session_id or not provided_signature:
        return False

    payload = session_id.encode("utf-8")
    expected_signature = hmac.new(
        secret.encode("utf-8"),
        payload,
        hashlib.sha256,
    ).hexdigest()

    return hmac.compare_digest(provided_signature, expected_signature)


def cleanup_expired_images(retention_days: int) -> int:
    """Delete images in image store directory older than retention_days."""
    if retention_days <= 0:
        return 0

    image_store_dir = get_image_store_dir()
    now = time.time()
    retention_seconds = retention_days * 24 * 60 * 60
    cutoff = now - retention_seconds

    count = 0
    try:
        for file_path in image_store_dir.iterdir():
            if not file_path.is_file():
                continue
            try:
                if file_path.stat().st_mtime < cutoff:
                    file_path.unlink()
                    count += 1
            except Exception as e:
                logger.warning(f"Failed to delete expired image {file_path}: {e}")
    except FileNotFoundError:
        logger.debug(f"Image store directory does not exist yet: {image_store_dir}")
    except Exception as e:
        logger.warning(f"Failed to cleanup expired images: {e}")

    if count > 0:
        logger.info(f"Cleaned up {count} expired images.")
    return count


def global_exception_handler(request: Request, exc: Exception):
    if isinstance(exc, HTTPException):
        return ORJSONResponse(
            status_code=exc.status_code,
            content={"error": {"message": exc.detail}},
        )

    return ORJSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={"error": {"message": str(exc)}},
    )


async def get_temp_dir():
    """
    Async context manager for temporary directory.
    Ensures cleanup even if request handling fails.
    """
    temp_dir = tempfile.TemporaryDirectory()
    try:
        yield Path(temp_dir.name)
    finally:
        # Run cleanup in thread pool to avoid blocking (Python 3.9+)
        try:
            await asyncio.to_thread(temp_dir.cleanup)
        except AttributeError:
            # Fallback for Python < 3.9
            await asyncio.get_running_loop().run_in_executor(None, temp_dir.cleanup)


def verify_api_key(
    request: Request,
    credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer(auto_error=False)),
):
    if not g_config.server.api_key:
        return ""

    if credentials is not None and credentials.scheme.lower() == "bearer":
        api_key = credentials.credentials
        if api_key != g_config.server.api_key:
            raise HTTPException(status.HTTP_403_FORBIDDEN, detail="Wrong API key")
        return api_key

    frontend_session = request.headers.get("x-frontend-session") or request.cookies.get(
        "gemini_frontend_session"
    )
    if verify_frontend_session_token(frontend_session, request.headers.get("user-agent")):
        return "frontend-session"

    raise HTTPException(status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing token")


def add_exception_handler(app: FastAPI):
    app.add_exception_handler(Exception, global_exception_handler)


def add_cors_middleware(app: FastAPI):
    if g_config.cors.enabled:
        cors = g_config.cors
        app.add_middleware(
            CORSMiddleware,
            allow_origins=cors.allow_origins,
            allow_credentials=cors.allow_credentials,
            allow_methods=cors.allow_methods,
            allow_headers=cors.allow_headers,
        )