authentik.admin.files.backends.s3
1from collections.abc import Generator, Iterator 2from contextlib import contextmanager 3from tempfile import SpooledTemporaryFile 4from typing import TYPE_CHECKING, Any, TypeVar 5from urllib.parse import urlsplit, urlunsplit 6 7from django.db import connection 8from django.http.request import HttpRequest 9 10from authentik.admin.files.backends.base import ManageableBackend, get_content_type 11from authentik.admin.files.usage import FileUsage 12from authentik.lib.config import CONFIG 13from authentik.lib.utils.time import timedelta_from_string 14 15if TYPE_CHECKING: 16 import boto3 17 18_ConfigValue = TypeVar("_ConfigValue") 19 20 21class S3Backend(ManageableBackend): 22 """S3-compatible object storage backend. 23 24 Stores files in s3-compatible storage: 25 - Key prefix: {usage}/{schema}/{filename} 26 - Supports full file management (upload, delete, list) 27 - Generates presigned URLs for file access 28 - Used when storage.backend=s3 29 """ 30 31 allowed_usages = list(FileUsage) # All usages 32 name = "s3" 33 34 def __init__(self, *args, **kwargs): 35 super().__init__(*args, **kwargs) 36 self._config = {} 37 self._session = None 38 self._client = None 39 40 def _remember_config(self, key: str, refreshed: _ConfigValue) -> tuple[_ConfigValue, bool]: 41 unset = object() 42 current = self._config.get(key, unset) 43 if current is unset: 44 current = refreshed 45 self._config[key] = refreshed 46 return refreshed, current != refreshed 47 48 def _get_config(self, key: str, default: Any) -> tuple[Any, bool]: 49 refreshed = CONFIG.refresh( 50 f"storage.{self.usage.value}.{self.name}.{key}", 51 CONFIG.refresh(f"storage.{self.name}.{key}", default), 52 ) 53 return self._remember_config(key, refreshed) 54 55 def _get_bool_config(self, key: str, default: bool) -> tuple[bool, bool]: 56 refreshed = CONFIG.get_bool( 57 f"storage.{self.usage.value}.{self.name}.{key}", 58 CONFIG.get_bool(f"storage.{self.name}.{key}", default), 59 ) 60 return self._remember_config(key, refreshed) 61 62 @property 63 def base_path(self) -> str: 64 """S3 key prefix: {usage}/{schema}/""" 65 return f"{self.usage.value}/{connection.schema_name}" 66 67 @property 68 def bucket_name(self) -> str: 69 return CONFIG.get( 70 f"storage.{self.usage.value}.{self.name}.bucket_name", 71 CONFIG.get(f"storage.{self.name}.bucket_name"), 72 ) 73 74 @property 75 def session(self) -> boto3.Session: 76 """Create boto3 session with configured credentials.""" 77 # boto3 is heavy, only import it when S3 is used 78 import boto3 79 80 session_profile, session_profile_r = self._get_config("session_profile", None) 81 if session_profile is not None: 82 if session_profile_r or self._session is None: 83 self._session = boto3.Session(profile_name=session_profile) 84 self._client = None 85 return self._session 86 else: 87 return self._session 88 else: 89 access_key, access_key_r = self._get_config("access_key", None) 90 secret_key, secret_key_r = self._get_config("secret_key", None) 91 session_token, session_token_r = self._get_config("session_token", None) 92 if access_key_r or secret_key_r or session_token_r or self._session is None: 93 self._session = boto3.Session( 94 aws_access_key_id=access_key, 95 aws_secret_access_key=secret_key, 96 aws_session_token=session_token, 97 ) 98 self._client = None 99 return self._session 100 else: 101 return self._session 102 103 @property 104 def client(self): 105 """Create S3 client with configured endpoint and region.""" 106 from botocore.config import Config 107 108 endpoint_url, endpoint_url_r = self._get_config("endpoint", None) 109 session = self.session 110 use_ssl, use_ssl_r = self._get_bool_config("use_ssl", True) 111 region_name, region_name_r = self._get_config("region", None) 112 addressing_style, addressing_style_r = self._get_config("addressing_style", "auto") 113 signature_version, signature_version_r = self._get_config("signature_version", "s3v4") 114 115 if self._client is not None and not any( 116 ( 117 endpoint_url_r, 118 use_ssl_r, 119 region_name_r, 120 addressing_style_r, 121 signature_version_r, 122 ) 123 ): 124 return self._client 125 # Keep signature_version pass-through and let boto3/botocore handle it. 126 # In boto3's S3 configuration docs, `s3v4` (default) and deprecated `s3` 127 # are the documented values: 128 # https://github.com/boto/boto3/blob/791a3e8f36d83664a47b4281a0586b3546cef3ec/docs/source/guide/configuration.rst?plain=1#L398-L407 129 # Botocore also supports additional signer names, so we intentionally do 130 # not enforce a restricted allowlist here. 131 132 self._client = session.client( 133 "s3", 134 endpoint_url=endpoint_url, 135 use_ssl=use_ssl, 136 region_name=region_name, 137 config=Config( 138 signature_version=signature_version, s3={"addressing_style": addressing_style} 139 ), 140 ) 141 return self._client 142 143 @property 144 def manageable(self) -> bool: 145 return True 146 147 def supports_file(self, name: str) -> bool: 148 """We support all files""" 149 return True 150 151 def list_files(self) -> Generator[str]: 152 """List all files returning relative paths from base_path.""" 153 paginator = self.client.get_paginator("list_objects_v2") 154 pages = paginator.paginate(Bucket=self.bucket_name, Prefix=f"{self.base_path}/") 155 156 for page in pages: 157 for obj in page.get("Contents", []): 158 key = obj["Key"] 159 # Remove base path prefix to get relative path 160 rel_path = key.removeprefix(f"{self.base_path}/") 161 if rel_path: # Skip if it's just the directory itself 162 yield rel_path 163 164 def file_url( 165 self, 166 name: str, 167 request: HttpRequest | None = None, 168 use_cache: bool = True, 169 ) -> str: 170 """Generate presigned URL for file access.""" 171 use_https = CONFIG.get_bool( 172 f"storage.{self.usage.value}.{self.name}.secure_urls", 173 CONFIG.get_bool(f"storage.{self.name}.secure_urls", True), 174 ) 175 176 expires_in = int( 177 timedelta_from_string( 178 CONFIG.get( 179 f"storage.{self.usage.value}.{self.name}.url_expiry", 180 CONFIG.get(f"storage.{self.name}.url_expiry", "minutes=15"), 181 ) 182 ).total_seconds() 183 ) 184 185 def _file_url(name: str, request: HttpRequest | None) -> str: 186 client = self.client 187 params = { 188 "Bucket": self.bucket_name, 189 "Key": f"{self.base_path}/{name}", 190 } 191 192 operation_name = "GetObject" 193 operation_model = client.meta.service_model.operation_model(operation_name) 194 request_dict = client._convert_to_request_dict( 195 params, 196 operation_model, 197 endpoint_url=client.meta.endpoint_url, 198 context={"is_presign_request": True}, 199 ) 200 201 # Support custom domain for S3-compatible storage (so not AWS) 202 # Well, can't you do custom domains on AWS as well? 203 custom_domain = CONFIG.get( 204 f"storage.{self.usage.value}.{self.name}.custom_domain", 205 CONFIG.get(f"storage.{self.name}.custom_domain", None), 206 ) 207 if custom_domain: 208 scheme = "https" if use_https else "http" 209 path = request_dict["url_path"] 210 211 # When using path-style addressing, the presigned URL contains the bucket 212 # name in the path (e.g., /bucket-name/key). Since custom_domain must 213 # include the bucket name (per docs), strip it from the path to avoid 214 # duplication. See: https://github.com/goauthentik/authentik/issues/19521 215 # Check with trailing slash to ensure exact bucket name match 216 if path.startswith(f"/{self.bucket_name}/"): 217 path = path.removeprefix(f"/{self.bucket_name}") 218 219 # Normalize to avoid double slashes 220 custom_domain = custom_domain.rstrip("/") 221 if not path.startswith("/"): 222 path = f"/{path}" 223 224 custom_base = urlsplit(f"{scheme}://{custom_domain}") 225 226 # Sign the final public URL instead of signing the internal S3 endpoint and 227 # rewriting it afterwards. Presigned SigV4 URLs include the host header in the 228 # canonical request, so post-sign host changes break strict backends like RustFS. 229 public_path = f"{custom_base.path.rstrip('/')}{path}" if custom_base.path else path 230 request_dict["url_path"] = public_path 231 request_dict["url"] = urlunsplit( 232 (custom_base.scheme, custom_base.netloc, public_path, "", "") 233 ) 234 235 return client._request_signer.generate_presigned_url( 236 request_dict, 237 operation_name, 238 expires_in=expires_in, 239 ) 240 241 if use_cache: 242 return self._cache_get_or_set(name, request, _file_url, expires_in) 243 else: 244 return _file_url(name, request) 245 246 def save_file(self, name: str, content: bytes) -> None: 247 """Save file to S3.""" 248 self.client.put_object( 249 Bucket=self.bucket_name, 250 Key=f"{self.base_path}/{name}", 251 Body=content, 252 ACL="private", 253 ContentType=get_content_type(name), 254 ) 255 256 @contextmanager 257 def save_file_stream(self, name: str) -> Iterator: 258 """Context manager for streaming file writes to S3.""" 259 # Keep files in memory up to 5 MB 260 with SpooledTemporaryFile(max_size=5 * 1024 * 1024, suffix=".S3File") as file: 261 yield file 262 file.seek(0) 263 self.client.upload_fileobj( 264 Fileobj=file, 265 Bucket=self.bucket_name, 266 Key=f"{self.base_path}/{name}", 267 ExtraArgs={ 268 "ACL": "private", 269 "ContentType": get_content_type(name), 270 }, 271 ) 272 273 def delete_file(self, name: str) -> None: 274 """Delete file from S3.""" 275 self.client.delete_object( 276 Bucket=self.bucket_name, 277 Key=f"{self.base_path}/{name}", 278 ) 279 280 def file_exists(self, name: str) -> bool: 281 """Check if a file exists in S3.""" 282 from botocore.exceptions import ClientError 283 284 try: 285 self.client.head_object( 286 Bucket=self.bucket_name, 287 Key=f"{self.base_path}/{name}", 288 ) 289 return True 290 except ClientError: 291 return False
22class S3Backend(ManageableBackend): 23 """S3-compatible object storage backend. 24 25 Stores files in s3-compatible storage: 26 - Key prefix: {usage}/{schema}/{filename} 27 - Supports full file management (upload, delete, list) 28 - Generates presigned URLs for file access 29 - Used when storage.backend=s3 30 """ 31 32 allowed_usages = list(FileUsage) # All usages 33 name = "s3" 34 35 def __init__(self, *args, **kwargs): 36 super().__init__(*args, **kwargs) 37 self._config = {} 38 self._session = None 39 self._client = None 40 41 def _remember_config(self, key: str, refreshed: _ConfigValue) -> tuple[_ConfigValue, bool]: 42 unset = object() 43 current = self._config.get(key, unset) 44 if current is unset: 45 current = refreshed 46 self._config[key] = refreshed 47 return refreshed, current != refreshed 48 49 def _get_config(self, key: str, default: Any) -> tuple[Any, bool]: 50 refreshed = CONFIG.refresh( 51 f"storage.{self.usage.value}.{self.name}.{key}", 52 CONFIG.refresh(f"storage.{self.name}.{key}", default), 53 ) 54 return self._remember_config(key, refreshed) 55 56 def _get_bool_config(self, key: str, default: bool) -> tuple[bool, bool]: 57 refreshed = CONFIG.get_bool( 58 f"storage.{self.usage.value}.{self.name}.{key}", 59 CONFIG.get_bool(f"storage.{self.name}.{key}", default), 60 ) 61 return self._remember_config(key, refreshed) 62 63 @property 64 def base_path(self) -> str: 65 """S3 key prefix: {usage}/{schema}/""" 66 return f"{self.usage.value}/{connection.schema_name}" 67 68 @property 69 def bucket_name(self) -> str: 70 return CONFIG.get( 71 f"storage.{self.usage.value}.{self.name}.bucket_name", 72 CONFIG.get(f"storage.{self.name}.bucket_name"), 73 ) 74 75 @property 76 def session(self) -> boto3.Session: 77 """Create boto3 session with configured credentials.""" 78 # boto3 is heavy, only import it when S3 is used 79 import boto3 80 81 session_profile, session_profile_r = self._get_config("session_profile", None) 82 if session_profile is not None: 83 if session_profile_r or self._session is None: 84 self._session = boto3.Session(profile_name=session_profile) 85 self._client = None 86 return self._session 87 else: 88 return self._session 89 else: 90 access_key, access_key_r = self._get_config("access_key", None) 91 secret_key, secret_key_r = self._get_config("secret_key", None) 92 session_token, session_token_r = self._get_config("session_token", None) 93 if access_key_r or secret_key_r or session_token_r or self._session is None: 94 self._session = boto3.Session( 95 aws_access_key_id=access_key, 96 aws_secret_access_key=secret_key, 97 aws_session_token=session_token, 98 ) 99 self._client = None 100 return self._session 101 else: 102 return self._session 103 104 @property 105 def client(self): 106 """Create S3 client with configured endpoint and region.""" 107 from botocore.config import Config 108 109 endpoint_url, endpoint_url_r = self._get_config("endpoint", None) 110 session = self.session 111 use_ssl, use_ssl_r = self._get_bool_config("use_ssl", True) 112 region_name, region_name_r = self._get_config("region", None) 113 addressing_style, addressing_style_r = self._get_config("addressing_style", "auto") 114 signature_version, signature_version_r = self._get_config("signature_version", "s3v4") 115 116 if self._client is not None and not any( 117 ( 118 endpoint_url_r, 119 use_ssl_r, 120 region_name_r, 121 addressing_style_r, 122 signature_version_r, 123 ) 124 ): 125 return self._client 126 # Keep signature_version pass-through and let boto3/botocore handle it. 127 # In boto3's S3 configuration docs, `s3v4` (default) and deprecated `s3` 128 # are the documented values: 129 # https://github.com/boto/boto3/blob/791a3e8f36d83664a47b4281a0586b3546cef3ec/docs/source/guide/configuration.rst?plain=1#L398-L407 130 # Botocore also supports additional signer names, so we intentionally do 131 # not enforce a restricted allowlist here. 132 133 self._client = session.client( 134 "s3", 135 endpoint_url=endpoint_url, 136 use_ssl=use_ssl, 137 region_name=region_name, 138 config=Config( 139 signature_version=signature_version, s3={"addressing_style": addressing_style} 140 ), 141 ) 142 return self._client 143 144 @property 145 def manageable(self) -> bool: 146 return True 147 148 def supports_file(self, name: str) -> bool: 149 """We support all files""" 150 return True 151 152 def list_files(self) -> Generator[str]: 153 """List all files returning relative paths from base_path.""" 154 paginator = self.client.get_paginator("list_objects_v2") 155 pages = paginator.paginate(Bucket=self.bucket_name, Prefix=f"{self.base_path}/") 156 157 for page in pages: 158 for obj in page.get("Contents", []): 159 key = obj["Key"] 160 # Remove base path prefix to get relative path 161 rel_path = key.removeprefix(f"{self.base_path}/") 162 if rel_path: # Skip if it's just the directory itself 163 yield rel_path 164 165 def file_url( 166 self, 167 name: str, 168 request: HttpRequest | None = None, 169 use_cache: bool = True, 170 ) -> str: 171 """Generate presigned URL for file access.""" 172 use_https = CONFIG.get_bool( 173 f"storage.{self.usage.value}.{self.name}.secure_urls", 174 CONFIG.get_bool(f"storage.{self.name}.secure_urls", True), 175 ) 176 177 expires_in = int( 178 timedelta_from_string( 179 CONFIG.get( 180 f"storage.{self.usage.value}.{self.name}.url_expiry", 181 CONFIG.get(f"storage.{self.name}.url_expiry", "minutes=15"), 182 ) 183 ).total_seconds() 184 ) 185 186 def _file_url(name: str, request: HttpRequest | None) -> str: 187 client = self.client 188 params = { 189 "Bucket": self.bucket_name, 190 "Key": f"{self.base_path}/{name}", 191 } 192 193 operation_name = "GetObject" 194 operation_model = client.meta.service_model.operation_model(operation_name) 195 request_dict = client._convert_to_request_dict( 196 params, 197 operation_model, 198 endpoint_url=client.meta.endpoint_url, 199 context={"is_presign_request": True}, 200 ) 201 202 # Support custom domain for S3-compatible storage (so not AWS) 203 # Well, can't you do custom domains on AWS as well? 204 custom_domain = CONFIG.get( 205 f"storage.{self.usage.value}.{self.name}.custom_domain", 206 CONFIG.get(f"storage.{self.name}.custom_domain", None), 207 ) 208 if custom_domain: 209 scheme = "https" if use_https else "http" 210 path = request_dict["url_path"] 211 212 # When using path-style addressing, the presigned URL contains the bucket 213 # name in the path (e.g., /bucket-name/key). Since custom_domain must 214 # include the bucket name (per docs), strip it from the path to avoid 215 # duplication. See: https://github.com/goauthentik/authentik/issues/19521 216 # Check with trailing slash to ensure exact bucket name match 217 if path.startswith(f"/{self.bucket_name}/"): 218 path = path.removeprefix(f"/{self.bucket_name}") 219 220 # Normalize to avoid double slashes 221 custom_domain = custom_domain.rstrip("/") 222 if not path.startswith("/"): 223 path = f"/{path}" 224 225 custom_base = urlsplit(f"{scheme}://{custom_domain}") 226 227 # Sign the final public URL instead of signing the internal S3 endpoint and 228 # rewriting it afterwards. Presigned SigV4 URLs include the host header in the 229 # canonical request, so post-sign host changes break strict backends like RustFS. 230 public_path = f"{custom_base.path.rstrip('/')}{path}" if custom_base.path else path 231 request_dict["url_path"] = public_path 232 request_dict["url"] = urlunsplit( 233 (custom_base.scheme, custom_base.netloc, public_path, "", "") 234 ) 235 236 return client._request_signer.generate_presigned_url( 237 request_dict, 238 operation_name, 239 expires_in=expires_in, 240 ) 241 242 if use_cache: 243 return self._cache_get_or_set(name, request, _file_url, expires_in) 244 else: 245 return _file_url(name, request) 246 247 def save_file(self, name: str, content: bytes) -> None: 248 """Save file to S3.""" 249 self.client.put_object( 250 Bucket=self.bucket_name, 251 Key=f"{self.base_path}/{name}", 252 Body=content, 253 ACL="private", 254 ContentType=get_content_type(name), 255 ) 256 257 @contextmanager 258 def save_file_stream(self, name: str) -> Iterator: 259 """Context manager for streaming file writes to S3.""" 260 # Keep files in memory up to 5 MB 261 with SpooledTemporaryFile(max_size=5 * 1024 * 1024, suffix=".S3File") as file: 262 yield file 263 file.seek(0) 264 self.client.upload_fileobj( 265 Fileobj=file, 266 Bucket=self.bucket_name, 267 Key=f"{self.base_path}/{name}", 268 ExtraArgs={ 269 "ACL": "private", 270 "ContentType": get_content_type(name), 271 }, 272 ) 273 274 def delete_file(self, name: str) -> None: 275 """Delete file from S3.""" 276 self.client.delete_object( 277 Bucket=self.bucket_name, 278 Key=f"{self.base_path}/{name}", 279 ) 280 281 def file_exists(self, name: str) -> bool: 282 """Check if a file exists in S3.""" 283 from botocore.exceptions import ClientError 284 285 try: 286 self.client.head_object( 287 Bucket=self.bucket_name, 288 Key=f"{self.base_path}/{name}", 289 ) 290 return True 291 except ClientError: 292 return False
S3-compatible object storage backend.
Stores files in s3-compatible storage:
- Key prefix: {usage}/{schema}/{filename}
- Supports full file management (upload, delete, list)
- Generates presigned URLs for file access
- Used when storage.backend=s3
S3Backend(*args, **kwargs)
35 def __init__(self, *args, **kwargs): 36 super().__init__(*args, **kwargs) 37 self._config = {} 38 self._session = None 39 self._client = None
Initialize backend for the given usage type.
Args: usage: FileUsage type enum value
base_path: str
63 @property 64 def base_path(self) -> str: 65 """S3 key prefix: {usage}/{schema}/""" 66 return f"{self.usage.value}/{connection.schema_name}"
S3 key prefix: {usage}/{schema}/
session
75 @property 76 def session(self) -> boto3.Session: 77 """Create boto3 session with configured credentials.""" 78 # boto3 is heavy, only import it when S3 is used 79 import boto3 80 81 session_profile, session_profile_r = self._get_config("session_profile", None) 82 if session_profile is not None: 83 if session_profile_r or self._session is None: 84 self._session = boto3.Session(profile_name=session_profile) 85 self._client = None 86 return self._session 87 else: 88 return self._session 89 else: 90 access_key, access_key_r = self._get_config("access_key", None) 91 secret_key, secret_key_r = self._get_config("secret_key", None) 92 session_token, session_token_r = self._get_config("session_token", None) 93 if access_key_r or secret_key_r or session_token_r or self._session is None: 94 self._session = boto3.Session( 95 aws_access_key_id=access_key, 96 aws_secret_access_key=secret_key, 97 aws_session_token=session_token, 98 ) 99 self._client = None 100 return self._session 101 else: 102 return self._session
Create boto3 session with configured credentials.
client
104 @property 105 def client(self): 106 """Create S3 client with configured endpoint and region.""" 107 from botocore.config import Config 108 109 endpoint_url, endpoint_url_r = self._get_config("endpoint", None) 110 session = self.session 111 use_ssl, use_ssl_r = self._get_bool_config("use_ssl", True) 112 region_name, region_name_r = self._get_config("region", None) 113 addressing_style, addressing_style_r = self._get_config("addressing_style", "auto") 114 signature_version, signature_version_r = self._get_config("signature_version", "s3v4") 115 116 if self._client is not None and not any( 117 ( 118 endpoint_url_r, 119 use_ssl_r, 120 region_name_r, 121 addressing_style_r, 122 signature_version_r, 123 ) 124 ): 125 return self._client 126 # Keep signature_version pass-through and let boto3/botocore handle it. 127 # In boto3's S3 configuration docs, `s3v4` (default) and deprecated `s3` 128 # are the documented values: 129 # https://github.com/boto/boto3/blob/791a3e8f36d83664a47b4281a0586b3546cef3ec/docs/source/guide/configuration.rst?plain=1#L398-L407 130 # Botocore also supports additional signer names, so we intentionally do 131 # not enforce a restricted allowlist here. 132 133 self._client = session.client( 134 "s3", 135 endpoint_url=endpoint_url, 136 use_ssl=use_ssl, 137 region_name=region_name, 138 config=Config( 139 signature_version=signature_version, s3={"addressing_style": addressing_style} 140 ), 141 ) 142 return self._client
Create S3 client with configured endpoint and region.
manageable: bool
Whether this backend can actually be used for management.
Used only for management check, not for created the backend
def
list_files(self) -> Generator[str]:
152 def list_files(self) -> Generator[str]: 153 """List all files returning relative paths from base_path.""" 154 paginator = self.client.get_paginator("list_objects_v2") 155 pages = paginator.paginate(Bucket=self.bucket_name, Prefix=f"{self.base_path}/") 156 157 for page in pages: 158 for obj in page.get("Contents", []): 159 key = obj["Key"] 160 # Remove base path prefix to get relative path 161 rel_path = key.removeprefix(f"{self.base_path}/") 162 if rel_path: # Skip if it's just the directory itself 163 yield rel_path
List all files returning relative paths from base_path.
def
file_url( self, name: str, request: django.http.request.HttpRequest | None = None, use_cache: bool = True) -> str:
165 def file_url( 166 self, 167 name: str, 168 request: HttpRequest | None = None, 169 use_cache: bool = True, 170 ) -> str: 171 """Generate presigned URL for file access.""" 172 use_https = CONFIG.get_bool( 173 f"storage.{self.usage.value}.{self.name}.secure_urls", 174 CONFIG.get_bool(f"storage.{self.name}.secure_urls", True), 175 ) 176 177 expires_in = int( 178 timedelta_from_string( 179 CONFIG.get( 180 f"storage.{self.usage.value}.{self.name}.url_expiry", 181 CONFIG.get(f"storage.{self.name}.url_expiry", "minutes=15"), 182 ) 183 ).total_seconds() 184 ) 185 186 def _file_url(name: str, request: HttpRequest | None) -> str: 187 client = self.client 188 params = { 189 "Bucket": self.bucket_name, 190 "Key": f"{self.base_path}/{name}", 191 } 192 193 operation_name = "GetObject" 194 operation_model = client.meta.service_model.operation_model(operation_name) 195 request_dict = client._convert_to_request_dict( 196 params, 197 operation_model, 198 endpoint_url=client.meta.endpoint_url, 199 context={"is_presign_request": True}, 200 ) 201 202 # Support custom domain for S3-compatible storage (so not AWS) 203 # Well, can't you do custom domains on AWS as well? 204 custom_domain = CONFIG.get( 205 f"storage.{self.usage.value}.{self.name}.custom_domain", 206 CONFIG.get(f"storage.{self.name}.custom_domain", None), 207 ) 208 if custom_domain: 209 scheme = "https" if use_https else "http" 210 path = request_dict["url_path"] 211 212 # When using path-style addressing, the presigned URL contains the bucket 213 # name in the path (e.g., /bucket-name/key). Since custom_domain must 214 # include the bucket name (per docs), strip it from the path to avoid 215 # duplication. See: https://github.com/goauthentik/authentik/issues/19521 216 # Check with trailing slash to ensure exact bucket name match 217 if path.startswith(f"/{self.bucket_name}/"): 218 path = path.removeprefix(f"/{self.bucket_name}") 219 220 # Normalize to avoid double slashes 221 custom_domain = custom_domain.rstrip("/") 222 if not path.startswith("/"): 223 path = f"/{path}" 224 225 custom_base = urlsplit(f"{scheme}://{custom_domain}") 226 227 # Sign the final public URL instead of signing the internal S3 endpoint and 228 # rewriting it afterwards. Presigned SigV4 URLs include the host header in the 229 # canonical request, so post-sign host changes break strict backends like RustFS. 230 public_path = f"{custom_base.path.rstrip('/')}{path}" if custom_base.path else path 231 request_dict["url_path"] = public_path 232 request_dict["url"] = urlunsplit( 233 (custom_base.scheme, custom_base.netloc, public_path, "", "") 234 ) 235 236 return client._request_signer.generate_presigned_url( 237 request_dict, 238 operation_name, 239 expires_in=expires_in, 240 ) 241 242 if use_cache: 243 return self._cache_get_or_set(name, request, _file_url, expires_in) 244 else: 245 return _file_url(name, request)
Generate presigned URL for file access.
def
save_file(self, name: str, content: bytes) -> None:
247 def save_file(self, name: str, content: bytes) -> None: 248 """Save file to S3.""" 249 self.client.put_object( 250 Bucket=self.bucket_name, 251 Key=f"{self.base_path}/{name}", 252 Body=content, 253 ACL="private", 254 ContentType=get_content_type(name), 255 )
Save file to S3.
@contextmanager
def
save_file_stream(self, name: str) -> Iterator:
257 @contextmanager 258 def save_file_stream(self, name: str) -> Iterator: 259 """Context manager for streaming file writes to S3.""" 260 # Keep files in memory up to 5 MB 261 with SpooledTemporaryFile(max_size=5 * 1024 * 1024, suffix=".S3File") as file: 262 yield file 263 file.seek(0) 264 self.client.upload_fileobj( 265 Fileobj=file, 266 Bucket=self.bucket_name, 267 Key=f"{self.base_path}/{name}", 268 ExtraArgs={ 269 "ACL": "private", 270 "ContentType": get_content_type(name), 271 }, 272 )
Context manager for streaming file writes to S3.
def
delete_file(self, name: str) -> None:
274 def delete_file(self, name: str) -> None: 275 """Delete file from S3.""" 276 self.client.delete_object( 277 Bucket=self.bucket_name, 278 Key=f"{self.base_path}/{name}", 279 )
Delete file from S3.
def
file_exists(self, name: str) -> bool:
281 def file_exists(self, name: str) -> bool: 282 """Check if a file exists in S3.""" 283 from botocore.exceptions import ClientError 284 285 try: 286 self.client.head_object( 287 Bucket=self.bucket_name, 288 Key=f"{self.base_path}/{name}", 289 ) 290 return True 291 except ClientError: 292 return False
Check if a file exists in S3.