File size: 4,219 Bytes
30698e9
2c8882f
 
302fbfe
a1c5ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30698e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a6568
30698e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1c5ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from datetime import datetime, timedelta
import jwt

# ===================== Rate Limiting =====================

class RateLimiter:
    """Simple in-memory rate limiter"""
    def __init__(self):
        self.requests = {}  # {key: [(timestamp, count)]}
        self.lock = threading.Lock()
    
    def is_allowed(self, key: str, max_requests: int, window_seconds: int) -> bool:
        """Check if request is allowed"""
        with self.lock:
            now = datetime.now(timezone.utc)
            
            if key not in self.requests:
                self.requests[key] = []
            
            # Remove old entries
            cutoff = now.timestamp() - window_seconds
            self.requests[key] = [
                (ts, count) for ts, count in self.requests[key]
                if ts > cutoff
            ]
            
            # Count requests in window
            total = sum(count for _, count in self.requests[key])
            
            if total >= max_requests:
                return False
            
            # Add this request
            self.requests[key].append((now.timestamp(), 1))
            return True
    
    def reset(self, key: str):
        """Reset rate limit for key"""
        with self.lock:
            if key in self.requests:
                del self.requests[key]

# Create global rate limiter instance
import threading
rate_limiter = RateLimiter()

# ===================== JWT Config =====================
def get_jwt_config():
    """Get JWT configuration based on environment"""
    # Check if we're in HuggingFace Space
    if os.getenv("SPACE_ID"):
        # Cloud mode - use secrets from environment
        jwt_secret = os.getenv("JWT_SECRET")
        if not jwt_secret:
            log("⚠️  WARNING: JWT_SECRET not found in environment, using fallback")
            jwt_secret = "flare-admin-secret-key-change-in-production"  # Fallback
    else:
        # On-premise mode - use .env file
        from dotenv import load_dotenv
        load_dotenv()
        jwt_secret = os.getenv("JWT_SECRET", "flare-admin-secret-key-change-in-production")
    
    return {
        "secret": jwt_secret,
        "algorithm": os.getenv("JWT_ALGORITHM", "HS256"),
        "expiration_hours": int(os.getenv("JWT_EXPIRATION_HOURS", "24"))
    }

# ===================== Auth Helpers =====================
def create_token(username: str) -> str:
    """Create JWT token for user"""
    config = get_jwt_config()
    expiry = datetime.now(timezone.utc) + timedelta(hours=config["expiration_hours"])
    
    payload = {
        "sub": username,
        "exp": expiry,
        "iat": datetime.now(timezone.utc)
    }
    
    return jwt.encode(payload, config["secret"], algorithm=config["algorithm"])

def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str:
    """Verify JWT token and return username"""
    token = credentials.credentials
    config = get_jwt_config()
    
    try:
        payload = jwt.decode(token, config["secret"], algorithms=[config["algorithm"]])
        return payload["sub"]
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")

# ===================== Utility Functions =====================

def truncate_string(text: str, max_length: int = 100, suffix: str = "...") -> str:
    """Truncate string to max length"""
    if len(text) <= max_length:
        return text
    return text[:max_length - len(suffix)] + suffix

def format_file_size(size_bytes: int) -> str:
    """Format file size in human readable format"""
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size_bytes < 1024.0:
            return f"{size_bytes:.2f} {unit}"
        size_bytes /= 1024.0
    return f"{size_bytes:.2f} PB"

def is_safe_path(path: str, base_path: str) -> bool:
    """Check if path is safe (no directory traversal)"""
    import os
    # Resolve to absolute paths
    base = os.path.abspath(base_path)
    target = os.path.abspath(os.path.join(base, path))
    
    # Check if target is under base
    return target.startswith(base)