bimquery-api / app /core /s3.py
BIM Query Deploy
deploy: pick up R2/health/alembic/celery fixes from monorepo
0917996
Raw History Blame Contribute Delete
14.1 kB
# Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
S3 storage configuration and utilities
"""
import hashlib
import logging
from typing import AsyncGenerator, Optional, BinaryIO
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
from botocore.config import Config
from app.core.config import get_settings
logger = logging.getLogger(__name__)
settings = get_settings()
# Global S3 client
s3_client = None
def init_s3():
"""Initialize S3 client"""
global s3_client
logger.info(f"Initializing S3 client: {settings.S3_ENDPOINT} (bucket: {settings.S3_BUCKET})")
try:
# Cloudflare R2 only accepts SigV4 and ignores any region except
# "auto"; virtual-hosted addressing works because boto3 prefixes
# the bucket onto the configured endpoint host. Setting these
# explicitly here means R2, MinIO, Backblaze and AWS itself can
# all share the same code path.
s3_config = Config(
region_name=settings.S3_REGION,
retries={'max_attempts': 3},
max_pool_connections=50,
connect_timeout=10,
read_timeout=60,
signature_version='s3v4',
s3={'addressing_style': 'virtual'},
)
# endpoint_url must always be passed when set, regardless of TLS.
# The previous logic (`if not S3_SECURE else None`) zeroed out the
# endpoint exactly when it was most needed β€” i.e. for managed S3
# backends like Cloudflare R2 that are HTTPS and have a custom
# endpoint host. With endpoint_url=None boto3 falls back to AWS,
# so head_bucket tries '<bucket>.s3.<region>.amazonaws.com' and
# DNS-fails. `use_ssl` is the right knob for HTTP vs HTTPS.
s3_client = boto3.client(
's3',
endpoint_url=settings.S3_ENDPOINT or None,
aws_access_key_id=settings.S3_ACCESS_KEY,
aws_secret_access_key=settings.S3_SECRET_KEY,
region_name=settings.S3_REGION,
config=s3_config,
use_ssl=settings.S3_SECURE,
)
# Test connection by listing buckets
s3_client.head_bucket(Bucket=settings.S3_BUCKET)
logger.info("βœ… S3 client initialized successfully")
except (ClientError, NoCredentialsError) as e:
logger.error(f"❌ S3 initialization failed: {e}")
raise
def get_s3_client():
"""Get S3 client"""
if not s3_client:
raise RuntimeError("S3 client not initialized")
return s3_client
class S3StorageService:
"""S3 storage operations"""
@staticmethod
def get_object_key(project_id: str, filename: str) -> str:
"""Generate S3 object key for project file"""
# Use project_id as prefix for organization
return f"projects/{project_id}/files/{filename}"
@staticmethod
async def upload_file_stream(
file_stream: BinaryIO,
project_id: str,
filename: str,
content_type: str = "application/octet-stream"
) -> tuple[str, str, int]:
"""
Upload file stream to S3 with SHA256 calculation
Returns: (object_key, sha256_hash, file_size)
"""
client = get_s3_client()
object_key = S3StorageService.get_object_key(project_id, filename)
# Read file content and calculate hash
file_content = file_stream.read()
file_size = len(file_content)
sha256_hash = hashlib.sha256(file_content).hexdigest()
logger.info(
f"Uploading file to S3: {object_key} "
f"(size: {file_size} bytes, sha256: {sha256_hash})"
)
try:
# Upload to S3
client.put_object(
Bucket=settings.S3_BUCKET,
Key=object_key,
Body=file_content,
ContentType=content_type,
Metadata={
'original_filename': filename,
'project_id': project_id,
'sha256': sha256_hash,
'uploaded_by': 'bim-query'
}
)
logger.info(f"βœ… File uploaded successfully: {object_key}")
return object_key, sha256_hash, file_size
except ClientError as e:
logger.error(f"❌ S3 upload failed for {object_key}: {e}")
raise
@staticmethod
async def upload_file_chunked(
file_stream: AsyncGenerator[bytes, None],
project_id: str,
filename: str,
content_type: str = "application/octet-stream",
chunk_size: int = 8 * 1024 * 1024 # 8MB chunks
) -> tuple[str, str, int]:
"""
Upload large file using multipart upload
Returns: (object_key, sha256_hash, file_size)
"""
client = get_s3_client()
object_key = S3StorageService.get_object_key(project_id, filename)
logger.info(f"Starting multipart upload: {object_key}")
try:
# Initialize multipart upload
multipart_response = client.create_multipart_upload(
Bucket=settings.S3_BUCKET,
Key=object_key,
ContentType=content_type,
Metadata={
'original_filename': filename,
'project_id': project_id,
'uploaded_by': 'bim-query'
}
)
upload_id = multipart_response['UploadId']
parts = []
part_number = 1
total_size = 0
hasher = hashlib.sha256()
try:
# Upload parts
async for chunk in file_stream:
if len(chunk) == 0:
break
total_size += len(chunk)
hasher.update(chunk)
# Upload part
part_response = client.upload_part(
Bucket=settings.S3_BUCKET,
Key=object_key,
PartNumber=part_number,
UploadId=upload_id,
Body=chunk
)
parts.append({
'ETag': part_response['ETag'],
'PartNumber': part_number
})
part_number += 1
logger.debug(f"Uploaded part {part_number-1}, total size: {total_size}")
# Complete multipart upload
client.complete_multipart_upload(
Bucket=settings.S3_BUCKET,
Key=object_key,
UploadId=upload_id,
MultipartUpload={'Parts': parts}
)
sha256_hash = hasher.hexdigest()
logger.info(f"βœ… Multipart upload completed: {object_key} ({total_size} bytes)")
# Update metadata with hash
client.copy_object(
Bucket=settings.S3_BUCKET,
Key=object_key,
CopySource={'Bucket': settings.S3_BUCKET, 'Key': object_key},
Metadata={
'original_filename': filename,
'project_id': project_id,
'sha256': sha256_hash,
'uploaded_by': 'bim-query'
},
MetadataDirective='REPLACE'
)
return object_key, sha256_hash, total_size
except Exception as e:
# Abort multipart upload on error
try:
client.abort_multipart_upload(
Bucket=settings.S3_BUCKET,
Key=object_key,
UploadId=upload_id
)
logger.info(f"Aborted multipart upload: {upload_id}")
except (ClientError, Exception) as abort_err:
logger.warning(f"Failed to abort multipart upload: {abort_err}")
raise
except ClientError as e:
logger.error(f"❌ Multipart upload failed for {object_key}: {e}")
raise
@staticmethod
def download_file(project_id: str, filename: str) -> bytes:
"""Download file from S3"""
client = get_s3_client()
object_key = S3StorageService.get_object_key(project_id, filename)
try:
logger.info(f"Downloading file from S3: {object_key}")
response = client.get_object(Bucket=settings.S3_BUCKET, Key=object_key)
return response['Body'].read()
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchKey':
logger.error(f"File not found in S3: {object_key}")
raise FileNotFoundError(f"File not found: {object_key}")
else:
logger.error(f"❌ S3 download failed for {object_key}: {e}")
raise
@staticmethod
def download_file_by_key(s3_key: str) -> bytes:
"""Download file from S3 using direct S3 key
Validates that the key is within the allowed projects/ prefix
to prevent path traversal attacks.
"""
# Validate key prefix to prevent path traversal
if not s3_key.startswith("projects/") or ".." in s3_key:
raise ValueError(f"Invalid S3 key: access denied")
client = get_s3_client()
try:
logger.info(f"Downloading file from S3: {s3_key}")
response = client.get_object(Bucket=settings.S3_BUCKET, Key=s3_key)
return response['Body'].read()
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchKey':
logger.error(f"File not found in S3: {s3_key}")
raise FileNotFoundError(f"File not found: {s3_key}")
else:
logger.error(f"❌ S3 download failed for {s3_key}: {e}")
raise
@staticmethod
def get_file_info(project_id: str, filename: str) -> dict:
"""Get file metadata from S3"""
client = get_s3_client()
object_key = S3StorageService.get_object_key(project_id, filename)
try:
response = client.head_object(Bucket=settings.S3_BUCKET, Key=object_key)
return {
'size': response['ContentLength'],
'last_modified': response['LastModified'],
'content_type': response['ContentType'],
'metadata': response.get('Metadata', {}),
'etag': response['ETag'].strip('"')
}
except ClientError as e:
if e.response['Error']['Code'] == '404':
logger.error(f"File not found in S3: {object_key}")
raise FileNotFoundError(f"File not found: {object_key}")
else:
logger.error(f"❌ S3 head_object failed for {object_key}: {e}")
raise
@staticmethod
def delete_file(project_id: str, filename: str) -> bool:
"""Delete file from S3"""
client = get_s3_client()
object_key = S3StorageService.get_object_key(project_id, filename)
try:
client.delete_object(Bucket=settings.S3_BUCKET, Key=object_key)
logger.info(f"βœ… File deleted from S3: {object_key}")
return True
except ClientError as e:
logger.error(f"❌ S3 delete failed for {object_key}: {e}")
return False
@staticmethod
def list_project_files(project_id: str) -> list:
"""List all files for a project"""
client = get_s3_client()
prefix = f"projects/{project_id}/files/"
try:
response = client.list_objects_v2(
Bucket=settings.S3_BUCKET,
Prefix=prefix
)
files = []
for obj in response.get('Contents', []):
# Extract filename from key
filename = obj['Key'].replace(prefix, '')
files.append({
'filename': filename,
'size': obj['Size'],
'last_modified': obj['LastModified'],
'etag': obj['ETag'].strip('"')
})
return files
except ClientError as e:
logger.error(f"❌ S3 list failed for project {project_id}: {e}")
return []
@staticmethod
def generate_presigned_url(
project_id: str,
filename: str,
expiration: int = 3600,
http_method: str = 'GET'
) -> str:
"""Generate presigned URL for file access"""
# Validate http_method to prevent abuse
allowed_methods = {'GET', 'PUT'}
if http_method.upper() not in allowed_methods:
raise ValueError(f"Unsupported HTTP method for presigned URL: {http_method}")
# Cap expiration to 1 hour max
expiration = min(expiration, 3600)
client = get_s3_client()
object_key = S3StorageService.get_object_key(project_id, filename)
try:
url = client.generate_presigned_url(
http_method.lower() + '_object',
Params={'Bucket': settings.S3_BUCKET, 'Key': object_key},
ExpiresIn=expiration
)
return url
except ClientError as e:
logger.error(f"❌ Presigned URL generation failed for {object_key}: {e}")
raise