plinth/*: Rename plinth/ folder to freedombox/

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa authored and James Valleroy committed 2026-08-28 07:35:01 -04:00
1 parent dd0161a7e5
commit 23b6aff290
1264 files changed

No files matched your search

+275
View File
@@ -0,0 +1,275 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""FreedomBox app for Apache server.
This module implements a mechanism for protecting various URL paths using
FreedomBox's OpenID Connect implementation as Identity Provider and
mod_auth_oidc as Relying Party. The following is a simplified description of
how the flow works:
- User accesses the URL /foo using a browser. /foo is a URL path which is
protected by this module's OpenID Connect SSO (using AuthType
openid-connect).
- mod_auth_opendic seizes control and checks for authorization. Since this is
the first visit, it starts the authentication/authorization process. It first
redirects the browser to provider discovery URL
/freedombox/apache/discover-idp/.
- This URL selects and Identity Provider based on incoming URL's host header.
It will select https://mydomain.example/freedombox/o as IDP if the original
URL is https://mydomain.example/foo. Or https://freedombox.local/freedombox/o
if the original URL is https://freedombox.local/foo. After selection it will
redirect the browser back to /apache/oidc/callback with the selected IDP in
the GET parameters.
- /apache/oidc/callback is controlled by mod_auth_openidc which receives the
IDP selection. It will then query the IDP for further information such as
authorization URL, token URL, supported scopes and claims. This is done using
a backend call to /freedombox/o/.well-known/openid-configuration.
- After determining the authorization end point (/freedombox/o/authorize/) from
the metadata, mod_auth_openidc will start the authentication/authorization
process by redirecting the browser to the URL.
- FreedomBox shows login page if the user is not already logged in. User logs
in.
- FreedomBox will show a page asking the user to authorize the application to
access information such as name and email. In case of Apache's
mod_auth_openidc, this is skipped.
- FreedomBox will redirect back to /apache/oidc/callback after various checks.
This request will contain authorization grant token and OIDC claims in
parameters.
- mod_auth_openidc connects using back channel HTTP call to token endpoint
(/freedombox/o/token/) with the authorization grant token and then obtains
access token and refresh token. OIDC claims are checked using client_secret
known only to FreedomBox IDP and mod_auth_openidc.
- The OIDC claims contains username as part of 'sub' claim. This is exported as
REMOTE_USER header. 'freedombox_groups' contains the list of groups that
FreedomBox account is part of. These, along with 'Require claim' Apache
configuration directives, are used to determine if the user should get access
to /foo path or not.
- The application providing /foo will have access to information such username
and groups as part of REMOTE_USER and other OIDC_* environment variables.
- mod_auth_openidc also sets cookies that ensure that the whole process is not
repeated when a second request for the path /foo is received.
"""
import ipaddress
import os
from django.utils.translation import gettext_lazy as _
from plinth import action_utils
from plinth import app as app_module
from plinth import cfg
from plinth.config import DropinConfigs
from plinth.daemon import Daemon
from plinth.modules import names
from plinth.modules.firewall.components import Firewall
from plinth.modules.letsencrypt.components import LetsEncrypt
from plinth.modules.oidc.components import OpenIDConnect
from plinth.package import Packages
from plinth.signals import domain_added, domain_removed
from plinth.utils import format_lazy, is_valid_user_name
from . import privileged
class ApacheApp(app_module.App):
"""FreedomBox app for Apache web server."""
app_id = 'apache'
_version = 17
def __init__(self) -> None:
"""Create components for the app."""
super().__init__()
info = app_module.Info(app_id=self.app_id, version=self._version,
is_essential=True, name=_('Apache HTTP Server'))
self.add(info)
packages = Packages(
'packages-apache',
['apache2', 'php-fpm', 'ssl-cert', 'libapache2-mod-auth-openidc'])
self.add(packages)
dropin_configs = DropinConfigs('dropin-configs-apache', [
'/etc/apache2/conf-available/10-freedombox.conf',
'/etc/apache2/conf-available/php-fpm-freedombox.conf',
'/etc/fail2ban/jail.d/apache-auth-freedombox.conf',
])
self.add(dropin_configs)
web_server_ports = Firewall('firewall-web', _('Web Server'),
ports=['http', 'https'], is_external=True)
self.add(web_server_ports)
freedombox_ports = Firewall(
'firewall-plinth',
format_lazy(_('{box_name} Web Interface (Plinth)'),
box_name=_(cfg.box_name)), ports=['http', 'https'],
is_external=True)
self.add(freedombox_ports)
letsencrypt = LetsEncrypt('letsencrypt-apache', domains='*',
daemons=['apache2'], reload_daemons=True)
self.add(letsencrypt)
openidconnect = OpenIDConnect(
'openidconnect-apache', 'apache',
_('Web app protected by FreedomBox'),
redirect_uris=['https://{domain}/apache/oidc/callback'],
skip_authorization=True)
self.add(openidconnect)
daemon = Daemon('daemon-apache', 'apache2')
self.add(daemon)
@staticmethod
def post_init():
"""Perform post initialization operations."""
domain_added.connect(_on_domain_added)
domain_removed.connect(_on_domain_removed)
def setup(self, old_version):
"""Install and configure the app."""
super().setup(old_version)
privileged.setup(old_version)
self.enable()
def validate_host(hostname: str):
"""Check whether we are allowed to be called by a given name.
This is to prevent DNS rebinding attacks and other poor consequences in the
OpenID Connect protoctol.
"""
if hostname in ('localhost', 'ip6-localhost', 'ip6-loopback'):
return
if hostname == action_utils.get_hostname():
return
if hostname in names.components.DomainName.list_names():
return
try:
ipaddress.ip_address(hostname)
return
except ValueError:
pass
raise ValueError(f'Server not configured to be called as {hostname}')
def setup_oidc_client(netloc: str, hostname: str):
"""Setup OpenID Connect client configuration.
netloc is hostname or IP address along with port as parsed by
urllib.parse.urlparse() method from a URL.
"""
validate_host(hostname)
oidc = app_module.App.get('apache').get_component('openidconnect-apache')
privileged.setup_oidc_client(netloc, oidc.client_id,
oidc.get_client_secret())
def _on_domain_added(sender, domain_type, name='', description='',
services=None, **kwargs):
"""Add site specific configuration for a domain."""
if name:
privileged.domain_setup(name)
def _on_domain_removed(sender, domain_type, name='', **kwargs):
"""Remove site specific configuration for a domain."""
if name:
privileged.domain_remove(name)
# (U)ser (W)eb (S)ites
def uws_directory_of_user(user):
"""Return the directory of the given user's website."""
return '/home/{}/public_html'.format(user)
def uws_url_of_user(user):
"""Return the url path of the given user's website."""
return '/~{}/'.format(user)
def user_of_uws_directory(directory):
"""Return the user of a given user website directory."""
if directory.startswith('/home/'):
pos_ini = 6
elif directory.startswith('home/'):
pos_ini = 5
else:
return None
pos_end = directory.find('/public_html')
if pos_end == -1:
return None
user = directory[pos_ini:pos_end]
return user if is_valid_user_name(user) else None
def user_of_uws_url(url):
"""Return the user of a given user website url path."""
MISSING = -1
pos_ini = url.find('~')
if pos_ini == MISSING:
return None
pos_end = url.find('/', pos_ini)
if pos_end == MISSING:
pos_end = len(url)
user = url[pos_ini + 1:pos_end]
return user if is_valid_user_name(user) else None
def uws_directory_of_url(url):
"""Return the directory of the user's website for the given url path.
Note: It doesn't return the full OS file path to the url path!
"""
return uws_directory_of_user(user_of_uws_url(url))
def uws_url_of_directory(directory):
"""Return the url base path of the user's website for the given OS path.
Note: It doesn't return the url path for the file!
"""
return uws_url_of_user(user_of_uws_directory(directory))
def get_users_with_website():
"""Return a dictionary of users with actual website subdirectory."""
def lst_sub_dirs(directory):
"""Return the list of subdirectories of the given directory."""
return [
name for name in os.listdir(directory)
if os.path.isdir(os.path.join(directory, name))
]
return {
name: uws_url_of_user(name)
for name in lst_sub_dirs('/home')
if os.path.isdir(uws_directory_of_user(name))
}
+316
View File
@@ -0,0 +1,316 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""App component for other apps to use Apache configuration functionality."""
import re
import subprocess
from django.utils.translation import gettext_noop
from plinth import action_utils, app, kvstore
from plinth.diagnostic_check import (DiagnosticCheck,
DiagnosticCheckParameters, Result)
from plinth.privileged import service as service_privileged
from . import privileged
class Webserver(app.LeaderComponent):
"""Component to enable/disable Apache configuration."""
def __init__(self, component_id: str, web_name: str, kind: str = 'config',
urls: list[str] | None = None, expect_redirects: bool = False,
last_updated_version: int | None = None):
"""Initialize the web server component.
component_id should be a unique ID across all components of an app and
across all components.
web_name is the primary part of the configuration file path which must
be enabled/disabled by this component.
kind is the type of Apache configuration being enabled/disabled. This
must be 'config' for a configuration in /etc/apache/conf-available/,
'module' for configuration in /etc/apache2/mods-available/, 'site' for
configuration in /etc/apache2/sites-available/.
urls is a list of URLs over which a HTTP services will be available due
to this component. This list is only used for running diagnostics.
expect_redirects is a boolean that allows redirects when trying to
access the URLs during diagnosis of the component.
last_updated_version is the app version in which the web server
configuration/site/module file was updated. Using this, web server will
be automatically reloaded or restarted as necessary during app upgrade.
"""
super().__init__(component_id)
self.web_name = web_name
self.kind = kind
self.urls = urls or []
self.expect_redirects = expect_redirects
self.last_updated_version = last_updated_version or 0
def is_enabled(self) -> bool:
"""Return whether the Apache configuration is enabled."""
return action_utils.webserver_is_enabled(self.web_name, kind=self.kind)
def enable(self) -> None:
"""Enable the Apache configuration."""
privileged.enable(self.web_name, self.kind)
def disable(self) -> None:
"""Disable the Apache configuration."""
privileged.disable(self.web_name, self.kind)
def diagnose(self) -> list[DiagnosticCheck]:
"""Check if the web path is accessible by clients.
See :py:meth:`plinth.app.Component.diagnose`.
"""
results = []
for url in self.urls:
if '{host}' in url:
results.extend(
diagnose_url_on_all(url, check_certificate=False,
expect_redirects=self.expect_redirects,
component_id=self.component_id))
else:
results.append(
diagnose_url(url, check_certificate=False,
component_id=self.component_id))
return results
def setup(self, old_version: int):
"""Restart/reload web server if configuration files changed."""
if not old_version:
# App is being freshly setup. After setup, app will be enabled
# which will result in reload/restart of web server.
return
if old_version >= self.last_updated_version:
# Already using the latest configuration. Web server reload/restart
# is not necessary.
return
if not self.app.is_enabled():
# App is currently disabled, web server will reloaded/restarted
# when the app is enabled.
return
if self.kind == 'module':
service_privileged.restart('apache2')
else:
service_privileged.reload('apache2')
class WebserverRoot(app.FollowerComponent):
"""Component to enable/disable Apache configuration for domain root.
Each domain has a unique virtual host configuration in Apache. This file
includes an option configuration file that can dropped in by FreedomBox. If
an app wants to be hosted on a dedicated domain, it can provide a
configuration file that is meant to be in the <VirtualHost> section. Using
this component, the include file fragment for a selected domain can be
linked to app's configuration file. Then, for the selected domain, the
app's configuration becomes the domain's root configuration.
This components uses key/value store to remember the selected domain. When
the domain changes, the change must be notified using domain_set().
"""
def __init__(self, component_id: str, web_name: str,
expect_redirects: bool = False,
last_updated_version: int | None = None):
"""Initialize the web server component for domain root.
component_id should be a unique ID across all components of an app and
across all components.
web_name is the primary part of the configuration file path which must
be enabled/disabled by this component. The file's path should be
/etc/apache2/includes/<web_name>.conf.
expect_redirects is a boolean that allows redirects when trying to
access the domain URL during diagnosis of the component.
last_updated_version is the app version in which the web server
configuration/site/module file was updated. Using this, web server will
be automatically reloaded or restarted as necessary during app upgrade.
"""
super().__init__(component_id)
self.web_name = web_name
self.expect_redirects = expect_redirects
self.last_updated_version = last_updated_version or 0
def enable(self) -> None:
"""Link the Apache site root configuration to app configuration."""
domain = self.domain_get()
if domain:
privileged.link_root(domain, self.web_name)
def disable(self) -> None:
"""Unlink the Apache site root configuration from app configuration."""
domain = self.domain_get()
if domain:
privileged.unlink_root(domain)
def _key_get(self) -> str:
"""Return the key used to store the domain in kvstore."""
return f'{self.component_id}_domain'
def domain_get(self) -> str | None:
"""Return the currently configured domain name."""
return kvstore.get_default(self._key_get(), None)
def domain_set(self, domain: str | None):
"""Set the domain to use with the app."""
self.disable()
kvstore.set(self._key_get(), domain)
if self.app.is_enabled():
self.enable()
def diagnose(self) -> list[DiagnosticCheck]:
"""Check if the site root path is accessible by clients.
See :py:meth:`plinth.app.Component.diagnose`.
"""
results = []
domain = self.domain_get()
if domain:
results.append(
diagnose_url(f'https://{domain}', check_certificate=False,
component_id=self.component_id))
return results
def setup(self, old_version: int):
"""Restart/reload web server if configuration files changed."""
if not old_version:
# App is being freshly setup. After setup, app will be enabled
# which will result in reload/restart of web server.
return
if old_version >= self.last_updated_version:
# Already using the latest configuration. Web server reload/restart
# is not necessary.
return
if not self.app.is_enabled():
# App is currently disabled, web server will reloaded/restarted
# when the app is enabled.
return
service_privileged.reload('apache2')
def uninstall(self):
"""Remove the domain configured."""
kvstore.delete(self._key_get(), ignore_missing=True)
def diagnose_url(url: str, kind: str | None = None,
env: dict[str, str] | None = None,
check_certificate: bool = True,
extra_options: list[str] | None = None,
wrapper: str | None = None,
expected_output: str | None = None,
component_id: str | None = None) -> DiagnosticCheck:
"""Run a diagnostic on whether a URL is accessible.
Kind can be '4' for IPv4 or '6' for IPv6.
"""
try:
return_value = check_url(url, kind, env, check_certificate,
extra_options, wrapper, expected_output)
result = Result.PASSED if return_value else Result.FAILED
except FileNotFoundError:
result = Result.ERROR
parameters: DiagnosticCheckParameters = {'url': url, 'kind': kind}
if kind:
check_id = f'apache-url-kind-{url}-{kind}'
description = gettext_noop('Access URL {url} on tcp{kind}')
else:
check_id = f'apache-url-{url}'
description = gettext_noop('Access URL {url}')
return DiagnosticCheck(check_id, description, result, parameters,
component_id)
def diagnose_url_on_all(url: str, expect_redirects: bool = False,
component_id: str | None = None,
**kwargs) -> list[DiagnosticCheck]:
"""Run a diagnostic on whether a URL is accessible."""
results = []
for address in action_utils.get_addresses():
current_url = url.format(host=address['url_address'])
diagnose_kwargs = dict(kwargs)
if not expect_redirects:
diagnose_kwargs.setdefault('kind', address['kind'])
results.append(
diagnose_url(current_url, component_id=component_id,
**diagnose_kwargs))
return results
def check_url(url: str, kind: str | None = None,
env: dict[str, str] | None = None,
check_certificate: bool = True,
extra_options: list[str] | None = None,
wrapper: str | None = None,
expected_output: str | None = None) -> bool:
"""Check whether a URL is accessible."""
# When testing a URL with cURL, following any redirections with --location.
# During those follows, store cookies that have been set and use them for
# later requests. mod_auth_openidc will set a cookie 'x_csrf' to prevent
# CSRF attacks and expect this cookie to sent back to it in later requests.
# If this cookie is not present, it will refuse to perform OIDC Discovery
# process resulting 404 errors and diagnostic failures for domains that
# have not been visited by a user recently. --cookie '' means the cURL will
# use an in-process cookie-jar for storing and retrieving cookies without
# writing to a file on the disk.
command = [
'curl', '--location', '--cookie', '', '--fail', '--write-out',
'%{response_code}'
]
if kind == '6':
# extract zone index
match = re.match(r'(.*://)\[(.*)%(?P<zone>.*)\](.*)', url)
if match:
command = command + ['--interface', match.group('zone')]
url = '{0}[{1}]{2}'.format(*match.group(1, 2, 4))
command.append(url)
if wrapper:
command.insert(0, wrapper)
if not check_certificate:
command.append('-k')
if extra_options:
command.extend(extra_options)
if kind:
command.append({'4': '-4', '6': '-6'}[kind])
try:
process = subprocess.run(command, env=env, check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = True
if expected_output and expected_output not in process.stdout.decode():
result = False
except subprocess.CalledProcessError as exception:
result = False
# Authorization failed is a success
if exception.stdout.decode().strip() in ('401', '405'):
result = True
return result
@@ -0,0 +1,28 @@
## SPDX-License-Identifier: AGPL-3.0-or-later
##
## DO NOT EDIT. If you do, FreedomBox will not automatically upgrade.
##
## Apache configuration managed by FreedomBox. If customization is needed,
## create a new configuration file with higher priority and override directives.
##
##
## Macro to protect directories or locations (potentially backed by application
## proxies) with OpenID Connect. To use the macro add 'Use AuthOpenIDConnect'.
## By default, the visitor will need to be part of the 'admin' group to be able
## to access the resource. Add additional groups using 'Use RequireGroup
## <group>'. To debug OpenID Connect related communication add 'LogLevel
## auth_openidc:debug'.
##
<Macro AuthOpenIDConnect>
<IfModule mod_auth_openidc.c>
AuthType openid-connect
Require claim freedombox_groups:admin
</IfModule>
</Macro>
<Macro RequireGroup $group>
<IfModule mod_auth_openidc.c>
Require claim freedombox_groups:$group
</IfModule>
</Macro>
@@ -0,0 +1,41 @@
# Proxy all PHP file requests through PHP-FPM.
#
# Based on /etc/apache2/conf-available/php7.3-fpm.conf but modified to not break
# when PHP version upgrade happens due to php-fpm package depending on the
# latest version of PHP. Since PHP-FPM unix sockets have version number their
# path, to work with future version of PHP, hack assuming some future versions.
# Redirect to local php-fpm if mod_php is not available
<IfModule !mod_php7.c>
<IfModule proxy_fcgi_module>
# Enable http authorization headers
<IfModule setenvif_module>
SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1
</IfModule>
<FilesMatch ".+\.ph(ar|p|tml)$">
<If "-e '/run/php/php-fpm.sock'">
SetHandler "proxy:unix:/run/php/php-fpm.sock|fcgi://localhost"
</If>
<ElseIf "-e '/run/php/php7.4-fpm.sock'">
SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost"
</ElseIf>
<ElseIf "-e '/run/php/php7.3-fpm.sock'">
SetHandler "proxy:unix:/run/php/php7.3-fpm.sock|fcgi://localhost"
</ElseIf>
<Else>
Require all denied
</Else>
</FilesMatch>
<FilesMatch ".+\.phps$">
# Deny access to raw php sources by default
# To re-enable it's recommended to enable access to the files
# only in specific virtual host or directory
Require all denied
</FilesMatch>
# Deny access to files without filename (e.g. '.php')
<FilesMatch "^\.ph(ar|p|ps|tml)$">
Require all denied
</FilesMatch>
</IfModule>
</IfModule>
@@ -0,0 +1,6 @@
[apache-auth]
enabled = true
# Tweak the filter regex to work with journal format. Use apache-error as the
# syslog facility
filter = apache-auth[logtype="journal",logging="syslog",_daemon="apache-error"]
journalmatch = SYSLOG_IDENTIFIER=apache-error
@@ -0,0 +1 @@
plinth.modules.apache
+395
View File
@@ -0,0 +1,395 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Configure Apache web server."""
import glob
import json
import os
import pathlib
import re
import shutil
import urllib.parse
import augeas
from plinth import action_utils, utils
from plinth.actions import privileged, secret_str
openidc_config_path = pathlib.Path(
'/etc/apache2/conf-available/freedombox-openidc.conf')
metadata_dir_path = pathlib.Path(
'/var/cache/apache2/mod_auth_openidc/metadata/')
def _get_sort_key_of_version(version):
"""Return the sort key for a given version string.
Simple implementation hoping that PHP Apache module version numbers will be
simple.
"""
parts = []
for part in version.split('.'):
try:
parts.append(int(part))
except ValueError:
parts.append(part)
return parts
def _sort_versions(versions):
"""Return a list of sorted version strings."""
return sorted(versions, key=_get_sort_key_of_version, reverse=True)
def _disable_mod_php(webserver):
"""Disable all mod_php versions.
Idempotent and harmless if all or no PHP modules are identified.
Problematic if only some modules are found.
"""
paths = glob.glob('/etc/apache2/mods-available/php*.conf')
versions = []
for path in paths:
match = re.search(r'\/php(.*)\.conf$', path)
if match:
versions.append(match[1])
versions = _sort_versions(versions)
for version in versions:
webserver.disable('php' + version, kind='module')
@privileged
def setup(old_version: int):
"""Setup Apache configuration."""
# Regenerate the snakeoil self-signed SSL certificate. This is so that
# FreedomBox images don't all have the same certificate. When FreedomBox
# package is installed via apt, don't regenerate. When upgrading to newer
# version of Apache FreedomBox app and setting up for the first time don't
# regenerate.
if action_utils.is_disk_image() and old_version == 0:
action_utils.run([
'make-ssl-cert', 'generate-default-snakeoil', '--force-overwrite'
], check=True)
# In case the certificate has been removed after ssl-cert is installed
# on a fresh Debian machine.
elif not os.path.exists('/etc/ssl/certs/ssl-cert-snakeoil.pem'):
action_utils.run(['make-ssl-cert', 'generate-default-snakeoil'],
check=True)
_setup_oidc_config()
with action_utils.WebserverChange() as webserver:
# Disable mod_php as we have switched to mod_fcgi + php-fpm. Disable
# before switching away from mpm_prefork otherwise switching fails due
# dependency.
_disable_mod_php(webserver)
# set the prefork worker model
webserver.disable('mpm_worker', kind='module')
webserver.disable('mpm_prefork', kind='module')
webserver.enable('mpm_event', kind='module')
# enable miscellaneous modules.
webserver.enable('proxy', kind='module')
webserver.enable('proxy_http', kind='module')
webserver.enable('proxy_fcgi', kind='module')
webserver.enable('proxy_html', kind='module')
webserver.enable('rewrite', kind='module')
webserver.enable('macro', kind='module')
webserver.enable('expires', kind='module')
# Disable logging into files, use FreedomBox configured systemd logging
webserver.disable('other-vhosts-access-log', kind='config')
# Disable /server-status page to avoid leaking private info.
webserver.disable('status', kind='module')
# Enable HTTP/2 protocol
webserver.enable('http2', kind='module')
# Enable shared object cache needed for OSCP stapling. Needed by
# mod_ssl.
webserver.enable('socache_shmcb', kind='module')
# switch to mod_ssl from mod_gnutls
webserver.disable('gnutls', kind='module')
webserver.enable('ssl', kind='module')
# enable mod_alias for RedirectMatch
webserver.enable('alias', kind='module')
# enable mod_headers for HSTS
webserver.enable('headers', kind='module')
# Various modules for authentication/authorization
webserver.enable('auth_openidc', kind='module')
webserver.enable('authnz_ldap', kind='module')
webserver.disable('auth_pubtkt', kind='module')
# enable some critical modules to avoid restart while installing
# FreedomBox applications.
webserver.disable('cgi', kind='module') # For process MPMs
webserver.enable('cgid', kind='module') # For threaded MPMs
webserver.enable('proxy_uwsgi', kind='module')
webserver.enable('proxy_wstunnel', kind='module')
# enable configuration for PHP-FPM
webserver.enable('php-fpm-freedombox', kind='config')
# enable users to share files uploaded to ~/public_html
webserver.enable('userdir', kind='module')
# enable WebDAV protocol. Used by feather wiki and potentially by other
# apps and file sharing.
webserver.enable('dav', kind='module')
webserver.enable('dav_fs', kind='module')
# setup freedombox configuration
webserver.enable('10-freedombox', kind='config')
webserver.enable('freedombox', kind='config')
webserver.enable('freedombox-tls', kind='config')
webserver.enable('freedombox-openidc.conf', kind='config')
# enable serving Debian javascript libraries
webserver.enable('javascript-common', kind='config')
# default sites
webserver.disable('000-default', kind='site')
webserver.disable('default-tls', kind='site')
webserver.disable('default-ssl', kind='site')
webserver.disable('plinth', kind='site')
webserver.disable('plinth-ssl', kind='site')
webserver.enable('freedombox-default', kind='site')
def _load_augeas():
"""Initialize augeas for this app's configuration file."""
aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
augeas.Augeas.NO_MODL_AUTOLOAD)
aug.transform('Httpd', str(openidc_config_path))
aug.set('/augeas/context', '/files' + str(openidc_config_path))
aug.load()
return aug
def _get_mod_openidc_passphrase() -> str:
"""Read existing mod-auth-openidc passphase.
Instead of generating a new passphrase every time, use existing one. If the
passphrase changes, all the existing sessions will be logged out and users
will have login to apps again.
"""
aug = _load_augeas()
for directive in aug.match('*/directive'):
if aug.get(directive) == 'OIDCCryptoPassphrase':
return aug.get(directive + '/arg')
# Does not exist already, generate new
return utils.generate_password(size=64)
@privileged
def setup_oidc_client(netloc: str, client_id: str, client_secret: secret_str):
"""Setup client ID and secret for provided domain.
netloc is hostname or IP address along with port as parsed by
urllib.parse.urlparse() method from a URL.
"""
issuer = f'{netloc}/freedombox/o'
issuer_quoted = urllib.parse.quote_plus(issuer)
client_path = metadata_dir_path / f'{issuer_quoted}.client'
if client_path.exists():
try:
current_data = json.loads(client_path.read_text())
if (current_data['client_id'] == client_id
and current_data['client_secret'] == client_secret):
return
except Exception:
pass
client_configuration = {
'client_id': client_id,
'client_secret': client_secret
}
previous_umask = os.umask(0o077)
try:
client_path.write_text(json.dumps(client_configuration))
finally:
os.umask(previous_umask)
shutil.chown(client_path, 'www-data', 'www-data')
def _setup_oidc_config():
"""Setup Apache as a OpenID Connect Relying Party.
Ensure that auth_openidc module's metadata directory is created. It will be
used to store provider-specific configuration. Since FreedomBox will be
configured with multiple domains and some of them may not be accessible due
to the access method, we need to configure a separate IDP for each domain.
This is also because auth_openidc does not allow IDP configuration with
relative URLs.
Keep the metadata directory and configuration file unreadable by non-admin
users since they contain module's crypto secret and OIDC client secret.
# Session management
When apps like Syncthing are protected with mod_auth_openidc, there a
session maintained using server-side session storage and a cookie on the
client side. This session is different from the session managed by the
OpenID Connect Provider (FreedomBox web interface). As long as this session
is valid, no further authentication mechanisms are triggered.
When the session expires, if the request is a GET request (due to page
reload), the browser is redirected to OP, a fresh token is created, and the
page is loaded. However, for POST requests, 401 error is returned and if
the application is unaware, it won't do much about it. So, this
necessitates keeping the session timeout value high.
When logout is performed on FreedomBox web interface, mod_auth_openidc
cookie is also removed and logout feels instantaneous. However, this won't
work for applications not using mod_auth_openidc and for applications
hosted on other domains. A better way to do this is to implement OpenID
Connect's Back-Channel Logout or using OpenID Connect Session Management.
For more about session management see:
https://github.com/OpenIDC/mod_auth_openidc/wiki/Sessions-and-Timeouts and
https://github.com/OpenIDC/mod_auth_openidc/wiki/Session-Management-Settings
"""
metadata_dir_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
metadata_dir_path.mkdir(mode=0o700, exist_ok=True)
shutil.chown(metadata_dir_path.parent, 'www-data', 'www-data')
shutil.chown(metadata_dir_path, 'www-data', 'www-data')
# XXX: Default cache type is 'shm' or shared memory. This is lost when
# Apache is restarted and users/apps will have to reauthenticate. Improve
# this by using file (in tmpfs), redis, or memache caches.
passphrase = _get_mod_openidc_passphrase()
configuration = f'''##
## OpenID Connect related configuration
##
<IfModule mod_auth_openidc.c>
OIDCCryptoPassphrase {passphrase}
OIDCMetadataDir {str(metadata_dir_path)}
# Use relative URL to redirect to the same origin as the resource
OIDCDiscoverURL /freedombox/apache/discover-idp/
OIDCSSLValidateServer Off
OIDCProviderMetadataRefreshInterval 86400
# Expire the mod_auth_openidc session (not the OpenID Conneect Provider
# session) after 10 hours of idle with a maximum session duration equal to
# the expiry time of the ID token (10 hours). This allows applications such
# as FeatherWiki to have long editing sessions before save.
OIDCSessionInactivityTimeout 36000
OIDCSessionMaxDuration 0
# Use relative URL to return to the original domain
OIDCRedirectURI /apache/oidc/callback
OIDCRemoteUserClaim sub
# The redirect URI must always be under a location protected by
# mod_openidc.
<Location /apache>
AuthType openid-connect
# Checking audience is not necessary, but we need to check some claim.
Require claim aud:apache
</Location>
</IfModule>
'''
previous_umask = os.umask(0o077)
try:
openidc_config_path.write_text(configuration)
finally:
os.umask(previous_umask)
# TODO: Check that the (name, kind) is a managed by FreedomBox before
# performing operation.
@privileged
def enable(name: str, kind: str):
"""Enable an Apache site/config/module."""
_assert_kind(kind)
action_utils.webserver_enable(name, kind)
@privileged
def disable(name: str, kind: str):
"""Disable an Apache site/config/module."""
_assert_kind(kind)
action_utils.webserver_disable(name, kind)
def _assert_kind(kind: str):
"""Raise and exception if kind parameter has an unexpected value."""
if kind not in ('site', 'config', 'module'):
raise ValueError('Invalid value for parameter kind')
@privileged
def link_root(domain: str, name: str):
"""Link the Apache site root configuration to app configuration."""
if '/' in domain or '/' in name:
raise ValueError('Invalid domain or name')
target_config = f'{name}.conf'
include_root = pathlib.Path('/etc/apache2/includes/')
config = include_root / f'{domain}-include-freedombox.conf'
config.unlink(missing_ok=True)
config.symlink_to(target_config)
action_utils.service_reload('apache2')
@privileged
def unlink_root(domain: str):
"""Unlink the Apache site root configuration from app configuration."""
if '/' in domain:
raise ValueError('Invalid domain')
include_root = pathlib.Path('/etc/apache2/includes/')
config = include_root / f'{domain}-include-freedombox.conf'
if not config.is_symlink():
return # Does not exist or not a symlink
config.unlink()
action_utils.service_reload('apache2')
@privileged
def domain_setup(domain: str):
"""Add site specific configuration for a domain."""
if '/' in domain:
raise ValueError('Invalid domain')
path = pathlib.Path('/etc/apache2/sites-available/')
path = path / (domain + '.conf')
configuration = 'Use FreedomBoxTLSSiteMacro {domain}\n'
if path.is_file():
return # File already exists. Assume it to be correct one.
path.write_text(configuration.format(domain=domain))
with action_utils.WebserverChange() as webserver:
webserver.enable('freedombox-tls-site-macro', kind='config')
webserver.enable(domain, kind='site')
@privileged
def domain_remove(domain: str):
"""Remove site specific configuration for a domain."""
if '/' in domain:
raise ValueError('Invalid domain')
with action_utils.WebserverChange() as webserver:
webserver.disable(domain, kind='site')
path = pathlib.Path('/etc/apache2/sites-available/')
path = path / (domain + '.conf')
path.unlink(missing_ok=True)
Whitespace-only changes.
@@ -0,0 +1,453 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Test module for webserver components.
"""
import subprocess
from unittest.mock import Mock, PropertyMock, call, patch
import pytest
from plinth import app, kvstore
from plinth.diagnostic_check import DiagnosticCheck, Result
from plinth.modules.apache.components import (Webserver, WebserverRoot,
check_url, diagnose_url,
diagnose_url_on_all)
def test_webserver_init():
"""Test that webserver component can be initialized."""
with pytest.raises(ValueError):
Webserver(None, None)
webserver = Webserver('test-webserver', 'test-config', kind='module',
urls=['url1', 'url2'], expect_redirects=True)
assert webserver.component_id == 'test-webserver'
assert webserver.web_name == 'test-config'
assert webserver.kind == 'module'
assert webserver.urls == ['url1', 'url2']
assert webserver.expect_redirects
webserver = Webserver('test-webserver', None)
assert webserver.kind == 'config'
assert webserver.urls == []
assert not webserver.expect_redirects
@patch('plinth.action_utils.webserver_is_enabled')
def test_webserver_is_enabled(webserver_is_enabled):
"""Test that checking webserver configuration enabled works."""
webserver = Webserver('test-webserver', 'test-config', kind='module')
webserver_is_enabled.return_value = True
assert webserver.is_enabled()
webserver_is_enabled.assert_has_calls([call('test-config', kind='module')])
webserver_is_enabled.reset_mock()
webserver_is_enabled.return_value = False
assert not webserver.is_enabled()
webserver_is_enabled.assert_has_calls([call('test-config', kind='module')])
@patch('plinth.modules.apache.privileged.enable')
def test_webserver_enable(enable):
"""Test that enabling webserver configuration works."""
webserver = Webserver('test-webserver', 'test-config', kind='module')
webserver.enable()
enable.assert_has_calls([call('test-config', 'module')])
@patch('plinth.modules.apache.privileged.disable')
def test_webserver_disable(disable):
"""Test that disabling webserver configuration works."""
webserver = Webserver('test-webserver', 'test-config', kind='module')
webserver.disable()
disable.assert_has_calls([call('test-config', 'module')])
@patch('plinth.modules.apache.components.diagnose_url')
@patch('plinth.modules.apache.components.diagnose_url_on_all')
def test_webserver_diagnose(diagnose_url_on_all, diagnose_url):
"""Test running diagnostics."""
def on_all_side_effect(url, check_certificate, expect_redirects,
component_id):
return [
DiagnosticCheck('test-all-id', 'test-result-' + url, 'success', {},
component_id)
]
def side_effect(url, check_certificate, component_id):
return DiagnosticCheck('test-id', 'test-result-' + url, 'success', {},
component_id)
diagnose_url_on_all.side_effect = on_all_side_effect
diagnose_url.side_effect = side_effect
webserver1 = Webserver('test-webserver', 'test-config',
urls=['{host}url1', 'url2'], expect_redirects=True)
results = webserver1.diagnose()
assert results == [
DiagnosticCheck('test-all-id', 'test-result-{host}url1', 'success', {},
'test-webserver'),
DiagnosticCheck('test-id', 'test-result-url2', 'success', {},
'test-webserver')
]
diagnose_url_on_all.assert_has_calls([
call('{host}url1', check_certificate=False, expect_redirects=True,
component_id='test-webserver')
])
diagnose_url.assert_has_calls(
[call('url2', check_certificate=False, component_id='test-webserver')])
diagnose_url_on_all.reset_mock()
webserver2 = Webserver('test-webserver', 'test-config',
urls=['{host}url1', 'url2'], expect_redirects=False)
results = webserver2.diagnose()
diagnose_url_on_all.assert_has_calls([
call('{host}url1', check_certificate=False, expect_redirects=False,
component_id='test-webserver')
])
@patch('plinth.privileged.service.restart')
@patch('plinth.privileged.service.reload')
def test_webserver_setup(service_reload, service_restart):
"""Test that component restart/reloads web server during app upgrades."""
class AppTest(app.App):
app_id = 'testapp'
enabled = False
def is_enabled(self):
return self.enabled
app1 = AppTest()
# Don't fail when last_updated_version is not provided.
webserver1 = Webserver('test-webserver1', 'test-config')
assert webserver1.last_updated_version == 0
webserver1.setup(old_version=10)
service_reload.assert_not_called()
service_restart.assert_not_called()
webserver1 = Webserver('test-webserver1', 'test-config',
last_updated_version=5)
for version in (0, 5, 6):
webserver1.setup(old_version=version)
service_reload.assert_not_called()
service_restart.assert_not_called()
app1.enabled = False
webserver2 = Webserver('test-webserver2', 'test-config',
last_updated_version=5)
app1.add(webserver2)
webserver2.setup(old_version=3)
service_reload.assert_not_called()
service_restart.assert_not_called()
app1.enabled = True
webserver3 = Webserver('test-webserver3', 'test-config',
last_updated_version=5)
app1.add(webserver3)
webserver3.setup(old_version=3)
service_reload.assert_has_calls([call('apache2')])
service_restart.assert_not_called()
service_reload.reset_mock()
webserver4 = Webserver('test-webserver', 'test-module', 'module',
last_updated_version=5)
app1.add(webserver4)
webserver4.setup(old_version=3)
service_restart.assert_has_calls([call('apache2')])
service_reload.assert_not_called()
def test_webserver_root_init():
"""Test that webserver root component can be initialized."""
with pytest.raises(ValueError):
WebserverRoot(None, None)
webserver = WebserverRoot('test-webserverroot', 'test-config',
expect_redirects=True, last_updated_version=10)
assert webserver.component_id == 'test-webserverroot'
assert webserver.web_name == 'test-config'
assert webserver.expect_redirects
assert webserver.last_updated_version == 10
webserver = WebserverRoot('test-webserverroot', None)
assert not webserver.expect_redirects
assert webserver.last_updated_version == 0
@patch('plinth.modules.apache.privileged.link_root')
def test_webserver_root_enable(link_root):
"""Test that enabling webserver root works."""
webserver = WebserverRoot('test-webserver', 'test-config')
with patch('plinth.modules.apache.components.WebserverRoot.domain_get'
) as get:
get.return_value = None
webserver.enable()
link_root.assert_not_called()
get.return_value = 'x-domain'
webserver.enable()
link_root.assert_has_calls([call('x-domain', 'test-config')])
@patch('plinth.modules.apache.privileged.unlink_root')
def test_webserver_root_disable(unlink_root):
"""Test that disabling webserver root works."""
webserver = WebserverRoot('test-webserver', 'test-config')
with patch('plinth.modules.apache.components.WebserverRoot.domain_get'
) as get:
get.return_value = None
webserver.disable()
unlink_root.assert_not_called()
get.return_value = 'x-domain'
webserver.disable()
unlink_root.assert_has_calls([call('x-domain')])
@pytest.mark.django_db
def test_webserver_root_domain_get():
"""Test retrieving webserver root's domain."""
webserver = WebserverRoot('test-webserver', 'test-config')
assert webserver.domain_get() is None
kvstore.set('test-webserver_domain', 'test-domain')
assert webserver.domain_get() == 'test-domain'
@pytest.mark.django_db
@patch('plinth.modules.apache.privileged.unlink_root')
@patch('plinth.modules.apache.privileged.link_root')
@patch('plinth.app.Component.app', new_callable=PropertyMock)
def test_webserver_root_domain_set(component_app, link_root, unlink_root):
"""Test setting webserver root's domain."""
webserver = WebserverRoot('test-webserver', 'test-config')
assert webserver.domain_get() is None
app = Mock()
component_app.return_value = app
app.is_enabled.return_value = True
webserver.domain_set('test-domain')
assert unlink_root.mock_calls == []
assert webserver.domain_get() == 'test-domain'
assert link_root.mock_calls == [call('test-domain', 'test-config')]
link_root.reset_mock()
app.is_enabled.return_value = False
assert not webserver.app.is_enabled()
webserver.domain_set('test-domain2')
assert unlink_root.mock_calls == [call('test-domain')]
assert webserver.domain_get() == 'test-domain2'
assert link_root.mock_calls == []
webserver.domain_set(None)
assert webserver.domain_get() is None
@pytest.mark.django_db
@patch('plinth.modules.apache.components.WebserverRoot.disable')
@patch('plinth.modules.apache.components.WebserverRoot.enable')
@patch('plinth.modules.apache.components.diagnose_url')
@patch('plinth.app.Component.app', new_callable=PropertyMock)
def test_webserver_root_diagnose(component_app, diagnose_url, enable, disable):
"""Test running diagnostics on webserver root component."""
webserver = WebserverRoot('test-webserver', 'test-config')
assert webserver.diagnose() == []
webserver.domain_set('test-domain')
result = DiagnosticCheck('test-all-id', 'test-result', 'success', {},
'message')
diagnose_url.return_value = result
assert webserver.diagnose() == [result]
@patch('plinth.privileged.service.reload')
def test_webserver_root_setup(service_reload):
"""Test that component reloads web server during app upgrades."""
class AppTest(app.App):
app_id = 'testapp'
enabled = False
def is_enabled(self):
return self.enabled
app1 = AppTest()
# Don't fail when last_updated_version is not provided.
webserver1 = WebserverRoot('test-webserverroot1', 'test-config')
assert webserver1.last_updated_version == 0
webserver1.setup(old_version=10)
service_reload.assert_not_called()
webserver1 = WebserverRoot('test-webserverroot1', 'test-config',
last_updated_version=5)
for version in (0, 5, 6):
webserver1.setup(old_version=version)
service_reload.assert_not_called()
app1.enabled = False
webserver2 = WebserverRoot('test-webserver2', 'test-config',
last_updated_version=5)
app1.add(webserver2)
webserver2.setup(old_version=3)
service_reload.assert_not_called()
app1.enabled = True
webserver3 = WebserverRoot('test-webserver3', 'test-config',
last_updated_version=5)
app1.add(webserver3)
webserver3.setup(old_version=3)
service_reload.assert_has_calls([call('apache2')])
service_reload.reset_mock()
@pytest.mark.django_db
@patch('plinth.modules.apache.components.WebserverRoot.disable')
@patch('plinth.modules.apache.components.WebserverRoot.enable')
@patch('plinth.app.Component.app', new_callable=PropertyMock)
def test_webserver_root_uninstall(component_app, enable, disable):
"""Test that component removes the DB key during uninstall."""
webserver = WebserverRoot('test-webserver', 'test-config')
webserver.uninstall()
assert kvstore.get_default('test-webserver_domain', 'x-value') == 'x-value'
webserver.domain_set('test-domain')
assert kvstore.get('test-webserver_domain') == 'test-domain'
webserver.uninstall()
assert kvstore.get_default('test-webserver_domain', 'x-value') == 'x-value'
@patch('plinth.modules.apache.components.check_url')
@patch('plinth.action_utils.get_addresses')
def test_diagnose_url(get_addresses, check):
"""Test diagnosing a URL."""
args = {
'url': 'https://localhost/test',
'kind': '4',
'env': {
'test': 'value'
},
'check_certificate': False,
'extra_options': {
'test-1': 'value-1'
},
'wrapper': 'test-wrapper',
'expected_output': 'test-expected',
'component_id': 'test-component',
}
parameters = {key: args[key] for key in ['url', 'kind']}
check.return_value = True
result = diagnose_url(**args)
assert result == DiagnosticCheck(
'apache-url-kind-https://localhost/test-4',
'Access URL {url} on tcp{kind}', Result.PASSED, parameters,
'test-component')
check.return_value = False
result = diagnose_url(**args)
assert result == DiagnosticCheck(
'apache-url-kind-https://localhost/test-4',
'Access URL {url} on tcp{kind}', Result.FAILED, parameters,
'test-component')
del args['kind']
args['url'] = 'https://{host}/test'
check.return_value = True
get_addresses.return_value = [{
'kind': '4',
'address': 'test-host-1',
'numeric': False,
'url_address': 'test-host-1'
}, {
'kind': '6',
'address': 'test-host-2',
'numeric': False,
'url_address': 'test-host-2'
}]
parameters = [
{
'url': 'https://test-host-1/test',
'kind': '4'
},
{
'url': 'https://test-host-2/test',
'kind': '6'
},
]
results = diagnose_url_on_all(**args)
assert results == [
DiagnosticCheck('apache-url-kind-https://test-host-1/test-4',
'Access URL {url} on tcp{kind}', Result.PASSED,
parameters[0], 'test-component'),
DiagnosticCheck('apache-url-kind-https://test-host-2/test-6',
'Access URL {url} on tcp{kind}', Result.PASSED,
parameters[1], 'test-component'),
]
@patch('subprocess.run')
def test_check_url(run):
"""Test checking whether a URL is accessible."""
url = 'http://localhost/test'
basic_command = [
'curl', '--location', '--cookie', '', '--fail', '--write-out',
'%{response_code}'
]
extra_args = {'env': None, 'check': True, 'stdout': -1, 'stderr': -1}
# Basic
assert check_url(url)
run.assert_called_with(basic_command + [url], **extra_args)
# Wrapper
check_url(url, wrapper='test-wrapper')
run.assert_called_with(['test-wrapper'] + basic_command + [url],
**extra_args)
# No certificate check
check_url(url, check_certificate=False)
run.assert_called_with(basic_command + [url, '-k'], **extra_args)
# Extra options
check_url(url, extra_options=['test-opt1', 'test-opt2'])
run.assert_called_with(basic_command + [url, 'test-opt1', 'test-opt2'],
**extra_args)
# TCP4/TCP6
check_url(url, kind='4')
run.assert_called_with(basic_command + [url, '-4'], **extra_args)
check_url(url, kind='6')
run.assert_called_with(basic_command + [url, '-6'], **extra_args)
# IPv6 Link Local URLs
check_url('https://[::2%eth0]/test', kind='6')
run.assert_called_with(
basic_command + ['--interface', 'eth0', 'https://[::2]/test', '-6'],
**extra_args)
# Failure
exception = subprocess.CalledProcessError(returncode=1, cmd=['curl'])
run.side_effect = exception
run.side_effect.stdout = b'500'
assert not check_url(url)
# Return code 401, 405
run.side_effect = exception
run.side_effect.stdout = b' 401 '
assert check_url(url)
run.side_effect.stdout = b'405\n'
assert check_url(url)
# Error
run.side_effect = FileNotFoundError()
with pytest.raises(FileNotFoundError):
assert check_url(url)
@@ -0,0 +1,31 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Test module for (U)ser (Web) (S)ites.
"""
from plinth.modules.apache import (user_of_uws_directory, user_of_uws_url,
uws_directory_of_url, uws_directory_of_user,
uws_url_of_directory, uws_url_of_user)
def test_uws_namings():
"""Test name solvers for user, url and directory of UWS."""
assert '/home/usr/public_html' == uws_directory_of_user('usr')
assert '/~usr/' == uws_url_of_user('usr')
f = user_of_uws_directory
assert f('/home/usr/lacks/the/UWS/directory') is None
assert 'usr' == f('/home/usr/public_html/is/a/normal/UWS/file')
assert 'usr' == f('/home/usr/public_html/is/a/normal/UWS/path/')
assert '€.;#@|' == f('/home/€.;#@|/public_html/is/stange/but/valid/')
f = user_of_uws_url
assert f('/usr/is/not/a/valid/UWS/url/due/to/missing/tilde') is None
assert 'usr' == f('whatever/~usr/is/considered/a/valid/UWS/path')
assert 'usr' == f('~usr')
assert 'usr' == f('~usr/')
assert 'usr' == f('/~usr/')
assert '/home/usr/public_html' == uws_directory_of_url('~usr/any/file')
assert '/~usr/' == uws_url_of_directory('/home/usr/public_html/any/file')
+12
View File
@@ -0,0 +1,12 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""URLs for the Apache module."""
from django.urls import re_path
from stronghold.decorators import public
from .views import DiscoverIDPView
urlpatterns = [
re_path(r'^apache/discover-idp/$', public(DiscoverIDPView.as_view()),
name='discover-idp'),
]
+71
View File
@@ -0,0 +1,71 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Views for the Apache app."""
from urllib.parse import urlencode, urlparse
from django.http import (HttpResponseBadRequest, HttpResponseRedirect,
HttpResponseServerError)
from django.views import View
from . import setup_oidc_client, validate_host
# By default 'openid' scope already included by mod_auth_openidc
OIDC_SCOPES = 'email freedombox_groups'
class DiscoverIDPView(View):
"""A view called by auth_openidc Apache module to find the IDP.
According to documentation for auth_openidc: an Issuer selection can be
passed back to the callback URL as in:
<callback-url>?iss=[${issuer}|${domain}|${e-mail-style-account-name}]
[parameters][&login_hint=<login-hint>][&scopes=<scopes>]
[&auth_request_params=<params>]
where the <iss> parameter contains the URL-encoded issuer value of the
selected Provider (or...), [parameters] contains the additional parameters
that were passed in on the discovery request (e.g.
target_link_uri=<url>&x_csrf=<x_csrf>&method=<method>&scopes=<scopes>)
"""
def get(self, request):
"""Redirect back to auth_openidc module after selecting a IDP."""
target_link_uri = request.GET.get('target_link_uri', '')
method = request.GET.get('method', 'get')
x_csrf = request.GET.get('x_csrf', '')
oidc_callback = request.GET.get('oidc_callback')
if method != 'get':
return HttpResponseBadRequest(f'Cannot handle "{method}" method')
oidc_callback_parts = urlparse(oidc_callback)
request_host = request.get_host()
if request_host != oidc_callback_parts.netloc:
return HttpResponseBadRequest(
f'Cannot redirect from {request_host} to a different host '
f'{oidc_callback_parts.netloc}')
try:
validate_host(oidc_callback_parts.hostname)
except ValueError:
return HttpResponseBadRequest(
f'Accessed using unknown domain {request_host}. Please add '
'the domain to list of configured domains.')
try:
setup_oidc_client(oidc_callback_parts.netloc,
oidc_callback_parts.hostname)
except ValueError:
return HttpResponseServerError(
f'Server not configured to called as {request_host}')
url = '/apache/oidc/callback'
params = {
'iss': f'https://{request_host}/freedombox/o',
'target_link_uri': target_link_uri,
'method': method,
'x_csrf': x_csrf,
'scopes': OIDC_SCOPES,
}
params = urlencode(params)
return HttpResponseRedirect(f'{url}?{params}')