authentik.admin.files.manager

  1from collections.abc import Generator, Iterable, Iterator
  2from contextlib import contextmanager
  3
  4from django.core.cache import cache
  5from django.core.exceptions import ImproperlyConfigured
  6from django.db import DatabaseError
  7from django.http.request import HttpRequest
  8from rest_framework.request import Request
  9from structlog.stdlib import get_logger
 10
 11from authentik.admin.files.backends.base import (
 12    PREFETCHED_URLS,
 13    ManageableBackend,
 14    get_valid_themes,
 15    has_theme_variable,
 16    substitute_theme,
 17)
 18from authentik.admin.files.backends.file import FileBackend
 19from authentik.admin.files.backends.passthrough import PassthroughBackend
 20from authentik.admin.files.backends.s3 import S3Backend
 21from authentik.admin.files.backends.static import StaticBackend
 22from authentik.admin.files.usage import FileUsage
 23from authentik.lib.config import CONFIG
 24
 25LOGGER = get_logger()
 26
 27
 28_FILE_BACKENDS = [
 29    StaticBackend,
 30    PassthroughBackend,
 31    FileBackend,
 32    S3Backend,
 33]
 34
 35
 36class FileManager:
 37    def __init__(self, usage: FileUsage) -> None:
 38        management_backend_name = CONFIG.get(
 39            f"storage.{usage.value}.backend",
 40            CONFIG.get("storage.backend", "file"),
 41        )
 42
 43        self.management_backend = None
 44        for backend in _FILE_BACKENDS:
 45            if issubclass(backend, ManageableBackend) and backend.name == management_backend_name:
 46                self.management_backend = backend(usage)
 47        if self.management_backend is None:
 48            LOGGER.warning(
 49                f"Storage backend configuration for {usage.value} is "
 50                f"invalid: {management_backend_name}"
 51            )
 52
 53        self.backends = []
 54        for backend in _FILE_BACKENDS:
 55            if usage not in backend.allowed_usages:
 56                continue
 57            if isinstance(self.management_backend, backend):
 58                self.backends.append(self.management_backend)
 59            elif not issubclass(backend, ManageableBackend):
 60                self.backends.append(backend(usage))
 61
 62    @property
 63    def manageable(self) -> bool:
 64        """
 65        Whether this file manager is able to manage files.
 66        """
 67        return self.management_backend is not None and self.management_backend.manageable
 68
 69    def list_files(self, manageable_only: bool = False) -> Generator[str]:
 70        """
 71        List available files.
 72        """
 73        for backend in self.backends:
 74            if manageable_only and not isinstance(backend, ManageableBackend):
 75                continue
 76            yield from backend.list_files()
 77
 78    def file_url(
 79        self,
 80        name: str | None,
 81        request: HttpRequest | Request | None = None,
 82        use_cache: bool = True,
 83    ) -> str:
 84        """
 85        Get URL for accessing the file.
 86
 87        Set ``use_cache=False`` when the caller needs a fresh signed URL instead
 88        of a cached one, for example when serializing flow/login payloads that
 89        may be refreshed after the previous JWT has expired.
 90
 91        A name with ``%(theme)s`` resolves to its light variant, so the URL always
 92        points at a real file. Callers that know the theme use ``themed_urls()``.
 93        """
 94        if not name:
 95            return ""
 96
 97        if isinstance(request, Request):
 98            request = request._request
 99
100        name = substitute_theme(name, "light")
101        for backend in self.backends:
102            if backend.supports_file(name):
103                return backend.file_url(name, request, use_cache=use_cache)
104
105        LOGGER.warning(f"Could not find file backend for file: {name}")
106        return ""
107
108    def themed_urls(
109        self,
110        name: str | None,
111        request: HttpRequest | Request | None = None,
112        use_cache: bool = True,
113    ) -> dict[str, str] | None:
114        """
115        Get URLs for each theme variant when filename contains %(theme)s, or when it is
116        one variant of a built-in source icon.
117
118        ``use_cache`` has the same semantics as ``file_url()`` and allows
119        callers to force regeneration of expiring signed URLs.
120
121        Returns dict mapping theme to URL if there are theme variants, None otherwise.
122        """
123        if not name:
124            return None
125
126        if isinstance(request, Request):
127            request = request._request
128
129        for backend in self.backends:
130            if backend.supports_file(name):
131                return backend.themed_urls(name, request, use_cache=use_cache)
132
133        return None
134
135    @contextmanager
136    def prefetch_urls(self, names: Iterable[str | None]) -> Iterator[None]:
137        """
138        Read the cached URLs of ``names`` and their theme variants with one query, for the
139        ``file_url()`` and ``themed_urls()`` calls made without a request inside this block.
140        Each of those calls otherwise reads the cache with a query of its own, which a list
141        of objects with icons makes once per object.
142
143        A URL that is not cached yet is generated and cached by its own call, as without
144        this block.
145        """
146        keys = []
147        for name in names:
148            if not name:
149                continue
150            variants = [substitute_theme(name, "light")]
151            if has_theme_variable(name):
152                variants += [substitute_theme(name, theme) for theme in get_valid_themes()]
153            for variant in variants:
154                backend = next((b for b in self.backends if b.supports_file(variant)), None)
155                # Only the manageable backends cache their URLs
156                if isinstance(backend, ManageableBackend):
157                    keys.append(backend.cache_key(variant, None))
158        try:
159            prefetched = cache.get_many(keys)
160        except DatabaseError:
161            # cache.get() treats a failing cache as empty; do the same, so each call reads or
162            # generates its own URL
163            prefetched = {}
164        token = PREFETCHED_URLS.set(prefetched)
165        try:
166            yield
167        finally:
168            PREFETCHED_URLS.reset(token)
169
170    def _check_manageable(self) -> None:
171        if not self.manageable:
172            raise ImproperlyConfigured("No file management backend configured.")
173
174    def save_file(self, file_path: str, content: bytes) -> None:
175        """
176        Save file contents to storage.
177        """
178        self._check_manageable()
179        assert self.management_backend is not None  # nosec
180        return self.management_backend.save_file(file_path, content)
181
182    def save_file_stream(self, file_path: str) -> Iterator:
183        """
184        Context manager for streaming file writes.
185
186        Args:
187            file_path: Relative file path
188
189        Returns:
190            Context manager that yields a writable file-like object
191
192        Usage:
193            with manager.save_file_stream("output.csv") as f:
194                f.write(b"data...")
195        """
196        self._check_manageable()
197        assert self.management_backend is not None  # nosec
198        return self.management_backend.save_file_stream(file_path)
199
200    def delete_file(self, file_path: str) -> None:
201        """
202        Delete file from storage.
203        """
204        self._check_manageable()
205        assert self.management_backend is not None  # nosec
206        return self.management_backend.delete_file(file_path)
207
208    def file_exists(self, file_path: str) -> bool:
209        """
210        Check if a file exists.
211        """
212        self._check_manageable()
213        assert self.management_backend is not None  # nosec
214        return self.management_backend.file_exists(file_path)
215
216
217MANAGERS = {usage: FileManager(usage) for usage in list(FileUsage)}
218
219
220def get_file_manager(usage: FileUsage) -> FileManager:
221    return MANAGERS[usage]
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class FileManager:
 37class FileManager:
 38    def __init__(self, usage: FileUsage) -> None:
 39        management_backend_name = CONFIG.get(
 40            f"storage.{usage.value}.backend",
 41            CONFIG.get("storage.backend", "file"),
 42        )
 43
 44        self.management_backend = None
 45        for backend in _FILE_BACKENDS:
 46            if issubclass(backend, ManageableBackend) and backend.name == management_backend_name:
 47                self.management_backend = backend(usage)
 48        if self.management_backend is None:
 49            LOGGER.warning(
 50                f"Storage backend configuration for {usage.value} is "
 51                f"invalid: {management_backend_name}"
 52            )
 53
 54        self.backends = []
 55        for backend in _FILE_BACKENDS:
 56            if usage not in backend.allowed_usages:
 57                continue
 58            if isinstance(self.management_backend, backend):
 59                self.backends.append(self.management_backend)
 60            elif not issubclass(backend, ManageableBackend):
 61                self.backends.append(backend(usage))
 62
 63    @property
 64    def manageable(self) -> bool:
 65        """
 66        Whether this file manager is able to manage files.
 67        """
 68        return self.management_backend is not None and self.management_backend.manageable
 69
 70    def list_files(self, manageable_only: bool = False) -> Generator[str]:
 71        """
 72        List available files.
 73        """
 74        for backend in self.backends:
 75            if manageable_only and not isinstance(backend, ManageableBackend):
 76                continue
 77            yield from backend.list_files()
 78
 79    def file_url(
 80        self,
 81        name: str | None,
 82        request: HttpRequest | Request | None = None,
 83        use_cache: bool = True,
 84    ) -> str:
 85        """
 86        Get URL for accessing the file.
 87
 88        Set ``use_cache=False`` when the caller needs a fresh signed URL instead
 89        of a cached one, for example when serializing flow/login payloads that
 90        may be refreshed after the previous JWT has expired.
 91
 92        A name with ``%(theme)s`` resolves to its light variant, so the URL always
 93        points at a real file. Callers that know the theme use ``themed_urls()``.
 94        """
 95        if not name:
 96            return ""
 97
 98        if isinstance(request, Request):
 99            request = request._request
100
101        name = substitute_theme(name, "light")
102        for backend in self.backends:
103            if backend.supports_file(name):
104                return backend.file_url(name, request, use_cache=use_cache)
105
106        LOGGER.warning(f"Could not find file backend for file: {name}")
107        return ""
108
109    def themed_urls(
110        self,
111        name: str | None,
112        request: HttpRequest | Request | None = None,
113        use_cache: bool = True,
114    ) -> dict[str, str] | None:
115        """
116        Get URLs for each theme variant when filename contains %(theme)s, or when it is
117        one variant of a built-in source icon.
118
119        ``use_cache`` has the same semantics as ``file_url()`` and allows
120        callers to force regeneration of expiring signed URLs.
121
122        Returns dict mapping theme to URL if there are theme variants, None otherwise.
123        """
124        if not name:
125            return None
126
127        if isinstance(request, Request):
128            request = request._request
129
130        for backend in self.backends:
131            if backend.supports_file(name):
132                return backend.themed_urls(name, request, use_cache=use_cache)
133
134        return None
135
136    @contextmanager
137    def prefetch_urls(self, names: Iterable[str | None]) -> Iterator[None]:
138        """
139        Read the cached URLs of ``names`` and their theme variants with one query, for the
140        ``file_url()`` and ``themed_urls()`` calls made without a request inside this block.
141        Each of those calls otherwise reads the cache with a query of its own, which a list
142        of objects with icons makes once per object.
143
144        A URL that is not cached yet is generated and cached by its own call, as without
145        this block.
146        """
147        keys = []
148        for name in names:
149            if not name:
150                continue
151            variants = [substitute_theme(name, "light")]
152            if has_theme_variable(name):
153                variants += [substitute_theme(name, theme) for theme in get_valid_themes()]
154            for variant in variants:
155                backend = next((b for b in self.backends if b.supports_file(variant)), None)
156                # Only the manageable backends cache their URLs
157                if isinstance(backend, ManageableBackend):
158                    keys.append(backend.cache_key(variant, None))
159        try:
160            prefetched = cache.get_many(keys)
161        except DatabaseError:
162            # cache.get() treats a failing cache as empty; do the same, so each call reads or
163            # generates its own URL
164            prefetched = {}
165        token = PREFETCHED_URLS.set(prefetched)
166        try:
167            yield
168        finally:
169            PREFETCHED_URLS.reset(token)
170
171    def _check_manageable(self) -> None:
172        if not self.manageable:
173            raise ImproperlyConfigured("No file management backend configured.")
174
175    def save_file(self, file_path: str, content: bytes) -> None:
176        """
177        Save file contents to storage.
178        """
179        self._check_manageable()
180        assert self.management_backend is not None  # nosec
181        return self.management_backend.save_file(file_path, content)
182
183    def save_file_stream(self, file_path: str) -> Iterator:
184        """
185        Context manager for streaming file writes.
186
187        Args:
188            file_path: Relative file path
189
190        Returns:
191            Context manager that yields a writable file-like object
192
193        Usage:
194            with manager.save_file_stream("output.csv") as f:
195                f.write(b"data...")
196        """
197        self._check_manageable()
198        assert self.management_backend is not None  # nosec
199        return self.management_backend.save_file_stream(file_path)
200
201    def delete_file(self, file_path: str) -> None:
202        """
203        Delete file from storage.
204        """
205        self._check_manageable()
206        assert self.management_backend is not None  # nosec
207        return self.management_backend.delete_file(file_path)
208
209    def file_exists(self, file_path: str) -> bool:
210        """
211        Check if a file exists.
212        """
213        self._check_manageable()
214        assert self.management_backend is not None  # nosec
215        return self.management_backend.file_exists(file_path)
FileManager(usage: authentik.admin.files.usage.FileUsage)
38    def __init__(self, usage: FileUsage) -> None:
39        management_backend_name = CONFIG.get(
40            f"storage.{usage.value}.backend",
41            CONFIG.get("storage.backend", "file"),
42        )
43
44        self.management_backend = None
45        for backend in _FILE_BACKENDS:
46            if issubclass(backend, ManageableBackend) and backend.name == management_backend_name:
47                self.management_backend = backend(usage)
48        if self.management_backend is None:
49            LOGGER.warning(
50                f"Storage backend configuration for {usage.value} is "
51                f"invalid: {management_backend_name}"
52            )
53
54        self.backends = []
55        for backend in _FILE_BACKENDS:
56            if usage not in backend.allowed_usages:
57                continue
58            if isinstance(self.management_backend, backend):
59                self.backends.append(self.management_backend)
60            elif not issubclass(backend, ManageableBackend):
61                self.backends.append(backend(usage))
management_backend
backends
manageable: bool
63    @property
64    def manageable(self) -> bool:
65        """
66        Whether this file manager is able to manage files.
67        """
68        return self.management_backend is not None and self.management_backend.manageable

Whether this file manager is able to manage files.

def list_files(self, manageable_only: bool = False) -> Generator[str]:
70    def list_files(self, manageable_only: bool = False) -> Generator[str]:
71        """
72        List available files.
73        """
74        for backend in self.backends:
75            if manageable_only and not isinstance(backend, ManageableBackend):
76                continue
77            yield from backend.list_files()

List available files.

def file_url( self, name: str | None, request: django.http.request.HttpRequest | rest_framework.request.Request | None = None, use_cache: bool = True) -> str:
 79    def file_url(
 80        self,
 81        name: str | None,
 82        request: HttpRequest | Request | None = None,
 83        use_cache: bool = True,
 84    ) -> str:
 85        """
 86        Get URL for accessing the file.
 87
 88        Set ``use_cache=False`` when the caller needs a fresh signed URL instead
 89        of a cached one, for example when serializing flow/login payloads that
 90        may be refreshed after the previous JWT has expired.
 91
 92        A name with ``%(theme)s`` resolves to its light variant, so the URL always
 93        points at a real file. Callers that know the theme use ``themed_urls()``.
 94        """
 95        if not name:
 96            return ""
 97
 98        if isinstance(request, Request):
 99            request = request._request
100
101        name = substitute_theme(name, "light")
102        for backend in self.backends:
103            if backend.supports_file(name):
104                return backend.file_url(name, request, use_cache=use_cache)
105
106        LOGGER.warning(f"Could not find file backend for file: {name}")
107        return ""

Get URL for accessing the file.

Set use_cache=False when the caller needs a fresh signed URL instead of a cached one, for example when serializing flow/login payloads that may be refreshed after the previous JWT has expired.

A name with %(theme)s resolves to its light variant, so the URL always points at a real file. Callers that know the theme use themed_urls().

def themed_urls( self, name: str | None, request: django.http.request.HttpRequest | rest_framework.request.Request | None = None, use_cache: bool = True) -> dict[str, str] | None:
109    def themed_urls(
110        self,
111        name: str | None,
112        request: HttpRequest | Request | None = None,
113        use_cache: bool = True,
114    ) -> dict[str, str] | None:
115        """
116        Get URLs for each theme variant when filename contains %(theme)s, or when it is
117        one variant of a built-in source icon.
118
119        ``use_cache`` has the same semantics as ``file_url()`` and allows
120        callers to force regeneration of expiring signed URLs.
121
122        Returns dict mapping theme to URL if there are theme variants, None otherwise.
123        """
124        if not name:
125            return None
126
127        if isinstance(request, Request):
128            request = request._request
129
130        for backend in self.backends:
131            if backend.supports_file(name):
132                return backend.themed_urls(name, request, use_cache=use_cache)
133
134        return None

Get URLs for each theme variant when filename contains %(theme)s, or when it is one variant of a built-in source icon.

use_cache has the same semantics as file_url() and allows callers to force regeneration of expiring signed URLs.

Returns dict mapping theme to URL if there are theme variants, None otherwise.

@contextmanager
def prefetch_urls(self, names: Iterable[str | None]) -> Iterator[None]:
136    @contextmanager
137    def prefetch_urls(self, names: Iterable[str | None]) -> Iterator[None]:
138        """
139        Read the cached URLs of ``names`` and their theme variants with one query, for the
140        ``file_url()`` and ``themed_urls()`` calls made without a request inside this block.
141        Each of those calls otherwise reads the cache with a query of its own, which a list
142        of objects with icons makes once per object.
143
144        A URL that is not cached yet is generated and cached by its own call, as without
145        this block.
146        """
147        keys = []
148        for name in names:
149            if not name:
150                continue
151            variants = [substitute_theme(name, "light")]
152            if has_theme_variable(name):
153                variants += [substitute_theme(name, theme) for theme in get_valid_themes()]
154            for variant in variants:
155                backend = next((b for b in self.backends if b.supports_file(variant)), None)
156                # Only the manageable backends cache their URLs
157                if isinstance(backend, ManageableBackend):
158                    keys.append(backend.cache_key(variant, None))
159        try:
160            prefetched = cache.get_many(keys)
161        except DatabaseError:
162            # cache.get() treats a failing cache as empty; do the same, so each call reads or
163            # generates its own URL
164            prefetched = {}
165        token = PREFETCHED_URLS.set(prefetched)
166        try:
167            yield
168        finally:
169            PREFETCHED_URLS.reset(token)

Read the cached URLs of names and their theme variants with one query, for the file_url() and themed_urls() calls made without a request inside this block. Each of those calls otherwise reads the cache with a query of its own, which a list of objects with icons makes once per object.

A URL that is not cached yet is generated and cached by its own call, as without this block.

def save_file(self, file_path: str, content: bytes) -> None:
175    def save_file(self, file_path: str, content: bytes) -> None:
176        """
177        Save file contents to storage.
178        """
179        self._check_manageable()
180        assert self.management_backend is not None  # nosec
181        return self.management_backend.save_file(file_path, content)

Save file contents to storage.

def save_file_stream(self, file_path: str) -> Iterator:
183    def save_file_stream(self, file_path: str) -> Iterator:
184        """
185        Context manager for streaming file writes.
186
187        Args:
188            file_path: Relative file path
189
190        Returns:
191            Context manager that yields a writable file-like object
192
193        Usage:
194            with manager.save_file_stream("output.csv") as f:
195                f.write(b"data...")
196        """
197        self._check_manageable()
198        assert self.management_backend is not None  # nosec
199        return self.management_backend.save_file_stream(file_path)

Context manager for streaming file writes.

Args: file_path: Relative file path

Returns: Context manager that yields a writable file-like object

Usage: with manager.save_file_stream("output.csv") as f: f.write(b"data...")

def delete_file(self, file_path: str) -> None:
201    def delete_file(self, file_path: str) -> None:
202        """
203        Delete file from storage.
204        """
205        self._check_manageable()
206        assert self.management_backend is not None  # nosec
207        return self.management_backend.delete_file(file_path)

Delete file from storage.

def file_exists(self, file_path: str) -> bool:
209    def file_exists(self, file_path: str) -> bool:
210        """
211        Check if a file exists.
212        """
213        self._check_manageable()
214        assert self.management_backend is not None  # nosec
215        return self.management_backend.file_exists(file_path)

Check if a file exists.

MANAGERS = {<FileUsage.MEDIA: 'media'>: <FileManager object>, <FileUsage.REPORTS: 'reports'>: <FileManager object>}
def get_file_manager( usage: authentik.admin.files.usage.FileUsage) -> FileManager:
221def get_file_manager(usage: FileUsage) -> FileManager:
222    return MANAGERS[usage]