Merge branch 's3-support' into multi-tenant-django-tenants

This commit is contained in:
Marc 'risson' Schmitt 2023-12-20 10:33:29 +01:00
commit 951f9ce043
No known key found for this signature in database
GPG Key ID: 9C3FA22FABF1AA8D
17 changed files with 1346 additions and 117 deletions

View File

@ -34,6 +34,7 @@ REDIS_ENV_KEYS = [
f"{ENV_PREFIX}_REDIS__TLS_REQS",
]
# Old key -> new key
DEPRECATIONS = {
"redis.broker_url": "broker.url",
"redis.broker_transport_options": "broker.transport_options",
@ -200,12 +201,13 @@ class ConfigLoader:
root[key] = value
return root
def refresh(self, key: str):
def refresh(self, key: str, default=None, sep=".") -> Any:
"""Update a single value"""
attr: Attr = get_path_from_dict(self.raw, key)
attr: Attr = get_path_from_dict(self.raw, key, sep=sep, default=Attr(default))
if attr.source_type != Attr.Source.URI:
return
return attr.value
attr.value = self.parse_uri(attr.source).value
return attr.value
def parse_uri(self, value: str) -> Attr:
"""Parse string values which start with a URI"""

View File

@ -53,9 +53,6 @@ cache:
# result_backend:
# url: ""
paths:
media: ./media
debug: false
remote_debug: false
@ -125,3 +122,20 @@ web:
worker:
concurrency: 2
storage:
media:
backend: file # or s3
file:
path: ./media
s3:
# How to talk to s3
# region: "us-east-1"
# use_ssl: True
# endpoint: "https://s3.us-east-1.amazonaws.com"
# access_key: ""
# secret_key: ""
# bucket_name: "authentik-media"
# How to render file URLs
# custom_domain: null
secure_urls: True

View File

@ -17,10 +17,6 @@ from authentik.lib.utils.reflection import get_env
from authentik.stages.password import BACKEND_APP_PASSWORD, BACKEND_INBUILT, BACKEND_LDAP
BASE_DIR = Path(__file__).absolute().parent.parent.parent
STATICFILES_DIRS = [BASE_DIR / Path("web")]
MEDIA_ROOT = BASE_DIR / Path("media")
DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage"
MULTITENANT_RELATIVE_MEDIA_ROOT = "tenants"
DEBUG = CONFIG.get_bool("debug")
SECRET_KEY = CONFIG.get("secret_key")
@ -392,8 +388,54 @@ if _ERROR_REPORTING:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATICFILES_DIRS = [BASE_DIR / Path("web")]
STATIC_URL = "/static/"
MEDIA_URL = "/media/"
STORAGES = {
"staticfiles": {
"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
},
}
# Media files
if CONFIG.get("storage.media.backend", "file") == "s3":
STORAGES["default"] = {
"BACKEND": "authentik.root.storages.S3Storage",
"OPTIONS": {
# How to talk to S3
"session_profile": CONFIG.get("storage.media.s3.session_profile", None),
"access_key": CONFIG.get("storage.media.s3.access_key", None),
"secret_key": CONFIG.get("storage.media.s3.secret_key", None),
"security_token": CONFIG.get("storage.media.s3.security_token", None),
"region_name": CONFIG.get("storage.media.s3.region", None),
"use_ssl": CONFIG.get_bool("storage.media.s3.use_ssl", True),
"endpoint_url": CONFIG.get("storage.media.s3.endpoint", None),
"bucket_name": CONFIG.get("storage.media.s3.bucket_name"),
"default_acl": "private",
"querystring_auth": True,
"signature_version": "s3v4",
"file_overwrite": False,
"location": "media",
"url_protocol": "https:"
if CONFIG.get("storage.media.s3.secure_urls", True)
else "http:",
"custom_domain": CONFIG.get("storage.media.s3.custom_domain", None),
},
}
# Fallback on file storage backend
else:
STORAGES["default"] = {
"BACKEND": "authentik.root.storages.FileStorage",
"OPTIONS": {
"location": Path(CONFIG.get("storage.media.file.path")),
"base_url": "/media/",
},
}
# Compatibility for apps not supporting top-level STORAGES
# such as django-tenants
MEDIA_ROOT = STORAGES["default"]["OPTIONS"]["location"]
MEDIA_URL = STORAGES["default"]["OPTIONS"]["base_url"]
TEST = False
TEST_RUNNER = "authentik.root.test_runner.PytestTestRunner"

110
authentik/root/storages.py Normal file
View File

@ -0,0 +1,110 @@
"""authentik storage backends"""
import os
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.core.files.storage import FileSystemStorage
from django.db import connection
from storages.backends.s3 import S3Storage as BaseS3Storage
from storages.utils import clean_name, safe_join
from authentik.lib.config import CONFIG
class FileStorage(FileSystemStorage):
@property
def base_location(self):
return os.path.join(
self._value_or_setting(self._location, settings.MEDIA_ROOT), connection.schema_name
)
@property
def location(self):
return os.path.abspath(self.base_location)
@property
def base_url(self):
if self._base_url is not None and not self._base_url.endswith("/"):
self._base_url += "/"
return f"{self._base_url}/{connection.schema_name}/"
# pylint: disable=abstract-method
class S3Storage(BaseS3Storage):
"""S3 storage backend"""
@property
def session_profile(self) -> str | None:
"""Get session profile"""
return CONFIG.refresh("storage.media.s3.session_profile", None)
@session_profile.setter
def session_profile(self, value: str):
pass
@property
def access_key(self) -> str | None:
"""Get access key"""
return CONFIG.refresh("storage.media.s3.access_key", None)
@access_key.setter
def access_key(self, value: str):
pass
@property
def secret_key(self) -> str | None:
"""Get secret key"""
return CONFIG.refresh("storage.media.s3.secret_key", None)
@secret_key.setter
def secret_key(self, value: str):
pass
@property
def security_token(self) -> str | None:
"""Get security token"""
return CONFIG.refresh("storage.media.s3.security_token", None)
@security_token.setter
def security_token(self, value: str):
pass
def _normalize_name(self, name):
try:
return safe_join(self.location, connection.schema_name, name)
except ValueError:
raise SuspiciousOperation("Attempted access to '%s' denied." % name)
# This is a fix for https://github.com/jschneier/django-storages/pull/839
# pylint: disable=arguments-differ,no-member
def url(self, name, parameters=None, expire=None, http_method=None):
# Preserve the trailing slash after normalizing the path.
name = self._normalize_name(clean_name(name))
params = parameters.copy() if parameters else {}
if expire is None:
expire = self.querystring_expire
params["Bucket"] = self.bucket.name
params["Key"] = name
url = self.bucket.meta.client.generate_presigned_url(
"get_object",
Params=params,
ExpiresIn=expire,
HttpMethod=http_method,
)
if self.custom_domain:
# Key parameter can't be empty. Use "/" and remove it later.
params["Key"] = "/"
root_url_signed = self.bucket.meta.client.generate_presigned_url(
"get_object", Params=params, ExpiresIn=expire
)
# Remove signing parameter and previously added key "/".
root_url = self._strip_signing_parameters(root_url_signed)[:-1]
# Replace bucket domain with custom domain.
custom_url = "{}//{}/".format(self.url_protocol, self.custom_domain)
url = url.replace(root_url, custom_url)
if self.querystring_auth:
return url
return self._strip_signing_parameters(url)

View File

@ -5416,8 +5416,22 @@
"title": "Icon"
},
"provider_type": {
"type": [],
"enum": [],
"type": "string",
"enum": [
"apple",
"azuread",
"discord",
"facebook",
"github",
"google",
"mailcow",
"openidconnect",
"okta",
"patreon",
"reddit",
"twitch",
"twitter"
],
"title": "Provider type"
},
"request_token_url": {

View File

@ -2,7 +2,7 @@ package config
type Config struct {
// Core specific config
Paths PathsConfig `yaml:"paths"`
Storage StorageConfig `yaml:"storage"`
LogLevel string `yaml:"log_level" env:"AUTHENTIK_LOG_LEVEL"`
ErrorReporting ErrorReportingConfig `yaml:"error_reporting"`
Redis RedisConfig `yaml:"redis"`
@ -45,8 +45,17 @@ type ListenConfig struct {
TrustedProxyCIDRs []string `yaml:"trusted_proxy_cidrs" env:"AUTHENTIK_LISTEN__TRUSTED_PROXY_CIDRS"`
}
type PathsConfig struct {
Media string `yaml:"media"`
type StorageConfig struct {
Media StorageMediaConfig `yaml:"media"`
}
type StorageMediaConfig struct {
Backend string `yaml:"backend" env:"AUTHENTIK_STORAGE_MEDIA_BACKEND"`
File StorageFileConfig `yaml:"file"`
}
type StorageFileConfig struct {
Path string `yaml:"path" env:"AUTHENTIK_STORAGE_MEDIA_FILE_PATH"`
}
type ErrorReportingConfig struct {

View File

@ -6,6 +6,7 @@ import (
"github.com/go-http-utils/etag"
"github.com/gorilla/mux"
"goauthentik.io/internal/config"
"goauthentik.io/internal/constants"
"goauthentik.io/internal/utils/web"
@ -17,8 +18,6 @@ func (ws *WebServer) configureStatic() {
statRouter.Use(ws.staticHeaderMiddleware)
indexLessRouter := statRouter.NewRoute().Subrouter()
indexLessRouter.Use(web.DisableIndex)
// Media files, always local
fs := http.FileServer(http.Dir(config.Get().Paths.Media))
distFs := http.FileServer(http.Dir("./web/dist"))
distHandler := http.StripPrefix("/static/dist/", distFs)
authentikHandler := http.StripPrefix("/static/authentik/", http.FileServer(http.Dir("./web/authentik")))
@ -35,7 +34,11 @@ func (ws *WebServer) configureStatic() {
indexLessRouter.PathPrefix("/if/admin/assets").Handler(http.StripPrefix("/if/admin", distFs))
indexLessRouter.PathPrefix("/if/user/assets").Handler(http.StripPrefix("/if/user", distFs))
indexLessRouter.PathPrefix("/media/").Handler(http.StripPrefix("/media", fs))
// Media files, if backend is file
if config.Get().Storage.Media.Backend == "file" {
fsMedia := http.FileServer(http.Dir(config.Get().Storage.Media.File.Path))
indexLessRouter.PathPrefix("/media/").Handler(http.StripPrefix("/media", fsMedia))
}
statRouter.PathPrefix("/if/help/").Handler(http.StripPrefix("/if/help/", helpHandler))
statRouter.PathPrefix("/help").Handler(http.RedirectHandler("/if/help/", http.StatusMovedPermanently))

323
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -133,6 +133,7 @@ django-guardian = "*"
django-model-utils = "*"
django-prometheus = "*"
django-redis = "*"
django-storages = { extras = ["s3"], version = "*" }
# See https://github.com/django-tenants/django-tenants/pull/959
# See https://github.com/django-tenants/django-tenants/pull/997
django-tenants = { git = "https://github.com/rissson/django-tenants.git", branch="authentik-fixes" }

File diff suppressed because it is too large Load Diff

16
scripts/create_bucket.sh Normal file
View File

@ -0,0 +1,16 @@
#!/usr/bin/env -S bash -e
AWS_ACCESS_KEY_ID=accessKey1 AWS_SECRET_ACCESS_KEY=secretKey1 aws \
s3api \
--endpoint-url http://localhost:8020 \
create-bucket \
--acl private \
--bucket authentik-media
AWS_ACCESS_KEY_ID=accessKey1 AWS_SECRET_ACCESS_KEY=secretKey1 aws \
s3api \
--endpoint-url http://localhost:8020 \
put-bucket-cors \
--bucket authentik-media \
--cors-configuration \
'{"CORSRules": [{"AllowedOrigins": ["*"], "AllowedHeaders": ["Authorization"], "AllowedMethods": ["GET"], "MaxAgeSeconds": 3000}]}'

View File

@ -18,7 +18,24 @@ services:
ports:
- 127.0.0.1:6379:6379
restart: always
s3:
container_name: s3
image: docker.io/zenko/cloudserver
environment:
REMOTE_MANAGEMENT_DISABLE: "1"
SCALITY_ACCESS_KEY_ID: accessKey1
SCALITY_SECRET_ACCESS_KEY: secretKey1
ports:
- 8020:8000
volumes:
- s3-data:/usr/src/app/localData
- s3-metadata:/usr/scr/app/localMetadata
restart: always
volumes:
db-data:
driver: local
s3-data:
driver: local
s3-metadata:
driver: local

View File

@ -19,6 +19,19 @@ with open("local.env.yml", "w", encoding="utf-8") as _config:
"blueprints_dir": "./blueprints",
"cert_discovery_dir": "./certs",
"geoip": "tests/GeoLite2-City-Test.mmdb",
"storage": {
"media": {
"backend": "file",
"s3": {
"endpoint": "http://localhost:8020",
"access_key": "accessKey1",
"secret_key": "secretKey1",
"bucket_name": "authentik-media",
"custom_domain": "localhost:8020/authentik-media",
"secure_urls": False,
},
},
},
"tenants": {
"enabled": False,
"api_key": generate_id(),

View File

@ -116,7 +116,7 @@ To check if your config has been applied correctly, you can run the following co
`AUTHENTIK_REDIS__CACHE_TIMEOUT_REPUTATION` only applies to the cache expiry, see [`AUTHENTIK_REPUTATION__EXPIRY`](#authentik_reputation__expiry) to control how long reputation is persisted for.
:::
## Listen Setting
## Listen Settings
- `AUTHENTIK_LISTEN__HTTP`: Listening address:port (e.g. `0.0.0.0:9000`) for HTTP (Applies to Server and Proxy outpost)
- `AUTHENTIK_LISTEN__HTTPS`: Listening address:port (e.g. `0.0.0.0:9443`) for HTTPS (Applies to Server and Proxy outpost)
@ -130,6 +130,22 @@ To check if your config has been applied correctly, you can run the following co
Requests directly coming from one an address within a CIDR specified here are able to set proxy headers, such as `X-Forwarded-For`. Requests coming from other addresses will not be able to set these headers.
## Media Storage Settings
These settings affect where media files are stored. Those files include applications and sources icons. By default, they are stored on disk in the `/media` directory of the authentik container. S3 storage is also supported.
- `AUTHENTIK_STORAGE_MEDIA_BACKEND`: Where to store files. Valid values are `file` and `s3`. For `file` storage, files are stored in a `/media` directory in the container. For `s3`, see below.
- `AUTHENTIK_STORAGE_MEDIA_S3_REGION`: S3 region where the bucket has been created. May be omitted depending on which S3 provider you use. No default.
- `AUTHENTIK_STORAGE_MEDIA_S3_USE__SSL`: Whether to use HTTPS when talking to the S3 storage providers. Defaults to `true`.
- `AUTHENTIK_STORAGE_MEDIA_S3_ENDPOINT`: Endpoint to use to talk to the S3 storage provider. Override the previous region and use_ssl settings. Must be a valid URL in the form of `https://s3.provider`. No default.
- `AUTHENTIK_STORAGE_MEDIA_S3_SESSION__PROFILE`: Profile to use when using AWS SDK authentication. No default. Supports hot-reloading.
- `AUTHENTIK_STORAGE_MEDIA_S3_ACCESS__KEY`: Access key to authenticate to S3. May be omitted if using AWS SDK authentication. Supports hot-reloading.
- `AUTHENTIK_STORAGE_MEDIA_S3_SECRET__KEY`: Secret key to authenticate to S3. May be omitted if using AWS SDK authentication. Supports hot-reloading.
- `AUTHENTIK_STORAGE_MEDIA_S3_SECURITY__TOKEN`: Security token to authenticate to S3. May be omitted. Supports hot-reloading.
- `AUTHENTIK_STORAGE_MEDIA_S3_BUCKET__NAME`: Name of the bucket to use to store files.
- `AUTHENTIK_STORAGE_MEDIA_S3_CUSTOM__DOMAIN`: Domain to use to create URLs for users. Mainly useful for non-AWS providers. May include a port. Must include the bucket. Example: `s3.company:8080/authentik-media`.
- `AUTHENTIK_STORAGE_MEDIA_S3_SECURE__URLS`: Whether URLS created for users use `http` or `https`. Defaults to `true`.
## authentik Settings
### `AUTHENTIK_SECRET_KEY`

View File

@ -0,0 +1,104 @@
---
title: S3 storage setup
---
### Preparation
First, create a user on your S3 storage provider and get access credentials for S3, hereafter referred as `access_key` and `secret_key`.
You'll also need to know which endpoint authentik is going to use to access the S3 API, hereafter referred as `https://s3.provider`.
The bucket in which authentik is going to store files is going to be called `authentik-media`. You may need to change this name depending on your S3 provider limitations. Also, we're suffixing the bucket name with `-media` as authentik currently only stores media files, but may use other buckets in the future.
The domain used to access authentik is going to be referred to as `authentik.company`.
You will also need the AWS CLI.
### S3 configuration
#### Bucket creation
Let's create the bucket in which authentik is going to store files:
```bash
AWS_ACCESS_KEY_ID=access_key AWS_SECRET_ACCESS_KEY=secret_key aws s3api --endpoint-url=https://s3.provider create-bucket --bucket=authentik-media --acl=private
```
If using AWS S3, you can omit the `--endpoint-url` option, but may need to specify the `--region` option. If using Google Cloud Storage, refer to its documentation on how to create buckets.
The bucket ACL is set to private, although that is not strictly necessary, as an ACL associated with each object stored in the bucket will be private as well.
#### CORS policy
Next, let's associate a CORS policy to the bucket, to allow the authentik web interface to show images stored in the bucket.
First, save the following file locally as `cors.json`:
```json
{
"CORSRules": [
{
"AllowedOrigins": ["authentik.company"],
"AllowedHeaders": ["Authorization"],
"AllowedMethods": ["GET"],
"MaxAgeSeconds": 3000
}
]
}
```
If authentik is accessed from multiple domains, you can add them to the `AllowedOrigins` list.
Let's apply that policy to the bucket:
```bash
AWS_ACCESS_KEY_ID=access_key AWS_SECRET_ACCESS_KEY=secret_key aws s3api --endpoint-url=https://s3.provider put-bucket-cors --bucket=authentik-media --cors-configuration=file://cors.json
```
### Configuring authentik
Add the following to your `.env` file:
```env
AUTHENTIK_STORAGE_MEDIA_BACKEND=s3
AUTHENTIK_STORAGE_MEDIA_S3_ACCESS__KEY=access_key
AUTHENTIK_STORAGE_MEDIA_S3_SECRET__KEY=secret_key
AUTHENTIK_STORAGE_MEDIA_S3_BUCKET__NAME=authentik-media
```
If you're using AWS S3 as your S3 provider, add the following:
```env
AUTHENTIK_STORAGE_MEDIA_S3_REGION=us-east-1 # Use the region of the bucket
```
If you're not using AWS S3 as your S3 provider, add the following:
```env
AUTHENTIK_STORAGE_MEDIA_S3_ENDPOINT=https://s3.provider
AUTHENTIK_STORAGE_MEDIA_S3_CUSTOM__DOMAIN=s3.provider/authentik-media
```
The `ENDPOINT` setting specifies how authentik talks to the S3 provider.
The `CUSTOM__DOMAIN` setting specifies how URLs are constructed to be shown on the web interface. For example, an object stored at `application-icons/application.png` with a `CUSTOM__DOMAIN` setting of `s3.provider/authentik-media` will result in a URL of `https://s3.provider/authentik-media/application-icons/application.png`. You can also use subdomains for your buckets depending on what your S3 provider offers: `authentik-media.s3.provider`. Whether HTTPS is used is controlled by the `AUTHENTIK_STORAGE_MEDIA_S3_SECURE__URLS` which defaults to true.
For more control over settings, refer to the [configuration reference](./configuration.mdx#media-storage-settings)
### Migrating between storage backends
The following section assumes that the local storage path is `/media` and the bucket name is `authentik-media`. It also assumes you have a working `aws` CLI that can interact with the bucket.
#### From file to s3
Follow the setup steps above, and then migrate the files from your local directory to s3:
```bash
aws s3 sync /media s3://authentik-media
```
#### From s3 to file
```bash
aws s3 sync s3://authentik-media /media
```

View File

@ -23,6 +23,10 @@ slug: "/releases/2024.1"
Previously the identification stage would only continue if a user matching the user identifier exists. While this was the intended functionality, this release adds an option to continue to the next stage even if no matching user was found. "Pretend" users cannot authenticate nor receive emails, and don't exist in the database. **This feature is enabled by default.**
- S3 file storage
Media files can now be stored on S3. Follow the [setup guide](../../installation/storage-s3.md) to get started.
## Upgrading
This release does not introduce any new requirements.

View File

@ -27,6 +27,7 @@ const docsSidebar = {
"installation/automated-install",
"installation/air-gapped",
"installation/monitoring",
"installation/storage-s3",
],
},
{