Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b123802275 | ||
|
|
389bc07541 | ||
|
|
2d2cd1837e | ||
|
|
1933827a1c | ||
|
|
c4db2ec55f | ||
|
|
35b40af593 | ||
|
|
74b1ccec2a | ||
|
|
d691e20b16 | ||
|
|
1bd09f8cd7 | ||
|
|
0de4d0c854 | ||
|
|
23e6e01303 | ||
|
|
f8643bf60d | ||
|
|
f5e8e84e3c | ||
|
|
2f686b6499 | ||
|
|
22205f4e4b |
No files matched your search
@@ -20,6 +20,8 @@ work items in [Gitea issues][issues]. Published versions and their release
|
|||||||
notes are available on [Gitea Releases][releases].
|
notes are available on [Gitea Releases][releases].
|
||||||
|
|
||||||
See [Contributing](CONTRIBUTING.md) for the project workflow.
|
See [Contributing](CONTRIBUTING.md) for the project workflow.
|
||||||
|
See [Security](docs/security.md) for deployment hardening and private
|
||||||
|
vulnerability reporting.
|
||||||
|
|
||||||
[milestones]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/milestones
|
[milestones]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/milestones
|
||||||
[issues]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/issues
|
[issues]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/issues
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ if [ ! -x "$venv/bin/python" ]; then
|
|||||||
python3 -m venv "$venv"
|
python3 -m venv "$venv"
|
||||||
fi
|
fi
|
||||||
if [ -z "$installed" ]; then
|
if [ -z "$installed" ]; then
|
||||||
"$venv/bin/pip" install .
|
"$venv/bin/python" -m pip install --only-binary=:all: 'pip>=26.2'
|
||||||
|
"$venv/bin/python" -m pip install .
|
||||||
fi
|
fi
|
||||||
exec "$venv/bin/coulobre-node-setup" install-receiver "$@"
|
exec "$venv/bin/coulobre-node-setup" install-receiver "$@"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
Match User coulobre-dns-request,coulobre-mail-request
|
Match User coulobre-dns-request,coulobre-mail-request,coulobre-dns-p-*,coulobre-mail-p-*
|
||||||
AuthenticationMethods publickey
|
AuthenticationMethods publickey
|
||||||
PubkeyAuthentication yes
|
PubkeyAuthentication yes
|
||||||
PasswordAuthentication no
|
PasswordAuthentication no
|
||||||
@@ -11,10 +11,10 @@ Match User coulobre-dns-request,coulobre-mail-request
|
|||||||
PermitTTY no
|
PermitTTY no
|
||||||
PermitUserRC no
|
PermitUserRC no
|
||||||
|
|
||||||
Match User coulobre-dns-request
|
Match User coulobre-dns-request,coulobre-dns-p-*
|
||||||
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-dns-apply.sock
|
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-dns-apply.sock
|
||||||
|
|
||||||
Match User coulobre-mail-request
|
Match User coulobre-mail-request,coulobre-mail-p-*
|
||||||
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-mail-apply.sock
|
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-mail-apply.sock
|
||||||
|
|
||||||
Match all
|
Match all
|
||||||
@@ -282,6 +282,18 @@ def install_release(release, *, step=nullcontext):
|
|||||||
if key in os.environ
|
if key in os.environ
|
||||||
}
|
}
|
||||||
with step("Installing Coulobre and its Python dependencies"):
|
with step("Installing Coulobre and its Python dependencies"):
|
||||||
|
run(
|
||||||
|
BINDIR / "python",
|
||||||
|
"-m",
|
||||||
|
"pip",
|
||||||
|
"install",
|
||||||
|
"--disable-pip-version-check",
|
||||||
|
"--only-binary=:all:",
|
||||||
|
"pip>=26.2",
|
||||||
|
label="Update the virtual environment installer",
|
||||||
|
env=pip_env,
|
||||||
|
timeout=1200,
|
||||||
|
)
|
||||||
run(
|
run(
|
||||||
BINDIR / "pip",
|
BINDIR / "pip",
|
||||||
"install",
|
"install",
|
||||||
@@ -860,12 +872,9 @@ class Installer:
|
|||||||
HEALTH_TIMER,
|
HEALTH_TIMER,
|
||||||
):
|
):
|
||||||
install_unit(unit)
|
install_unit(unit)
|
||||||
if not REMOTE_MODES.intersection(
|
install_unit("coulobre-update.socket")
|
||||||
(self.plan.dns.mode, self.plan.mail.mode)
|
install_unit("coulobre-update@.service")
|
||||||
):
|
workers.append("coulobre-update.socket")
|
||||||
install_unit("coulobre-update.socket")
|
|
||||||
install_unit("coulobre-update@.service")
|
|
||||||
workers.append("coulobre-update.socket")
|
|
||||||
systemctl("daemon-reload")
|
systemctl("daemon-reload")
|
||||||
systemctl(
|
systemctl(
|
||||||
"enable", "--now", *PANEL_UNITS, *workers, "apache2.service"
|
"enable", "--now", *PANEL_UNITS, *workers, "apache2.service"
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ User=root
|
|||||||
WorkingDirectory=/opt/coulobre
|
WorkingDirectory=/opt/coulobre
|
||||||
EnvironmentFile=/etc/coulobre/panel.env
|
EnvironmentFile=/etc/coulobre/panel.env
|
||||||
StateDirectory=coulobre-update
|
StateDirectory=coulobre-update
|
||||||
StateDirectoryMode=0755
|
StateDirectoryMode=0700
|
||||||
UMask=0077
|
UMask=0077
|
||||||
ExecStart=/opt/coulobre/bin/coulobre-update
|
ExecStart=/opt/coulobre/bin/coulobre-update
|
||||||
StandardInput=socket
|
StandardInput=socket
|
||||||
|
|||||||
+183
-7
@@ -496,6 +496,20 @@ connected. Follow their logs with `journalctl`.
|
|||||||
sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat
|
sudo journalctl -u coulobre-panel -u coulobre-worker -u coulobre-beat
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Manage panel roles
|
||||||
|
|
||||||
|
A verified superuser can assign a Customer or Customer manager role to an
|
||||||
|
active login from **Customers** or **Customer managers**. Choose **Assign
|
||||||
|
to existing login** and enter the username. Customer roles use their own
|
||||||
|
assigned hosting accounts. Customer managers use their own hosting account
|
||||||
|
assignments and hosting plan policy. New manager assignments use the default
|
||||||
|
customer manager profile when one is configured.
|
||||||
|
|
||||||
|
Logins with multiple roles can choose **Panel role** in the account area.
|
||||||
|
The role applies to the session, including direct page requests and actions.
|
||||||
|
Returning to the administrator role requires a verified second factor. If the
|
||||||
|
active role assignment is revoked, the session asks the user to sign in again.
|
||||||
|
|
||||||
## Select a panel theme
|
## Select a panel theme
|
||||||
|
|
||||||
The panel follows the browser's light or dark preference on the first visit.
|
The panel follows the browser's light or dark preference on the first visit.
|
||||||
@@ -542,7 +556,8 @@ From the unpacked source release, upgrade the existing virtual environment
|
|||||||
and use the [management command helper](#prepare-the-panel).
|
and use the [management command helper](#prepare-the-panel).
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo /opt/coulobre/bin/pip install --upgrade '.[server,mariadb]'
|
sudo /opt/coulobre/bin/python -m pip install --only-binary=:all: 'pip>=26.2'
|
||||||
|
sudo /opt/coulobre/bin/python -m pip install --upgrade '.[server,mariadb]'
|
||||||
panel_manage migrate --noinput
|
panel_manage migrate --noinput
|
||||||
panel_manage collectstatic --noinput
|
panel_manage collectstatic --noinput
|
||||||
```
|
```
|
||||||
@@ -587,9 +602,9 @@ without service checks, follow [the collector setup](#monitor-local-and-remote-s
|
|||||||
|
|
||||||
### Install a compatible release from the panel
|
### Install a compatible release from the panel
|
||||||
|
|
||||||
The installer enables **Updates** for single-server deployments. On an
|
The installer enables **Updates** for installer-managed panels. On an
|
||||||
existing installer-managed single server, install the updater units from the
|
existing panel, install the updater units from the source release matching
|
||||||
v0.10.1 source release after upgrading the package:
|
the installed package:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo install -m 0644 deploy/systemd/coulobre-update.socket \
|
sudo install -m 0644 deploy/systemd/coulobre-update.socket \
|
||||||
@@ -602,9 +617,19 @@ A superuser with a verified second factor can choose a compatible release
|
|||||||
from **Server and services → Updates**. The updater uses the official Gitea
|
from **Server and services → Updates**. The updater uses the official Gitea
|
||||||
release over HTTPS and checks the wheel against its published SHA-256 hash.
|
release over HTTPS and checks the wheel against its published SHA-256 hash.
|
||||||
It supports the installer-managed local MariaDB database and installer
|
It supports the installer-managed local MariaDB database and installer
|
||||||
layout. Use the in-place procedure for linked mail or DNS receivers, custom
|
layout. The update manifest lists the tested starting versions. Use the
|
||||||
service unit changes, and releases requiring new dependencies. The update
|
in-place procedure for custom service unit changes and for environments
|
||||||
manifest lists the tested starting versions.
|
missing a dependency required by the target version. From 0.11 onward, the
|
||||||
|
updater checks installed dependencies before stopping panel services.
|
||||||
|
|
||||||
|
Markdown release notes require `markdown-it-py` in the panel's virtual
|
||||||
|
environment. To use the web updater for the first release with this feature,
|
||||||
|
install the dependency before starting the update. The in-place procedure
|
||||||
|
installs it with the panel package.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo /opt/coulobre/bin/python -m pip install 'markdown-it-py>=4.3,<5'
|
||||||
|
```
|
||||||
|
|
||||||
The panel and its workers pause during the upgrade. Refresh **Updates** after
|
The panel and its workers pause during the upgrade. Refresh **Updates** after
|
||||||
the panel returns. The latest update status names the recovery directory in
|
the panel returns. The latest update status names the recovery directory in
|
||||||
@@ -623,6 +648,138 @@ verify sign-in and service health. Archive `status.json` as root after
|
|||||||
recovery to allow a later update. Check that `panel.sql` and `venv` exist
|
recovery to allow a later update. Check that `panel.sql` and `venv` exist
|
||||||
before restoring from a directory created by an interrupted update.
|
before restoring from a directory created by an interrupted update.
|
||||||
|
|
||||||
|
### Coordinate a release across linked mail and DNS receivers
|
||||||
|
|
||||||
|
Use the in-place procedure for the first upgrade from 0.10 to 0.11 in a
|
||||||
|
linked deployment. The older web updater supports single-server upgrades.
|
||||||
|
Bring the receiver and all attached panels to the same release before
|
||||||
|
resuming provisioning. For manually configured relays, including separate
|
||||||
|
mail credential and archive relays, use the in-place procedure for the
|
||||||
|
whole fleet.
|
||||||
|
|
||||||
|
The **Updates** page in 0.11 reports the release, host, and status probe
|
||||||
|
protocol of each installer-enrolled receiver. Protocol 1 reports readiness
|
||||||
|
and release. Protocol 2 also reports a staged maintenance target. This is
|
||||||
|
a read-only addition to the probe. The mail and DNS apply request formats
|
||||||
|
keep their existing per-operation versions. Active provisioning requires
|
||||||
|
matching package releases. During a coordinated upgrade, the receiver
|
||||||
|
keeps provisioning requests paused while panels are on different releases.
|
||||||
|
Normal mail delivery, IMAP, and existing DNS answers can continue while
|
||||||
|
the provisioning socket is stopped or paused.
|
||||||
|
|
||||||
|
1. At each receiver, list the authorized panel keys. Match each fingerprint
|
||||||
|
to a panel and confirm its installed version on that host. Include every
|
||||||
|
key, including panels operated by another team. Back up the panels, the
|
||||||
|
receiver packages, and the managed mail or DNS configuration. Pause
|
||||||
|
new provisioning requests and let current jobs finish.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo /opt/coulobre/bin/coulobre-node-setup list-panels dns
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Save a root-owned JSON inventory with mode 0600, the target package version and a
|
||||||
|
fingerprint-to-version map. Replace the fingerprints and versions with
|
||||||
|
your actual values. Make a separate inventory for each role on a host.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"target": "0.11.1rc1",
|
||||||
|
"panels": {
|
||||||
|
"SHA256:panel-one-fingerprint": "0.11.0rc1",
|
||||||
|
"SHA256:panel-two-fingerprint": "0.11.0rc1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Stop the receiver socket and let instances of the corresponding apply
|
||||||
|
service finish. Stage the inventory, update the receiver to the target,
|
||||||
|
then start its socket again. Replace `dns` with `mail` for a mail receiver.
|
||||||
|
The staged receiver answers status probes and rejects apply requests.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo systemctl stop coulobre-dns-apply.socket
|
||||||
|
sudo /opt/coulobre/bin/coulobre-node-setup begin-maintenance dns /root/dns-upgrade.json
|
||||||
|
# Install the reviewed target package using its release instructions.
|
||||||
|
sudo systemctl start coulobre-dns-apply.socket
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Refresh **Updates** on each panel. Install the target when all its
|
||||||
|
receivers report that release in maintenance mode and the compatible
|
||||||
|
release is offered. Use the in-place procedure if its update requires
|
||||||
|
additional dependencies or unit changes. Keep the receivers staged if
|
||||||
|
any panel upgrade is interrupted. Check the recovery files and repair or
|
||||||
|
roll back before reopening provisioning.
|
||||||
|
5. Once every panel is running and verified at the target, update each
|
||||||
|
inventory with the observed installed versions. Finish maintenance on each
|
||||||
|
receiver, then resume provisioning and retry any affected operations.
|
||||||
|
The command checks the receiver release and the inventory against the
|
||||||
|
current authorized keys. The receiver administrator is responsible for
|
||||||
|
checking the installed version reported by every panel operator.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo /opt/coulobre/bin/coulobre-node-setup finish-maintenance dns /root/dns-upgrade.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### Limit linked provisioning to assigned domains
|
||||||
|
|
||||||
|
Use scoped keys when independent panels share a DNS or mail receiver. The
|
||||||
|
receiver authenticates a dedicated Unix account for each panel and checks
|
||||||
|
the requested domain before applying changes or inspecting its mail queue.
|
||||||
|
Each scope lists exact domains. DNS parent and child zones must belong to
|
||||||
|
the same panel if their scopes overlap.
|
||||||
|
|
||||||
|
Upgrade the receiver and the panels, then apply the current receiver SSH
|
||||||
|
configuration with `coulobre-node-setup --source /path/to/release
|
||||||
|
install-receiver dns` (or `mail`). Prepare the panel's role-specific key.
|
||||||
|
Copy its public half to the receiver and authorize the domains.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# On the panel
|
||||||
|
sudo /opt/coulobre/bin/coulobre-node-setup prepare-panel dns
|
||||||
|
|
||||||
|
# On the receiver
|
||||||
|
sudo /opt/coulobre/bin/coulobre-node-setup authorize-scoped-panel \
|
||||||
|
dns panel-one /root/panel-one-dns.pub example.net
|
||||||
|
|
||||||
|
# On the panel, using the receiver's verified host key
|
||||||
|
sudo /opt/coulobre/bin/coulobre-node-setup --source /path/to/release \
|
||||||
|
enrol-panel dns dns.example.org /root/dns-host.pub --scope panel-one
|
||||||
|
```
|
||||||
|
|
||||||
|
Repeat authorization with the same public key and the complete desired
|
||||||
|
domain list when assignments change. For an existing unrestricted receiver,
|
||||||
|
coordinate a maintenance window, back up and remove unrestricted panel
|
||||||
|
keys, enroll the scoped identities, and check both panels before resuming
|
||||||
|
provisioning. For an existing panel relay, update the `User` directive in
|
||||||
|
its role-specific `/etc/coulobre-remote/<role>/ssh_config` to the scoped
|
||||||
|
username printed by authorization. Keep its pinned host key and run
|
||||||
|
`coulobre-node-setup check-panel <role>` before enabling jobs.
|
||||||
|
|
||||||
|
On scoped mail receivers, use local administrative workflows for mailbox
|
||||||
|
credential and archive operations. The separate legacy SSH transports for
|
||||||
|
those operations are unavailable on a scoped receiver. Local mail
|
||||||
|
delivery and IMAP keep using their existing configuration.
|
||||||
|
|
||||||
|
### Use SHA-2 for new managed database logins
|
||||||
|
|
||||||
|
On a MariaDB build with `auth_mysql_sha2`, you can provision new managed
|
||||||
|
database logins with `caching_sha2_password`. Verify the active site's PHP
|
||||||
|
driver, phpMyAdmin, and administrative clients against a test login before
|
||||||
|
changing the policy. Coulobre retains the authentication plugin and password
|
||||||
|
for each existing login.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo mariadb -e "INSTALL SONAME 'auth_mysql_sha2';"
|
||||||
|
printf '%s\n' caching_sha2_password | sudo tee /etc/coulobre/database-authentication
|
||||||
|
sudo chown root:root /etc/coulobre/database-authentication
|
||||||
|
sudo chmod 0644 /etc/coulobre/database-authentication
|
||||||
|
```
|
||||||
|
|
||||||
|
Managed logins remain restricted to localhost. If the target host needs an
|
||||||
|
older driver or does not supply the SHA-2 plugin, use
|
||||||
|
`mysql_native_password` as the policy for new logins. Keep the SHA-2 plugin
|
||||||
|
loaded as long as any existing managed login uses it.
|
||||||
|
|
||||||
### Upgrade from v0.9 to v0.10
|
### Upgrade from v0.9 to v0.10
|
||||||
|
|
||||||
Use the in-place procedure above with the v0.10 source release. Keep a copy
|
Use the in-place procedure above with the v0.10 source release. Keep a copy
|
||||||
@@ -2514,6 +2671,25 @@ Keep the managed data directories on their service filesystems to allow
|
|||||||
an atomic move into the archive directory. Existing backup archives remain
|
an atomic move into the archive directory. Existing backup archives remain
|
||||||
available to operators with backup access.
|
available to operators with backup access.
|
||||||
|
|
||||||
|
## Configure installed features in the panel
|
||||||
|
|
||||||
|
Open **About Coulobre → Configure features** as a superuser with a verified
|
||||||
|
second factor. The page shows the installation prerequisites and distinguishes
|
||||||
|
local mail and DNS services from linked receivers. Use **Configure DNS
|
||||||
|
defaults** to edit the zone template for new hosting accounts.
|
||||||
|
|
||||||
|
The switches control which installed capabilities the panel offers for new
|
||||||
|
actions. Existing managed sites, mailbox delivery, published DNS records,
|
||||||
|
schedules and queued provisioning continue running. Backup archives remain
|
||||||
|
accessible when new backup requests are paused. Pausing an application sign-in
|
||||||
|
also prevents redemption of pending tickets for that application.
|
||||||
|
|
||||||
|
Configure service packages, linked receiver identities, bridge keys and
|
||||||
|
backup credentials on the host using their deployment procedures. Enabling
|
||||||
|
a paused feature checks its available service socket and, for linked mail or
|
||||||
|
DNS, the receiver's readiness and version. A failed prerequisite check leaves
|
||||||
|
the saved choices intact. Changes are recorded in the administrator audit log.
|
||||||
|
|
||||||
## Monitor local and remote services
|
## Monitor local and remote services
|
||||||
|
|
||||||
The panel's **Service health** page shows the latest observation and timestamp
|
The panel's **Service health** page shows the latest observation and timestamp
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# Security
|
||||||
|
|
||||||
|
## Report vulnerabilities privately
|
||||||
|
|
||||||
|
Contact a project maintainer privately with the affected release, the
|
||||||
|
deployment layout, the affected roles, and a description of the impact.
|
||||||
|
Share minimal evidence using test data. Remove credentials, tokens,
|
||||||
|
customer data, private keys, and identifiable account information. If you
|
||||||
|
cannot find a private channel, open a Gitea issue requesting private
|
||||||
|
contact and leave the technical details out of the issue.
|
||||||
|
|
||||||
|
Maintainers confirm scope, coordinate remediation with the reporter, and
|
||||||
|
publish an advisory with the fixed releases and any operational mitigations
|
||||||
|
after users have a way to update.
|
||||||
|
|
||||||
|
## Panel and account access
|
||||||
|
|
||||||
|
- Serve the panel over HTTPS. If you use a reverse proxy, restrict the
|
||||||
|
private origin to that proxy and let the managed Apache configuration set
|
||||||
|
the forwarding headers. Keep debug mode off on shared or public hosts.
|
||||||
|
- Require two-factor authentication for staff and customer managers. Use an
|
||||||
|
authenticator app for administrative accounts and keep recovery codes in a
|
||||||
|
protected location. The **My account** page lets users verify a new email
|
||||||
|
address, replace their authenticator, renew recovery codes, and revoke
|
||||||
|
other panel sessions. Revoking panel sessions also clears unused service
|
||||||
|
login tickets. Webmail, database, and SSH sessions established separately
|
||||||
|
have their own lifetimes.
|
||||||
|
- During customer impersonation, use only the approved support
|
||||||
|
actions. Review impersonation and credential access events. Account
|
||||||
|
security actions are recorded separately and visible to the account owner.
|
||||||
|
- Verify that the panel can deliver account messages and email factors.
|
||||||
|
Treat an address used for password recovery or an email factor as a
|
||||||
|
credential and check it after changing it.
|
||||||
|
|
||||||
|
## Service boundaries and recovery
|
||||||
|
|
||||||
|
- Restrict the panel database and RabbitMQ to local access. Expose only
|
||||||
|
the client-facing ports for the functions you run. Keep Unix sockets and
|
||||||
|
environment files restricted to the identities listed in the deployment
|
||||||
|
guide. Keep each site's PHP-FPM pool and SFTP keys scoped to that site.
|
||||||
|
- Pin SSH host keys for linked nodes and off-site backups. Use separate
|
||||||
|
domain-scoped keys for independent panels that share a receiver. Keep
|
||||||
|
unrestricted keys within one trusted operator group. The linked-node
|
||||||
|
upgrade runbook accounts for every authorized panel key.
|
||||||
|
- Review DNS delegation, mail routing permissions, and allowed forwarding.
|
||||||
|
Keep private DKIM material on the mail receiver and publish the matching
|
||||||
|
public records. Verify the mail configuration after changing packages.
|
||||||
|
- Store backup destinations and their keys separately from hosted content.
|
||||||
|
Protect recovery copies of the virtual environment and database. Test
|
||||||
|
website, database, and mailbox restores with isolated accounts and check
|
||||||
|
ownership and access afterwards.
|
||||||
|
- Keep Ubuntu or Debian packages and the panel's Python environment on
|
||||||
|
security-supported versions. Check installed dependencies against a
|
||||||
|
vulnerability advisory source such as OSV before a release. Verify both
|
||||||
|
distribution files against the reviewed Git revision and check the
|
||||||
|
wheel digest before enabling a web update.
|
||||||
|
|
||||||
|
Use the [deployment guide](deployment.md) for operating-system support,
|
||||||
|
configuration and recovery steps.
|
||||||
+6
-5
@@ -4,18 +4,19 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "coulobre-panel"
|
name = "coulobre-panel"
|
||||||
version = "0.10.2rc1"
|
version = "0.11.1rc1"
|
||||||
description = "A web hosting control panel for hosting providers and resellers."
|
description = "A web hosting control panel for hosting providers and resellers."
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"Django>=5.2.8,<5.3",
|
"Django>=5.2.17,<5.3",
|
||||||
"django-otp>=1.7.5,<2",
|
"django-otp>=1.7.5,<2",
|
||||||
"celery>=5.6,<6",
|
"celery>=5.6,<6",
|
||||||
"cryptography>=45",
|
"cryptography>=50",
|
||||||
"dnspython>=2.7,<3",
|
"dnspython>=2.9.2,<3",
|
||||||
"idna>=3,<4",
|
"idna>=3.15,<4",
|
||||||
|
"markdown-it-py>=4.3,<5",
|
||||||
"qrcode>=8.2,<9",
|
"qrcode>=8.2,<9",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
from contextlib import closing, contextmanager, suppress
|
from contextlib import closing, contextmanager, suppress
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -8,6 +9,7 @@ from pathlib import Path
|
|||||||
from .credential_rotation import (
|
from .credential_rotation import (
|
||||||
ROTATION_IN_PROGRESS,
|
ROTATION_IN_PROGRESS,
|
||||||
rotation_path,
|
rotation_path,
|
||||||
|
save_credential_record,
|
||||||
valid_generation,
|
valid_generation,
|
||||||
)
|
)
|
||||||
from .node_files import read_root_file, require_root_directory, write_new_file
|
from .node_files import read_root_file, require_root_directory, write_new_file
|
||||||
@@ -15,6 +17,10 @@ from .node_retirement import RetirementRecord
|
|||||||
|
|
||||||
STATE_DIRECTORY = Path("/var/lib/coulobre/database-node")
|
STATE_DIRECTORY = Path("/var/lib/coulobre/database-node")
|
||||||
MANAGED_COMMENT_PREFIX = "Coulobre managed database "
|
MANAGED_COMMENT_PREFIX = "Coulobre managed database "
|
||||||
|
AUTHENTICATION_POLICY = Path("/etc/coulobre/database-authentication")
|
||||||
|
NATIVE_PASSWORD = "mysql_native_password"
|
||||||
|
SHA2_PASSWORD = "caching_sha2_password"
|
||||||
|
SHA2_VERIFIER = re.compile(r"[0-9A-F]+")
|
||||||
|
|
||||||
|
|
||||||
def apply_database(database, socket):
|
def apply_database(database, socket):
|
||||||
@@ -25,8 +31,8 @@ def apply_database(database, socket):
|
|||||||
require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750)
|
require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750)
|
||||||
require_root_directory(STATE_DIRECTORY, create_mode=0o700)
|
require_root_directory(STATE_DIRECTORY, create_mode=0o700)
|
||||||
record_path = STATE_DIRECTORY / f"{database.name}.json"
|
record_path = STATE_DIRECTORY / f"{database.name}.json"
|
||||||
with locked_cursor(database, socket) as (_, cursor):
|
with locked_cursor(database, socket) as (driver, cursor):
|
||||||
install_database(cursor, database, socket, record_path)
|
install_database(cursor, database, socket, record_path, driver=driver)
|
||||||
return record_path
|
return record_path
|
||||||
|
|
||||||
|
|
||||||
@@ -71,18 +77,25 @@ def locked_cursor(database, socket):
|
|||||||
) from None
|
) from None
|
||||||
|
|
||||||
|
|
||||||
def read_resources(cursor, name):
|
def read_resources(cursor, name, *, sha2=False):
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA "
|
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA "
|
||||||
"WHERE SCHEMA_NAME = %s",
|
"WHERE SCHEMA_NAME = %s",
|
||||||
(name,),
|
(name,),
|
||||||
)
|
)
|
||||||
schema = cursor.fetchone()
|
schema = cursor.fetchone()
|
||||||
cursor.execute(
|
if sha2:
|
||||||
"SELECT Host, plugin, authentication_string FROM mysql.user "
|
cursor.execute(
|
||||||
"WHERE User = %s",
|
"SELECT Host, plugin, HEX(authentication_string), "
|
||||||
(name,),
|
"authentication_string FROM mysql.user WHERE User = %s",
|
||||||
)
|
(name,),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT Host, plugin, authentication_string FROM mysql.user "
|
||||||
|
"WHERE User = %s",
|
||||||
|
(name,),
|
||||||
|
)
|
||||||
return schema, cursor.fetchall()
|
return schema, cursor.fetchall()
|
||||||
|
|
||||||
|
|
||||||
@@ -126,11 +139,11 @@ def checked_credentials(
|
|||||||
pending_password=None,
|
pending_password=None,
|
||||||
):
|
):
|
||||||
name = database.name
|
name = database.name
|
||||||
schema, users = read_resources(cursor, name)
|
|
||||||
ready_path = record_path.with_suffix(".ready")
|
ready_path = record_path.with_suffix(".ready")
|
||||||
with suppress(FileNotFoundError):
|
with suppress(FileNotFoundError):
|
||||||
require_root_directory(record_path.parent)
|
require_root_directory(record_path.parent)
|
||||||
if not os.path.lexists(record_path):
|
if not os.path.lexists(record_path):
|
||||||
|
schema, users = read_resources(cursor, name)
|
||||||
if os.path.lexists(ready_path) or schema is not None or users:
|
if os.path.lexists(ready_path) or schema is not None or users:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The database, login, or completion marker has no local "
|
"The database, login, or completion marker has no local "
|
||||||
@@ -147,30 +160,46 @@ def checked_credentials(
|
|||||||
rotation_path(record_path)
|
rotation_path(record_path)
|
||||||
):
|
):
|
||||||
raise ValueError(ROTATION_IN_PROGRESS)
|
raise ValueError(ROTATION_IN_PROGRESS)
|
||||||
|
sha2 = uses_sha2(record)
|
||||||
|
schema, users = read_resources(cursor, name, sha2=sha2)
|
||||||
password = record["password"]
|
password = record["password"]
|
||||||
if pending_password is not None and users == (
|
if sha2:
|
||||||
(
|
verifier, server_value = sha2_login(users)
|
||||||
"localhost",
|
if verifier != record.get("authentication_verifier"):
|
||||||
"mysql_native_password",
|
if not pending_password or not can_sign_in(
|
||||||
native_password_hash(pending_password),
|
driver, record, pending_password
|
||||||
),
|
):
|
||||||
):
|
raise ValueError(
|
||||||
password = pending_password
|
"The MariaDB verifier differs from the registry."
|
||||||
password_hash = native_password_hash(password)
|
)
|
||||||
|
password = pending_password
|
||||||
|
user_details = ("localhost", SHA2_PASSWORD, verifier, server_value)
|
||||||
|
authentication = (
|
||||||
|
f"IDENTIFIED VIA {SHA2_PASSWORD} USING '{server_value}'"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
if pending_password is not None and users == (
|
||||||
|
(
|
||||||
|
"localhost",
|
||||||
|
NATIVE_PASSWORD,
|
||||||
|
native_password_hash(pending_password),
|
||||||
|
),
|
||||||
|
):
|
||||||
|
password = pending_password
|
||||||
|
password_hash = native_password_hash(password)
|
||||||
|
user_details = ("localhost", NATIVE_PASSWORD, password_hash)
|
||||||
|
authentication = f"IDENTIFIED BY PASSWORD '{password_hash}'"
|
||||||
check_resources(
|
check_resources(
|
||||||
schema,
|
schema,
|
||||||
users,
|
users,
|
||||||
MANAGED_COMMENT_PREFIX + record["ownership"],
|
MANAGED_COMMENT_PREFIX + record["ownership"],
|
||||||
password_hash,
|
user_details,
|
||||||
require_complete=True,
|
require_complete=True,
|
||||||
)
|
)
|
||||||
cursor.execute("SHOW GRANTS FOR %s@'localhost'", (name,))
|
cursor.execute("SHOW GRANTS FOR %s@'localhost'", (name,))
|
||||||
grantee = f"`{name}`@`localhost`"
|
grantee = f"`{name}`@`localhost`"
|
||||||
expected_grants = {
|
expected_grants = {
|
||||||
(
|
(f"GRANT USAGE ON *.* TO {grantee} {authentication}",),
|
||||||
f"GRANT USAGE ON *.* TO {grantee} "
|
|
||||||
f"IDENTIFIED BY PASSWORD '{password_hash}'",
|
|
||||||
),
|
|
||||||
(f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",),
|
(f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",),
|
||||||
}
|
}
|
||||||
grants = {
|
grants = {
|
||||||
@@ -184,25 +213,71 @@ def checked_credentials(
|
|||||||
and login_is_locked(cursor, name)
|
and login_is_locked(cursor, name)
|
||||||
):
|
):
|
||||||
return record
|
return record
|
||||||
|
if not can_sign_in(driver, record, password):
|
||||||
|
raise ValueError(
|
||||||
|
"The stored application credentials cannot open the managed "
|
||||||
|
"database."
|
||||||
|
)
|
||||||
|
return record
|
||||||
|
|
||||||
|
|
||||||
|
def can_sign_in(driver, record, password):
|
||||||
try:
|
try:
|
||||||
with closing(
|
with closing(
|
||||||
driver.connect(
|
driver.connect(
|
||||||
host="localhost",
|
host="localhost",
|
||||||
user=name,
|
user=record["user"],
|
||||||
passwd=password,
|
passwd=password,
|
||||||
db=name,
|
db=record["database"],
|
||||||
unix_socket=str(socket),
|
unix_socket=record["socket"],
|
||||||
connect_timeout=5,
|
connect_timeout=5,
|
||||||
charset="utf8mb4",
|
charset="utf8mb4",
|
||||||
)
|
)
|
||||||
):
|
):
|
||||||
pass
|
return True
|
||||||
except driver.Error:
|
except driver.Error:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def uses_sha2(record):
|
||||||
|
return record.get("authentication_plugin") == SHA2_PASSWORD
|
||||||
|
|
||||||
|
|
||||||
|
def sha2_login(users):
|
||||||
|
if len(users) != 1 or len(users[0]) != 4:
|
||||||
|
raise ValueError("Expected one managed MariaDB SHA-2 login.")
|
||||||
|
host, plugin, verifier, server_value = users[0]
|
||||||
|
if (
|
||||||
|
host != "localhost"
|
||||||
|
or plugin != SHA2_PASSWORD
|
||||||
|
or not isinstance(verifier, str)
|
||||||
|
or not SHA2_VERIFIER.fullmatch(verifier)
|
||||||
|
or not isinstance(server_value, str)
|
||||||
|
or not server_value
|
||||||
|
):
|
||||||
|
raise ValueError("The existing MariaDB SHA-2 login is invalid.")
|
||||||
|
return verifier, server_value
|
||||||
|
|
||||||
|
|
||||||
|
def configured_authentication(cursor):
|
||||||
|
try:
|
||||||
|
policy = read_root_file(AUTHENTICATION_POLICY, mode=0o644).strip()
|
||||||
|
except FileNotFoundError:
|
||||||
|
return NATIVE_PASSWORD
|
||||||
|
if policy == NATIVE_PASSWORD:
|
||||||
|
return policy
|
||||||
|
if policy != SHA2_PASSWORD:
|
||||||
|
raise ValueError("Choose a supported MariaDB authentication plugin.")
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT PLUGIN_STATUS FROM information_schema.PLUGINS "
|
||||||
|
"WHERE PLUGIN_NAME = %s",
|
||||||
|
(policy,),
|
||||||
|
)
|
||||||
|
if cursor.fetchone() != ("ACTIVE",):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The stored application credentials cannot open the managed "
|
"Enable the MariaDB caching_sha2_password plugin first."
|
||||||
"database."
|
)
|
||||||
) from None
|
return policy
|
||||||
return record
|
|
||||||
|
|
||||||
|
|
||||||
def check_restore_complete(record_path):
|
def check_restore_complete(record_path):
|
||||||
@@ -212,7 +287,7 @@ def check_restore_complete(record_path):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def install_database(cursor, database, socket, record_path):
|
def install_database(cursor, database, socket, record_path, *, driver=None):
|
||||||
if os.path.lexists(record_path.with_suffix(".retired")):
|
if os.path.lexists(record_path.with_suffix(".retired")):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"This database is retained for a retired hosting account."
|
"This database is retained for a retired hosting account."
|
||||||
@@ -221,17 +296,44 @@ def install_database(cursor, database, socket, record_path):
|
|||||||
raise ValueError(ROTATION_IN_PROGRESS)
|
raise ValueError(ROTATION_IN_PROGRESS)
|
||||||
check_restore_complete(record_path)
|
check_restore_complete(record_path)
|
||||||
name = database.name
|
name = database.name
|
||||||
schema, users = read_resources(cursor, name)
|
existing = os.path.lexists(record_path)
|
||||||
ready_path = record_path.with_suffix(".ready")
|
record = (
|
||||||
record = reserve_credentials(
|
load_credentials(database, socket, record_path) if existing else {}
|
||||||
database, socket, record_path, ready_path, schema, users
|
|
||||||
)
|
)
|
||||||
comment = MANAGED_COMMENT_PREFIX + record["ownership"]
|
plugin = (
|
||||||
password_hash = native_password_hash(record["password"])
|
record.get("authentication_plugin", NATIVE_PASSWORD)
|
||||||
|
if existing
|
||||||
|
else configured_authentication(cursor)
|
||||||
|
)
|
||||||
|
sha2 = plugin == SHA2_PASSWORD
|
||||||
|
schema, users = read_resources(cursor, name, sha2=sha2)
|
||||||
|
ready_path = record_path.with_suffix(".ready")
|
||||||
|
if not existing:
|
||||||
|
record = reserve_credentials(
|
||||||
|
database, socket, record_path, ready_path, schema, users, plugin
|
||||||
|
)
|
||||||
ready = check_completion_marker(ready_path, record)
|
ready = check_completion_marker(ready_path, record)
|
||||||
|
if ready and sha2:
|
||||||
|
checked_credentials(driver, cursor, database, socket, record_path)
|
||||||
|
return
|
||||||
|
comment = MANAGED_COMMENT_PREFIX + record["ownership"]
|
||||||
|
password = record["password"]
|
||||||
|
if sha2:
|
||||||
|
if users:
|
||||||
|
verifier, server_value = sha2_login(users)
|
||||||
|
expected_user = (
|
||||||
|
"localhost",
|
||||||
|
SHA2_PASSWORD,
|
||||||
|
verifier,
|
||||||
|
server_value,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
expected_user = None
|
||||||
|
else:
|
||||||
|
password_hash = native_password_hash(password)
|
||||||
|
expected_user = ("localhost", NATIVE_PASSWORD, password_hash)
|
||||||
check_resources(
|
check_resources(
|
||||||
schema, users, comment, password_hash, require_complete=ready
|
schema, users, comment, expected_user, require_complete=ready
|
||||||
)
|
)
|
||||||
|
|
||||||
if schema is None:
|
if schema is None:
|
||||||
@@ -241,24 +343,40 @@ def install_database(cursor, database, socket, record_path):
|
|||||||
(comment,),
|
(comment,),
|
||||||
)
|
)
|
||||||
if not users:
|
if not users:
|
||||||
cursor.execute(
|
if sha2:
|
||||||
"CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password "
|
cursor.execute(
|
||||||
"USING %s",
|
"CREATE USER %s@'localhost' IDENTIFIED VIA "
|
||||||
(name, password_hash),
|
"caching_sha2_password USING PASSWORD(%s)",
|
||||||
)
|
(name, password),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cursor.execute(
|
||||||
|
"CREATE USER %s@'localhost' IDENTIFIED VIA "
|
||||||
|
"mysql_native_password USING %s",
|
||||||
|
(name, password_hash),
|
||||||
|
)
|
||||||
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO %s@'localhost'",
|
f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO %s@'localhost'",
|
||||||
(name,),
|
(name,),
|
||||||
)
|
)
|
||||||
|
if sha2:
|
||||||
|
_, users = read_resources(cursor, name, sha2=True)
|
||||||
|
verifier, _ = sha2_login(users)
|
||||||
|
if not can_sign_in(driver, record, password):
|
||||||
|
raise ValueError(
|
||||||
|
"The managed MariaDB SHA-2 login could not sign in."
|
||||||
|
)
|
||||||
|
save_credential_record(
|
||||||
|
record_path, record | {"authentication_verifier": verifier}
|
||||||
|
)
|
||||||
if not ready:
|
if not ready:
|
||||||
write_new_file(ready_path, record["ownership"] + "\n", mode=0o600)
|
write_new_file(ready_path, record["ownership"] + "\n", mode=0o600)
|
||||||
|
|
||||||
|
|
||||||
def reserve_credentials(database, socket, path, ready_path, schema, users):
|
def reserve_credentials(
|
||||||
if os.path.lexists(path):
|
database, socket, path, ready_path, schema, users, plugin
|
||||||
return load_credentials(database, socket, path)
|
):
|
||||||
|
|
||||||
if os.path.lexists(ready_path) or schema is not None or users:
|
if os.path.lexists(ready_path) or schema is not None or users:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The database name or login already exists outside Coulobre's "
|
"The database name or login already exists outside Coulobre's "
|
||||||
@@ -269,6 +387,8 @@ def reserve_credentials(database, socket, path, ready_path, schema, users):
|
|||||||
"password": secrets.token_urlsafe(32),
|
"password": secrets.token_urlsafe(32),
|
||||||
"ownership": secrets.token_hex(16),
|
"ownership": secrets.token_hex(16),
|
||||||
}
|
}
|
||||||
|
if plugin == SHA2_PASSWORD:
|
||||||
|
record["authentication_plugin"] = plugin
|
||||||
write_new_file(path, json.dumps(record, indent=2) + "\n", mode=0o600)
|
write_new_file(path, json.dumps(record, indent=2) + "\n", mode=0o600)
|
||||||
return record
|
return record
|
||||||
|
|
||||||
@@ -296,6 +416,8 @@ def load_credentials(database, socket, path):
|
|||||||
or not isinstance(record.get("password"), str)
|
or not isinstance(record.get("password"), str)
|
||||||
or not record["password"]
|
or not record["password"]
|
||||||
or not record["password"].isascii()
|
or not record["password"].isascii()
|
||||||
|
or record.get("authentication_plugin", NATIVE_PASSWORD)
|
||||||
|
not in (NATIVE_PASSWORD, SHA2_PASSWORD)
|
||||||
or not valid_generation(record.get("rotation_id"))
|
or not valid_generation(record.get("rotation_id"))
|
||||||
or not isinstance(record.get("ownership"), str)
|
or not isinstance(record.get("ownership"), str)
|
||||||
or not record["ownership"]
|
or not record["ownership"]
|
||||||
@@ -325,7 +447,7 @@ def check_completion_marker(path, record):
|
|||||||
|
|
||||||
|
|
||||||
def check_resources(
|
def check_resources(
|
||||||
schema, users, comment, password_hash, *, require_complete
|
schema, users, comment, expected_user, *, require_complete
|
||||||
):
|
):
|
||||||
if require_complete and (schema is None or not users):
|
if require_complete and (schema is None or not users):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
@@ -336,9 +458,7 @@ def check_resources(
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The existing database has a different ownership marker."
|
"The existing database has a different ownership marker."
|
||||||
)
|
)
|
||||||
if users and users != (
|
if users and users != (expected_user,):
|
||||||
("localhost", "mysql_native_password", password_hash),
|
|
||||||
):
|
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"The existing MariaDB login differs from its managed credentials."
|
"The existing MariaDB login differs from its managed credentials."
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -37,11 +37,18 @@ def rotate_database_credentials(request, socket):
|
|||||||
pending = stage_rotation(path, request, generation)
|
pending = stage_rotation(path, request, generation)
|
||||||
if generation != request.rotation_id:
|
if generation != request.rotation_id:
|
||||||
password = pending["password"]
|
password = pending["password"]
|
||||||
cursor.execute(
|
if db.uses_sha2(record):
|
||||||
"ALTER USER %s@'localhost' "
|
cursor.execute(
|
||||||
"IDENTIFIED VIA mysql_native_password USING %s",
|
"ALTER USER %s@'localhost' IDENTIFIED VIA "
|
||||||
(database.name, db.native_password_hash(password)),
|
"caching_sha2_password USING PASSWORD(%s)",
|
||||||
)
|
(database.name, password),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cursor.execute(
|
||||||
|
"ALTER USER %s@'localhost' "
|
||||||
|
"IDENTIFIED VIA mysql_native_password USING %s",
|
||||||
|
(database.name, db.native_password_hash(password)),
|
||||||
|
)
|
||||||
db.checked_credentials(
|
db.checked_credentials(
|
||||||
driver,
|
driver,
|
||||||
cursor,
|
cursor,
|
||||||
@@ -55,6 +62,10 @@ def rotate_database_credentials(request, socket):
|
|||||||
"password": password,
|
"password": password,
|
||||||
"rotation_id": request.rotation_id,
|
"rotation_id": request.rotation_id,
|
||||||
}
|
}
|
||||||
|
if db.uses_sha2(record):
|
||||||
|
_, users = db.read_resources(cursor, database.name, sha2=True)
|
||||||
|
verifier, _ = db.sha2_login(users)
|
||||||
|
record["authentication_verifier"] = verifier
|
||||||
save_credential_record(path, record)
|
save_credential_record(path, record)
|
||||||
finish_rotation(path)
|
finish_rotation(path)
|
||||||
return record
|
return record
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
|
||||||
|
class PanelRole(StrEnum):
|
||||||
|
ADMIN = "administrator"
|
||||||
|
MANAGER = "manager"
|
||||||
|
CUSTOMER = "customer"
|
||||||
|
|
||||||
|
|
||||||
NAVIGATION_SECTIONS = {
|
NAVIGATION_SECTIONS = {
|
||||||
"accounts": "accounts",
|
"accounts": "accounts",
|
||||||
"retired-accounts": "accounts",
|
"retired-accounts": "accounts",
|
||||||
@@ -14,12 +23,18 @@ NAVIGATION_SECTIONS = {
|
|||||||
|
|
||||||
|
|
||||||
def customer_for_user(user):
|
def customer_for_user(user):
|
||||||
|
role = getattr(user, "panel_role", None)
|
||||||
|
if role is not None and role != PanelRole.CUSTOMER:
|
||||||
|
return None
|
||||||
if not user.is_authenticated or user.is_superuser:
|
if not user.is_authenticated or user.is_superuser:
|
||||||
return None
|
return None
|
||||||
return getattr(user, "hosting_customer", None)
|
return getattr(user, "hosting_customer", None)
|
||||||
|
|
||||||
|
|
||||||
def reseller_for_user(user):
|
def reseller_for_user(user):
|
||||||
|
role = getattr(user, "panel_role", None)
|
||||||
|
if role is not None and role != PanelRole.MANAGER:
|
||||||
|
return None
|
||||||
if (
|
if (
|
||||||
not user.is_authenticated
|
not user.is_authenticated
|
||||||
or user.is_superuser
|
or user.is_superuser
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from coulobre.account_restore_request import (
|
|||||||
)
|
)
|
||||||
from coulobre.database_node import DatabaseSpec
|
from coulobre.database_node import DatabaseSpec
|
||||||
|
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import AccountBackupSchedule
|
from .models import AccountBackupSchedule
|
||||||
|
|
||||||
SCHEDULE_FIELDS = (
|
SCHEDULE_FIELDS = (
|
||||||
@@ -49,7 +50,11 @@ class AccountBackupScheduleForm(forms.Form):
|
|||||||
self.allow_mail = allow_mail
|
self.allow_mail = allow_mail
|
||||||
if not allow_mail and not self.initial.get("include_mailboxes"):
|
if not allow_mail and not self.initial.get("include_mailboxes"):
|
||||||
del self.fields["include_mailboxes"]
|
del self.fields["include_mailboxes"]
|
||||||
destinations = settings.OFFSITE_BACKUP_DESTINATIONS
|
destinations = (
|
||||||
|
settings.OFFSITE_BACKUP_DESTINATIONS
|
||||||
|
if panel_feature_allowed("OFFSITE_BACKUP_DESTINATIONS")
|
||||||
|
else {}
|
||||||
|
)
|
||||||
current = self.initial.get("offsite_destination")
|
current = self.initial.get("offsite_destination")
|
||||||
if destinations or current:
|
if destinations or current:
|
||||||
choices = [("", "Local archive only"), *destinations.items()]
|
choices = [("", "Local archive only"), *destinations.items()]
|
||||||
|
|||||||
@@ -0,0 +1,463 @@
|
|||||||
|
import secrets
|
||||||
|
from datetime import timedelta
|
||||||
|
from smtplib import SMTPException
|
||||||
|
|
||||||
|
import django_otp
|
||||||
|
from django import forms
|
||||||
|
from django.conf import settings
|
||||||
|
from django.contrib import messages
|
||||||
|
from django.contrib.auth import update_session_auth_hash
|
||||||
|
from django.contrib.auth.hashers import check_password
|
||||||
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||||
|
from django.contrib.auth.password_validation import validate_password
|
||||||
|
from django.core.exceptions import PermissionDenied
|
||||||
|
from django.core.mail import send_mail
|
||||||
|
from django.db import transaction
|
||||||
|
from django.shortcuts import redirect, render
|
||||||
|
from django.urls import reverse_lazy
|
||||||
|
from django.utils import timezone
|
||||||
|
from django.utils.crypto import constant_time_compare
|
||||||
|
from django.utils.decorators import method_decorator
|
||||||
|
from django.views.decorators.cache import never_cache
|
||||||
|
from django.views.decorators.debug import (
|
||||||
|
sensitive_post_parameters,
|
||||||
|
sensitive_variables,
|
||||||
|
)
|
||||||
|
from django.views.generic import FormView, TemplateView
|
||||||
|
from django_otp.plugins.otp_email.models import EmailDevice
|
||||||
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
|
||||||
|
from .models import PanelEmailChange, PanelSecurityEvent
|
||||||
|
from .panel_factors import (
|
||||||
|
DEVICE_NAME,
|
||||||
|
DEVICE_TYPES,
|
||||||
|
RECOVERY_SIGN_IN,
|
||||||
|
confirmed_device,
|
||||||
|
device_for_user,
|
||||||
|
lock_user,
|
||||||
|
replace_recovery_codes,
|
||||||
|
secret_digest,
|
||||||
|
send_factor_code,
|
||||||
|
user_devices,
|
||||||
|
)
|
||||||
|
from .panel_sessions import (
|
||||||
|
preserve_session,
|
||||||
|
record_security_event,
|
||||||
|
revoke_other_sessions,
|
||||||
|
session_is_current,
|
||||||
|
)
|
||||||
|
from .sign_in import ConfirmFactorForm, authenticator_setup
|
||||||
|
from .sign_in_limits import limit_attempt
|
||||||
|
|
||||||
|
Action = PanelSecurityEvent.Action
|
||||||
|
ACCOUNT_URL = reverse_lazy("panel:account_security")
|
||||||
|
FACTOR_SETUP = "coulobre_account_factor_setup"
|
||||||
|
|
||||||
|
|
||||||
|
class AccountSecurityMixin(LoginRequiredMixin):
|
||||||
|
@method_decorator(never_cache)
|
||||||
|
def dispatch(self, request, *args, **kwargs):
|
||||||
|
if getattr(request, "impersonation", None):
|
||||||
|
raise PermissionDenied
|
||||||
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class AccountSecurityView(AccountSecurityMixin, TemplateView):
|
||||||
|
template_name = "hosting/account_security.html"
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
user = self.request.user
|
||||||
|
device = confirmed_device(user)
|
||||||
|
factor = "Authenticator app" if device else "Not set up"
|
||||||
|
if isinstance(device, EmailDevice):
|
||||||
|
factor = "Email code"
|
||||||
|
return super().get_context_data(
|
||||||
|
factor=factor,
|
||||||
|
factor_enabled=device is not None,
|
||||||
|
email_available=bool(settings.EMAIL_HOST),
|
||||||
|
events=PanelSecurityEvent.objects.filter(user=user).order_by(
|
||||||
|
"-id"
|
||||||
|
)[:10],
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorizeForm(forms.Form):
|
||||||
|
password = forms.CharField(
|
||||||
|
label="Current password",
|
||||||
|
strip=False,
|
||||||
|
max_length=4096,
|
||||||
|
widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
|
||||||
|
)
|
||||||
|
code = ConfirmFactorForm.base_fields["code"]
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordForm(AuthorizeForm):
|
||||||
|
new_password = forms.CharField(
|
||||||
|
max_length=4096,
|
||||||
|
strip=False,
|
||||||
|
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
|
||||||
|
)
|
||||||
|
confirm_password = forms.CharField(
|
||||||
|
max_length=4096,
|
||||||
|
strip=False,
|
||||||
|
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
|
||||||
|
)
|
||||||
|
|
||||||
|
def clean(self):
|
||||||
|
cleaned = super().clean()
|
||||||
|
if (
|
||||||
|
"new_password" in cleaned
|
||||||
|
and "confirm_password" in cleaned
|
||||||
|
and cleaned["new_password"] != cleaned["confirm_password"]
|
||||||
|
):
|
||||||
|
self.add_error("confirm_password", "The passwords differ.")
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
class EmailForm(AuthorizeForm):
|
||||||
|
email = forms.EmailField(label="New email address", max_length=254)
|
||||||
|
|
||||||
|
|
||||||
|
class VerifyEmailForm(forms.Form):
|
||||||
|
code = forms.RegexField(
|
||||||
|
r"\A[0-9a-fA-F]{12}\Z",
|
||||||
|
label="Email verification code",
|
||||||
|
widget=forms.TextInput(attrs={"autocomplete": "one-time-code"}),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@method_decorator(sensitive_post_parameters(), name="dispatch")
|
||||||
|
class SecurityFormView(AccountSecurityMixin, FormView):
|
||||||
|
template_name = "hosting/account_security_form.html"
|
||||||
|
success_url = ACCOUNT_URL
|
||||||
|
instructions = ""
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
return super().get_context_data(
|
||||||
|
heading=self.heading, instructions=self.instructions, **kwargs
|
||||||
|
)
|
||||||
|
|
||||||
|
def post(self, request, *args, **kwargs):
|
||||||
|
return limit_attempt(
|
||||||
|
request,
|
||||||
|
"account-security",
|
||||||
|
str(request.user.pk),
|
||||||
|
address_limit=30,
|
||||||
|
identity_limit=10,
|
||||||
|
) or super().post(request, *args, **kwargs)
|
||||||
|
|
||||||
|
def locked_user(self):
|
||||||
|
user = lock_user(self.request.user.pk)
|
||||||
|
if (
|
||||||
|
not user.is_active
|
||||||
|
or not session_is_current(self.request, user)
|
||||||
|
or not constant_time_compare(
|
||||||
|
user.get_session_auth_hash(),
|
||||||
|
self.request.user.get_session_auth_hash(),
|
||||||
|
)
|
||||||
|
):
|
||||||
|
raise PermissionDenied
|
||||||
|
return user
|
||||||
|
|
||||||
|
def changed_access(self, user, action):
|
||||||
|
version = revoke_other_sessions(user)
|
||||||
|
record_security_event(user, action)
|
||||||
|
self.request.session.pop(RECOVERY_SIGN_IN, None)
|
||||||
|
self.request.session.pop(FACTOR_SETUP, None)
|
||||||
|
preserve_session(self.request, version)
|
||||||
|
|
||||||
|
@sensitive_variables("codes")
|
||||||
|
def show_recovery_codes(self, codes):
|
||||||
|
return render(
|
||||||
|
self.request,
|
||||||
|
"hosting/factor_recovery_codes.html",
|
||||||
|
{
|
||||||
|
"recovery_codes": "\n".join(codes),
|
||||||
|
"destination": self.success_url,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorizedSecurityChange(SecurityFormView):
|
||||||
|
form_class = AuthorizeForm
|
||||||
|
|
||||||
|
def get_form(self, form_class=None):
|
||||||
|
form = super().get_form(form_class)
|
||||||
|
if confirmed_device(self.request.user) is None:
|
||||||
|
del form.fields["code"]
|
||||||
|
return form
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
return super().get_context_data(
|
||||||
|
can_send_code=isinstance(
|
||||||
|
confirmed_device(self.request.user), EmailDevice
|
||||||
|
),
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
def post(self, request, *args, **kwargs):
|
||||||
|
if "send_code" not in request.POST:
|
||||||
|
return super().post(request, *args, **kwargs)
|
||||||
|
device = confirmed_device(request.user)
|
||||||
|
if not isinstance(device, EmailDevice):
|
||||||
|
raise PermissionDenied
|
||||||
|
messages.info(
|
||||||
|
request,
|
||||||
|
send_factor_code(
|
||||||
|
request.user, device.persistent_id, confirmed=True
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return redirect(request.path)
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
@sensitive_variables("form")
|
||||||
|
def form_valid(self, form):
|
||||||
|
user = self.locked_user()
|
||||||
|
if not check_password(form.cleaned_data["password"], user.password):
|
||||||
|
form.add_error("password", "The current password is incorrect.")
|
||||||
|
return self.form_invalid(form)
|
||||||
|
|
||||||
|
self.validate_change(user, form)
|
||||||
|
if form.errors:
|
||||||
|
return self.form_invalid(form)
|
||||||
|
|
||||||
|
if not self.verify_current_factor(user, form):
|
||||||
|
form.add_error(
|
||||||
|
"code", "Enter a valid code from your current factor."
|
||||||
|
)
|
||||||
|
return self.form_invalid(form)
|
||||||
|
return self.apply_change(user, form)
|
||||||
|
|
||||||
|
def verify_current_factor(self, user, form):
|
||||||
|
device = confirmed_device(user)
|
||||||
|
return device is None or device.verify_token(
|
||||||
|
form.cleaned_data.get("code", "")
|
||||||
|
)
|
||||||
|
|
||||||
|
def validate_change(self, user, form):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ChangePasswordView(AuthorizedSecurityChange):
|
||||||
|
heading = "Change password"
|
||||||
|
instructions = "Changing your password signs out your other sessions."
|
||||||
|
form_class = PasswordForm
|
||||||
|
|
||||||
|
def validate_change(self, user, form):
|
||||||
|
try:
|
||||||
|
validate_password(form.cleaned_data["new_password"], user)
|
||||||
|
except forms.ValidationError as error:
|
||||||
|
form.add_error("new_password", error)
|
||||||
|
|
||||||
|
@sensitive_variables("form")
|
||||||
|
def apply_change(self, user, form):
|
||||||
|
user.set_password(form.cleaned_data["new_password"])
|
||||||
|
user.save(update_fields=["password"])
|
||||||
|
update_session_auth_hash(self.request, user)
|
||||||
|
self.changed_access(user, Action.PASSWORD)
|
||||||
|
messages.success(self.request, "Your password was changed.")
|
||||||
|
return redirect(self.success_url)
|
||||||
|
|
||||||
|
|
||||||
|
class ChangeEmailView(AuthorizedSecurityChange):
|
||||||
|
heading = "Change email address"
|
||||||
|
instructions = "We will send a verification code to your new address."
|
||||||
|
form_class = EmailForm
|
||||||
|
|
||||||
|
def dispatch(self, request, *args, **kwargs):
|
||||||
|
if not settings.EMAIL_HOST:
|
||||||
|
raise PermissionDenied
|
||||||
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
|
def validate_change(self, user, form):
|
||||||
|
if form.cleaned_data["email"].casefold() == user.email.casefold():
|
||||||
|
form.add_error("email", "Enter a different email address.")
|
||||||
|
|
||||||
|
@sensitive_variables("code")
|
||||||
|
def apply_change(self, user, form):
|
||||||
|
email = form.cleaned_data["email"]
|
||||||
|
code = secrets.token_hex(6)
|
||||||
|
try:
|
||||||
|
sent = send_mail(
|
||||||
|
"Verify your new Coulobre Panel email address",
|
||||||
|
f"Enter {code} on the page where you requested the change. "
|
||||||
|
"The code expires in 15 minutes.",
|
||||||
|
None,
|
||||||
|
[email],
|
||||||
|
)
|
||||||
|
except (OSError, SMTPException):
|
||||||
|
sent = 0
|
||||||
|
if sent != 1:
|
||||||
|
form.add_error(None, "The verification email could not be sent.")
|
||||||
|
return self.form_invalid(form)
|
||||||
|
|
||||||
|
PanelEmailChange.objects.update_or_create(
|
||||||
|
user=user,
|
||||||
|
defaults={
|
||||||
|
"email": email,
|
||||||
|
"digest": secret_digest("email-change", code),
|
||||||
|
"session_digest": self.session_digest(),
|
||||||
|
"expires_at": timezone.now() + timedelta(minutes=15),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return redirect("panel:account_email_verify")
|
||||||
|
|
||||||
|
def session_digest(self):
|
||||||
|
return secret_digest("email-session", self.request.session.session_key)
|
||||||
|
|
||||||
|
|
||||||
|
def notify_old_address(email):
|
||||||
|
send_mail(
|
||||||
|
"Your Coulobre Panel email address changed",
|
||||||
|
"The email address on your account was changed. Contact your hosting "
|
||||||
|
"provider if you did not request this change.",
|
||||||
|
None,
|
||||||
|
[email],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class VerifyEmailView(SecurityFormView):
|
||||||
|
heading = "Verify your new email address"
|
||||||
|
form_class = VerifyEmailForm
|
||||||
|
|
||||||
|
@sensitive_variables("form")
|
||||||
|
@transaction.atomic
|
||||||
|
def form_valid(self, form):
|
||||||
|
user = self.locked_user()
|
||||||
|
pending = PanelEmailChange.objects.filter(user=user).first()
|
||||||
|
session_digest = secret_digest(
|
||||||
|
"email-session", self.request.session.session_key
|
||||||
|
)
|
||||||
|
code_digest = secret_digest(
|
||||||
|
"email-change", form.cleaned_data["code"].lower()
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
pending is None
|
||||||
|
or pending.expires_at <= timezone.now()
|
||||||
|
or not constant_time_compare(
|
||||||
|
pending.session_digest, session_digest
|
||||||
|
)
|
||||||
|
or not constant_time_compare(pending.digest, code_digest)
|
||||||
|
):
|
||||||
|
form.add_error(
|
||||||
|
"code", "The verification code is invalid or expired."
|
||||||
|
)
|
||||||
|
return self.form_invalid(form)
|
||||||
|
|
||||||
|
previous_email = user.email
|
||||||
|
user.email = pending.email
|
||||||
|
user.save(update_fields=["email"])
|
||||||
|
user_devices(user, EmailDevice).update(
|
||||||
|
email=user.email, token=None, valid_until=timezone.now()
|
||||||
|
)
|
||||||
|
self.changed_access(user, Action.EMAIL)
|
||||||
|
if previous_email:
|
||||||
|
transaction.on_commit(
|
||||||
|
lambda: notify_old_address(previous_email), robust=True
|
||||||
|
)
|
||||||
|
messages.success(self.request, "Your email address was changed.")
|
||||||
|
return redirect(self.success_url)
|
||||||
|
|
||||||
|
|
||||||
|
class StartAuthenticatorView(AuthorizedSecurityChange):
|
||||||
|
heading = "Set up an authenticator app"
|
||||||
|
instructions = "Your current factor works until you verify the new app."
|
||||||
|
|
||||||
|
def recently_used_recovery_code(self, user):
|
||||||
|
recovery = self.request.session.get(RECOVERY_SIGN_IN, {})
|
||||||
|
if recovery.get("expires", 0) <= int(timezone.now().timestamp()):
|
||||||
|
return False
|
||||||
|
device = confirmed_device(user)
|
||||||
|
return device is not None and recovery.get("device") == (
|
||||||
|
device.persistent_id
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_form(self, form_class=None):
|
||||||
|
form = super().get_form(form_class)
|
||||||
|
if self.recently_used_recovery_code(self.request.user):
|
||||||
|
form.fields.pop("code", None)
|
||||||
|
return form
|
||||||
|
|
||||||
|
def verify_current_factor(self, user, form):
|
||||||
|
return self.recently_used_recovery_code(
|
||||||
|
user
|
||||||
|
) or super().verify_current_factor(user, form)
|
||||||
|
|
||||||
|
def apply_change(self, user, form):
|
||||||
|
self.request.session.pop(RECOVERY_SIGN_IN, None)
|
||||||
|
for device_type in DEVICE_TYPES.values():
|
||||||
|
user_devices(user, device_type).filter(confirmed=False).delete()
|
||||||
|
pending = TOTPDevice.objects.create(
|
||||||
|
user=user, name=DEVICE_NAME, confirmed=False
|
||||||
|
)
|
||||||
|
self.request.session[FACTOR_SETUP] = {
|
||||||
|
"device": pending.persistent_id,
|
||||||
|
"expires": int(timezone.now().timestamp()) + 600,
|
||||||
|
}
|
||||||
|
return redirect("panel:account_authenticator_confirm")
|
||||||
|
|
||||||
|
|
||||||
|
class ConfirmAuthenticatorView(SecurityFormView):
|
||||||
|
heading = "Verify your authenticator app"
|
||||||
|
form_class = ConfirmFactorForm
|
||||||
|
|
||||||
|
def pending_device(self, user):
|
||||||
|
setup = self.request.session.get(FACTOR_SETUP, {})
|
||||||
|
if setup.get("expires", 0) <= int(timezone.now().timestamp()):
|
||||||
|
return None
|
||||||
|
return device_for_user(user, setup.get("device"), confirmed=False)
|
||||||
|
|
||||||
|
def get(self, request, *args, **kwargs):
|
||||||
|
if self.pending_device(request.user) is None:
|
||||||
|
return redirect("panel:account_authenticator")
|
||||||
|
return super().get(request, *args, **kwargs)
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
pending = self.pending_device(self.request.user)
|
||||||
|
context = authenticator_setup(pending) if pending else {}
|
||||||
|
return super().get_context_data(**context, **kwargs)
|
||||||
|
|
||||||
|
@sensitive_variables("form")
|
||||||
|
@transaction.atomic
|
||||||
|
def form_valid(self, form):
|
||||||
|
user = self.locked_user()
|
||||||
|
pending = self.pending_device(user)
|
||||||
|
if pending is None or not pending.verify_token(
|
||||||
|
form.cleaned_data["code"]
|
||||||
|
):
|
||||||
|
form.add_error(
|
||||||
|
"code", "The verification code is invalid or expired."
|
||||||
|
)
|
||||||
|
return self.form_invalid(form)
|
||||||
|
for device_type in DEVICE_TYPES.values():
|
||||||
|
user_devices(user, device_type).filter(confirmed=True).delete()
|
||||||
|
pending.confirmed = True
|
||||||
|
pending.save(update_fields=["confirmed"])
|
||||||
|
django_otp.login(self.request, pending)
|
||||||
|
self.request.session.pop(FACTOR_SETUP, None)
|
||||||
|
self.changed_access(user, Action.FACTOR)
|
||||||
|
return self.show_recovery_codes(replace_recovery_codes(user))
|
||||||
|
|
||||||
|
|
||||||
|
class ReplaceRecoveryCodesView(AuthorizedSecurityChange):
|
||||||
|
heading = "Generate new recovery codes"
|
||||||
|
instructions = "Generating new codes invalidates all your existing codes."
|
||||||
|
|
||||||
|
def validate_change(self, user, form):
|
||||||
|
if confirmed_device(user) is None:
|
||||||
|
form.add_error(None, "Set up a second factor first.")
|
||||||
|
|
||||||
|
def apply_change(self, user, form):
|
||||||
|
self.changed_access(user, Action.RECOVERY)
|
||||||
|
return self.show_recovery_codes(replace_recovery_codes(user))
|
||||||
|
|
||||||
|
|
||||||
|
class SignOutOtherSessionsView(AuthorizedSecurityChange):
|
||||||
|
heading = "Sign out other sessions"
|
||||||
|
instructions = "This browser stays signed in."
|
||||||
|
|
||||||
|
def apply_change(self, user, form):
|
||||||
|
self.changed_access(user, Action.SESSIONS)
|
||||||
|
messages.success(self.request, "Your other sessions were signed out.")
|
||||||
|
return redirect(self.success_url)
|
||||||
@@ -11,6 +11,7 @@ from coulobre.web_node import WebSite
|
|||||||
from .dns_defaults import zone_defaults
|
from .dns_defaults import zone_defaults
|
||||||
from .dns_forms import normalize_record_rows
|
from .dns_forms import normalize_record_rows
|
||||||
from .dns_publication import queue_zone_snapshot
|
from .dns_publication import queue_zone_snapshot
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .mail_dns_setup import mail_dns_proposal
|
from .mail_dns_setup import mail_dns_proposal
|
||||||
from .models import (
|
from .models import (
|
||||||
HostingDnsZone,
|
HostingDnsZone,
|
||||||
@@ -70,8 +71,8 @@ def setup_new_account(account, options):
|
|||||||
)
|
)
|
||||||
if managed_dns:
|
if managed_dns:
|
||||||
existing_managed_mail = (
|
existing_managed_mail = (
|
||||||
settings.LOCAL_MAILBOX_PROVISIONING
|
panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
|
||||||
and settings.MANAGE_MAIL_DNS
|
and panel_feature_allowed("MANAGE_MAIL_DNS")
|
||||||
and account.mail_domains.filter(domain=domain).exists()
|
and account.mail_domains.filter(domain=domain).exists()
|
||||||
)
|
)
|
||||||
create_default_dns_zone(
|
create_default_dns_zone(
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
from django import forms
|
from django import forms
|
||||||
from django.conf import settings
|
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.db import IntegrityError
|
from django.db import IntegrityError
|
||||||
@@ -20,6 +19,7 @@ from .independent_websites import (
|
|||||||
create_website,
|
create_website,
|
||||||
queue_website_operation,
|
queue_website_operation,
|
||||||
)
|
)
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import HostingAccount, IndependentWebsite, WebsiteDomain
|
from .models import HostingAccount, IndependentWebsite, WebsiteDomain
|
||||||
|
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@ class IndependentWebsiteEditor(
|
|||||||
template_name = "hosting/independent_website_form.html"
|
template_name = "hosting/independent_website_form.html"
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
if not settings.LOCAL_WEB_ACTIVATION:
|
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
|
||||||
raise Http404
|
raise Http404
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
@@ -130,7 +130,9 @@ class IndependentWebsiteOperation(IndependentWebsiteEditor):
|
|||||||
operation = Operation(self.kwargs["operation"])
|
operation = Operation(self.kwargs["operation"])
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise Http404 from None
|
raise Http404 from None
|
||||||
if operation == Operation.HTTPS and not settings.LOCAL_WEB_HTTPS:
|
if operation == Operation.HTTPS and not panel_feature_allowed(
|
||||||
|
"LOCAL_WEB_HTTPS"
|
||||||
|
):
|
||||||
raise Http404
|
raise Http404
|
||||||
return operation
|
return operation
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from coulobre.php_runtime import validate_php_version
|
|||||||
from coulobre.service_access import ServiceAccessRequest
|
from coulobre.service_access import ServiceAccessRequest
|
||||||
|
|
||||||
from .access import is_tenant, manages_account
|
from .access import is_tenant, manages_account
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob
|
from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob
|
||||||
from .node_client import (
|
from .node_client import (
|
||||||
activate_local_site,
|
activate_local_site,
|
||||||
@@ -54,7 +55,7 @@ def website_actions(website):
|
|||||||
if website.suspended:
|
if website.suspended:
|
||||||
return (Operation.RESUME, Operation.RETIRE)
|
return (Operation.RESUME, Operation.RETIRE)
|
||||||
actions = (Operation.PHP, Operation.SUSPEND)
|
actions = (Operation.PHP, Operation.SUSPEND)
|
||||||
if settings.LOCAL_WEB_HTTPS and not website.https_enabled:
|
if panel_feature_allowed("LOCAL_WEB_HTTPS") and not website.https_enabled:
|
||||||
actions += (Operation.HTTPS,)
|
actions += (Operation.HTTPS,)
|
||||||
return actions
|
return actions
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
from contextvars import ContextVar
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.utils.functional import cached_property
|
||||||
|
|
||||||
|
from coulobre.linked_updates import UNIT_DIR
|
||||||
|
|
||||||
|
from .dns_defaults import zone_defaults
|
||||||
|
from .models import PanelFeaturePolicy
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Feature:
|
||||||
|
setting: str
|
||||||
|
label: str
|
||||||
|
prerequisite: str
|
||||||
|
socket: str = ""
|
||||||
|
role: str = ""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def configured(self):
|
||||||
|
if self.setting == "DEFAULT_DNS_ZONES":
|
||||||
|
defaults = zone_defaults()
|
||||||
|
return bool(
|
||||||
|
settings.LOCAL_DNS_PUBLISHING
|
||||||
|
and defaults.nameservers
|
||||||
|
and defaults.addresses
|
||||||
|
)
|
||||||
|
if self.setting == "PHPMYADMIN_URL":
|
||||||
|
return bool(
|
||||||
|
settings.PHPMYADMIN_URL and settings.LOCAL_DATABASE_CREDENTIALS
|
||||||
|
)
|
||||||
|
if self.setting == "ROUNDCUBE_URL":
|
||||||
|
return bool(
|
||||||
|
settings.ROUNDCUBE_URL
|
||||||
|
and (
|
||||||
|
settings.LOCAL_MAILBOX_CREDENTIALS
|
||||||
|
or settings.REMOTE_MAILBOX_CREDENTIALS
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return bool(getattr(settings, self.setting))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def linked(self):
|
||||||
|
return (
|
||||||
|
bool(self.role)
|
||||||
|
and (
|
||||||
|
UNIT_DIR / f"coulobre-{self.role}-apply@.service.d/remote.conf"
|
||||||
|
).is_file()
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def socket_ready(self):
|
||||||
|
if self.setting == "ROUNDCUBE_URL":
|
||||||
|
socket = (
|
||||||
|
"coulobre-mail-credentials"
|
||||||
|
if settings.REMOTE_MAILBOX_CREDENTIALS
|
||||||
|
else "coulobre-service-credentials"
|
||||||
|
)
|
||||||
|
return Path(f"/run/{socket}.sock").is_socket()
|
||||||
|
return not self.socket or Path(f"/run/{self.socket}.sock").is_socket()
|
||||||
|
|
||||||
|
|
||||||
|
FEATURES = (
|
||||||
|
Feature(
|
||||||
|
"LOCAL_WEB_ACTIVATION",
|
||||||
|
"Website provisioning",
|
||||||
|
"Apache and PHP provisioning",
|
||||||
|
"coulobre-web-apply",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"LOCAL_WEB_HTTPS",
|
||||||
|
"Managed website certificates",
|
||||||
|
"Website certificate provisioning",
|
||||||
|
"coulobre-https-apply",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"WEB_FILE_MANAGER",
|
||||||
|
"Website file manager",
|
||||||
|
"Website file service",
|
||||||
|
"coulobre-website-files",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"WEBSITE_JOBS",
|
||||||
|
"Website scheduled tasks",
|
||||||
|
"Website task service",
|
||||||
|
"coulobre-website-jobs",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"LOCAL_DNS_PUBLISHING",
|
||||||
|
"DNS publishing",
|
||||||
|
"Local BIND9 or a linked DNS receiver",
|
||||||
|
"coulobre-dns-apply",
|
||||||
|
"dns",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"DEFAULT_DNS_ZONES",
|
||||||
|
"Default managed DNS zones for new accounts",
|
||||||
|
"DNS publishing, nameservers and hosting IP addresses",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"LOCAL_MAILBOX_PROVISIONING",
|
||||||
|
"Mailbox provisioning",
|
||||||
|
"Local mail services or a linked mail receiver",
|
||||||
|
"coulobre-mail-apply",
|
||||||
|
"mail",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"MANAGE_MAIL_DNS",
|
||||||
|
"Managed mail DNS records",
|
||||||
|
"Mail exchanger and sending IP addresses",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"LOCAL_DATABASE_PROVISIONING",
|
||||||
|
"Database provisioning",
|
||||||
|
"MariaDB provisioning",
|
||||||
|
"coulobre-database-apply",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"LOCAL_ACCOUNT_BACKUPS",
|
||||||
|
"Local account backups",
|
||||||
|
"Local backup service",
|
||||||
|
"coulobre-account-backup",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"OFFSITE_BACKUP_DESTINATIONS",
|
||||||
|
"Off-site backup destinations",
|
||||||
|
"A configured destination and the transfer service",
|
||||||
|
"coulobre-account-offsite",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"PHPMYADMIN_URL",
|
||||||
|
"phpMyAdmin sign-in",
|
||||||
|
"phpMyAdmin bridge and MariaDB credential service",
|
||||||
|
"coulobre-service-credentials",
|
||||||
|
),
|
||||||
|
Feature(
|
||||||
|
"ROUNDCUBE_URL",
|
||||||
|
"Roundcube sign-in",
|
||||||
|
"Roundcube bridge and mailbox credential service",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FeaturePolicy:
|
||||||
|
@cached_property
|
||||||
|
def saved(self):
|
||||||
|
return (
|
||||||
|
PanelFeaturePolicy.objects.filter(pk=1).first()
|
||||||
|
or PanelFeaturePolicy()
|
||||||
|
)
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def disabled(self):
|
||||||
|
return frozenset(self.saved.disabled)
|
||||||
|
|
||||||
|
|
||||||
|
current_policy = ContextVar("current_feature_policy", default=None)
|
||||||
|
|
||||||
|
|
||||||
|
def panel_feature_allowed(setting):
|
||||||
|
if not getattr(settings, setting):
|
||||||
|
return False
|
||||||
|
return not panel_feature_paused(setting)
|
||||||
|
|
||||||
|
|
||||||
|
def panel_feature_paused(setting):
|
||||||
|
policy = current_policy.get() or FeaturePolicy()
|
||||||
|
return setting in policy.disabled
|
||||||
|
|
||||||
|
|
||||||
|
def default_dns_zones_allowed(defaults):
|
||||||
|
if not defaults.nameservers or not defaults.addresses:
|
||||||
|
return False
|
||||||
|
policy = current_policy.get() or FeaturePolicy()
|
||||||
|
return (
|
||||||
|
panel_feature_allowed("LOCAL_DNS_PUBLISHING")
|
||||||
|
and "DEFAULT_DNS_ZONES" not in policy.disabled
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FeaturePolicyMiddleware:
|
||||||
|
def __init__(self, get_response):
|
||||||
|
self.get_response = get_response
|
||||||
|
|
||||||
|
def __call__(self, request):
|
||||||
|
token = current_policy.set(FeaturePolicy())
|
||||||
|
try:
|
||||||
|
return self.get_response(request)
|
||||||
|
finally:
|
||||||
|
current_policy.reset(token)
|
||||||
@@ -1,13 +1,23 @@
|
|||||||
from importlib.metadata import PackageNotFoundError, version
|
from importlib.metadata import PackageNotFoundError, version
|
||||||
|
|
||||||
from django.conf import settings
|
from django import forms
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
from django.contrib import messages
|
||||||
|
from django.contrib.admin.models import CHANGE, LogEntry
|
||||||
|
from django.contrib.auth.mixins import (
|
||||||
|
PermissionRequiredMixin,
|
||||||
|
UserPassesTestMixin,
|
||||||
|
)
|
||||||
|
from django.db import transaction
|
||||||
|
from django.db.models import F
|
||||||
|
from django.urls import reverse_lazy
|
||||||
from django.utils.decorators import method_decorator
|
from django.utils.decorators import method_decorator
|
||||||
from django.views.decorators.cache import never_cache
|
from django.views.decorators.cache import never_cache
|
||||||
from django.views.generic import TemplateView
|
from django.views.generic import FormView, TemplateView
|
||||||
|
|
||||||
from .access import OperatorOnlyMixin
|
from .access import OperatorOnlyMixin
|
||||||
from .dns_defaults import zone_defaults
|
from .installation_features import FEATURES, FeaturePolicy
|
||||||
|
from .models import PanelFeaturePolicy
|
||||||
|
from .update_views import inspect_linked_nodes
|
||||||
|
|
||||||
|
|
||||||
@method_decorator(never_cache, name="dispatch")
|
@method_decorator(never_cache, name="dispatch")
|
||||||
@@ -22,41 +32,137 @@ class InstallationView(
|
|||||||
installed_version = version("coulobre-panel")
|
installed_version = version("coulobre-panel")
|
||||||
except PackageNotFoundError:
|
except PackageNotFoundError:
|
||||||
installed_version = "Unavailable"
|
installed_version = "Unavailable"
|
||||||
|
policy = FeaturePolicy()
|
||||||
dns_defaults = zone_defaults()
|
features = []
|
||||||
features = (
|
for feature in FEATURES:
|
||||||
("Local website provisioning", settings.LOCAL_WEB_ACTIVATION),
|
configured = feature.configured
|
||||||
("Managed website certificates", settings.LOCAL_WEB_HTTPS),
|
enabled = (
|
||||||
("Website file manager", settings.WEB_FILE_MANAGER),
|
configured
|
||||||
("Website scheduled tasks", settings.WEBSITE_JOBS),
|
and feature.setting not in policy.disabled
|
||||||
("Local DNS publishing", settings.LOCAL_DNS_PUBLISHING),
|
and (
|
||||||
(
|
feature.setting != "DEFAULT_DNS_ZONES"
|
||||||
"Default managed DNS zones for new accounts",
|
or "LOCAL_DNS_PUBLISHING" not in policy.disabled
|
||||||
settings.LOCAL_DNS_PUBLISHING
|
)
|
||||||
and dns_defaults.nameservers
|
)
|
||||||
and dns_defaults.addresses,
|
features.append((feature, configured, enabled))
|
||||||
),
|
|
||||||
(
|
|
||||||
"Local mailbox provisioning",
|
|
||||||
settings.LOCAL_MAILBOX_PROVISIONING,
|
|
||||||
),
|
|
||||||
("Managed mail DNS records", settings.MANAGE_MAIL_DNS),
|
|
||||||
(
|
|
||||||
"Local database provisioning",
|
|
||||||
settings.LOCAL_DATABASE_PROVISIONING,
|
|
||||||
),
|
|
||||||
("Local account backups", settings.LOCAL_ACCOUNT_BACKUPS),
|
|
||||||
(
|
|
||||||
"Off-site backup destinations",
|
|
||||||
settings.OFFSITE_BACKUP_DESTINATIONS,
|
|
||||||
),
|
|
||||||
("phpMyAdmin sign-in", settings.PHPMYADMIN_URL),
|
|
||||||
("Roundcube sign-in", settings.ROUNDCUBE_URL),
|
|
||||||
)
|
|
||||||
return super().get_context_data(
|
return super().get_context_data(
|
||||||
installed_version=installed_version,
|
installed_version=installed_version, features=features, **kwargs
|
||||||
features=[
|
)
|
||||||
(name, bool(configured)) for name, configured in features
|
|
||||||
],
|
|
||||||
**kwargs,
|
class FeatureConfigurationForm(forms.Form):
|
||||||
|
revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput)
|
||||||
|
|
||||||
|
def __init__(self, *args, policy, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.initial["revision"] = policy.saved.revision
|
||||||
|
self.configured_features = [
|
||||||
|
feature for feature in FEATURES if feature.configured
|
||||||
|
]
|
||||||
|
for feature in self.configured_features:
|
||||||
|
self.fields[feature.setting] = forms.BooleanField(
|
||||||
|
required=False,
|
||||||
|
label=feature.label,
|
||||||
|
help_text=feature.prerequisite,
|
||||||
|
initial=feature.setting not in policy.disabled,
|
||||||
|
)
|
||||||
|
|
||||||
|
def changed_features(self):
|
||||||
|
return [
|
||||||
|
feature
|
||||||
|
for feature in self.configured_features
|
||||||
|
if feature.setting in self.changed_data
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def check_features(form, changed):
|
||||||
|
new_enabled = [
|
||||||
|
feature for feature in changed if form.cleaned_data[feature.setting]
|
||||||
|
]
|
||||||
|
nodes = {}
|
||||||
|
if any(feature.linked for feature in new_enabled):
|
||||||
|
topology = inspect_linked_nodes()
|
||||||
|
nodes = {node["role"]: node for node in topology.get("nodes", [])}
|
||||||
|
for feature in new_enabled:
|
||||||
|
if not feature.socket_ready:
|
||||||
|
form.add_error(
|
||||||
|
feature.setting,
|
||||||
|
"Start the configured service before enabling this feature.",
|
||||||
|
)
|
||||||
|
elif feature.linked:
|
||||||
|
report = nodes.get(feature.role, {})
|
||||||
|
if report.get("state") != "configured" or report.get(
|
||||||
|
"release"
|
||||||
|
) != version("coulobre-panel"):
|
||||||
|
form.add_error(
|
||||||
|
feature.setting,
|
||||||
|
"The linked receiver must be ready and on the same "
|
||||||
|
"release.",
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
feature.setting == "DEFAULT_DNS_ZONES"
|
||||||
|
and not form.cleaned_data.get("LOCAL_DNS_PUBLISHING")
|
||||||
|
):
|
||||||
|
form.add_error(feature.setting, "Enable DNS publishing first.")
|
||||||
|
|
||||||
|
|
||||||
|
@method_decorator(never_cache, name="dispatch")
|
||||||
|
class FeatureConfigurationView(UserPassesTestMixin, FormView):
|
||||||
|
form_class = FeatureConfigurationForm
|
||||||
|
template_name = "hosting/feature_configuration.html"
|
||||||
|
success_url = reverse_lazy("panel:installation")
|
||||||
|
|
||||||
|
def test_func(self):
|
||||||
|
return (
|
||||||
|
self.request.user.is_superuser and self.request.user.is_verified()
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_form_kwargs(self):
|
||||||
|
return {**super().get_form_kwargs(), "policy": FeaturePolicy()}
|
||||||
|
|
||||||
|
def form_valid(self, form):
|
||||||
|
revision = form.cleaned_data["revision"]
|
||||||
|
policy = FeaturePolicy()
|
||||||
|
if revision != policy.saved.revision:
|
||||||
|
return self.stale_form(form)
|
||||||
|
changed = form.changed_features()
|
||||||
|
if not changed:
|
||||||
|
return super().form_valid(form)
|
||||||
|
check_features(form, changed)
|
||||||
|
if form.errors:
|
||||||
|
return self.form_invalid(form)
|
||||||
|
disabled = set(policy.disabled)
|
||||||
|
for feature in changed:
|
||||||
|
if form.cleaned_data[feature.setting]:
|
||||||
|
disabled.discard(feature.setting)
|
||||||
|
else:
|
||||||
|
disabled.add(feature.setting)
|
||||||
|
with transaction.atomic():
|
||||||
|
saved, _ = PanelFeaturePolicy.objects.get_or_create(pk=1)
|
||||||
|
updated = PanelFeaturePolicy.objects.filter(
|
||||||
|
pk=1, revision=revision
|
||||||
|
).update(disabled=sorted(disabled), revision=F("revision") + 1)
|
||||||
|
if not updated:
|
||||||
|
return self.stale_form(form)
|
||||||
|
LogEntry.objects.log_actions(
|
||||||
|
self.request.user.pk,
|
||||||
|
[saved],
|
||||||
|
CHANGE,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"changed": {
|
||||||
|
"fields": [feature.label for feature in changed]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
messages.success(self.request, "Feature configuration saved.")
|
||||||
|
return super().form_valid(form)
|
||||||
|
|
||||||
|
def stale_form(self, form):
|
||||||
|
form.add_error(
|
||||||
|
None, "The configuration changed. Reopen this page and try again."
|
||||||
|
)
|
||||||
|
return self.render_to_response(
|
||||||
|
self.get_context_data(form=form), status=409
|
||||||
)
|
)
|
||||||
@@ -22,6 +22,7 @@ from coulobre.mail_dns import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant
|
from .access import OperatorOnlyMixin, TenantScopeMixin, is_tenant
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .mail_dns_setup import (
|
from .mail_dns_setup import (
|
||||||
closest_zone,
|
closest_zone,
|
||||||
mail_dns_proposal,
|
mail_dns_proposal,
|
||||||
@@ -156,8 +157,8 @@ class MailDnsCheckView(
|
|||||||
report=report,
|
report=report,
|
||||||
mail_domain=self.object,
|
mail_domain=self.object,
|
||||||
can_refresh=(
|
can_refresh=(
|
||||||
settings.MANAGE_MAIL_DNS
|
panel_feature_allowed("MANAGE_MAIL_DNS")
|
||||||
and settings.LOCAL_MAILBOX_PROVISIONING
|
and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
|
||||||
and not is_tenant(self.request.user)
|
and not is_tenant(self.request.user)
|
||||||
and self.request.user.has_perms(PROVISION_MAILBOX)
|
and self.request.user.has_perms(PROVISION_MAILBOX)
|
||||||
and self.object.mailboxes.filter(
|
and self.object.mailboxes.filter(
|
||||||
@@ -261,7 +262,8 @@ class RequestMailDnsSetup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
|
|
||||||
def post(self, request, pk):
|
def post(self, request, pk):
|
||||||
if not (
|
if not (
|
||||||
settings.MANAGE_MAIL_DNS and settings.LOCAL_MAILBOX_PROVISIONING
|
panel_feature_allowed("MANAGE_MAIL_DNS")
|
||||||
|
and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
|
||||||
):
|
):
|
||||||
raise Http404
|
raise Http404
|
||||||
domain = get_object_or_404(HostingMailDomain, pk=pk)
|
domain = get_object_or_404(HostingMailDomain, pk=pk)
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.http import Http404
|
from django.http import Http404
|
||||||
@@ -11,6 +10,7 @@ from django.views.decorators.cache import never_cache
|
|||||||
from django.views.generic import TemplateView
|
from django.views.generic import TemplateView
|
||||||
|
|
||||||
from .access import OperatorOnlyMixin
|
from .access import OperatorOnlyMixin
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import HostingMailDomain
|
from .models import HostingMailDomain
|
||||||
from .tasks import refresh_mail_queue
|
from .tasks import refresh_mail_queue
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ class MailQueueView(OperatorOnlyMixin, PermissionRequiredMixin, TemplateView):
|
|||||||
template_name = "hosting/mail_queue.html"
|
template_name = "hosting/mail_queue.html"
|
||||||
|
|
||||||
def get_domain(self, *, locked=False):
|
def get_domain(self, *, locked=False):
|
||||||
if not settings.LOCAL_MAILBOX_PROVISIONING:
|
if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"):
|
||||||
raise Http404
|
raise Http404
|
||||||
domains = HostingMailDomain.objects.filter(
|
domains = HostingMailDomain.objects.filter(
|
||||||
account__retired_at__isnull=True
|
account__retired_at__isnull=True
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-22 23:08
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("hosting", "0056_dns_zone_defaults"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="PanelAccountSecurity",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("session_version", models.PositiveBigIntegerField(default=0)),
|
||||||
|
(
|
||||||
|
"user",
|
||||||
|
models.OneToOneField(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="PanelEmailChange",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("email", models.EmailField(max_length=254)),
|
||||||
|
("digest", models.CharField(max_length=64)),
|
||||||
|
("session_digest", models.CharField(max_length=64)),
|
||||||
|
("expires_at", models.DateTimeField()),
|
||||||
|
(
|
||||||
|
"user",
|
||||||
|
models.OneToOneField(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="PanelSecurityEvent",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("username", models.CharField(max_length=150)),
|
||||||
|
(
|
||||||
|
"action",
|
||||||
|
models.CharField(
|
||||||
|
choices=[
|
||||||
|
("password", "Password changed"),
|
||||||
|
("email", "Email address changed"),
|
||||||
|
("factor", "Authenticator updated"),
|
||||||
|
("recovery", "Recovery codes replaced"),
|
||||||
|
("reset", "Operator-issued factor recovery"),
|
||||||
|
("sessions", "Other sessions signed out"),
|
||||||
|
],
|
||||||
|
max_length=12,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("created_at", models.DateTimeField(auto_now_add=True)),
|
||||||
|
(
|
||||||
|
"user",
|
||||||
|
models.ForeignKey(
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.SET_NULL,
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"indexes": [
|
||||||
|
models.Index(
|
||||||
|
fields=["user", "-id"],
|
||||||
|
name="hosting_pan_user_id_9e9e3e_idx",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-23 19:26
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("hosting", "0057_panel_account_security"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="phpmyadmingrant",
|
||||||
|
name="actor_scope",
|
||||||
|
field=models.JSONField(blank=True, default=list),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="roundcubegrant",
|
||||||
|
name="actor_scope",
|
||||||
|
field=models.JSONField(blank=True, default=list),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-23 19:32
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("hosting", "0058_scope_service_signon_grants"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="PanelFeaturePolicy",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("disabled", models.JSONField(blank=True, default=list)),
|
||||||
|
("revision", models.PositiveBigIntegerField(default=0)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -582,6 +582,7 @@ class ServiceSignOnGrant(models.Model):
|
|||||||
actor = models.ForeignKey(
|
actor = models.ForeignKey(
|
||||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
|
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
|
||||||
)
|
)
|
||||||
|
actor_scope = models.JSONField(default=list, blank=True)
|
||||||
expires_at = models.DateTimeField(db_index=True)
|
expires_at = models.DateTimeField(db_index=True)
|
||||||
redeemed_at = models.DateTimeField(null=True, blank=True)
|
redeemed_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
|
||||||
@@ -607,6 +608,11 @@ class DirectAdminImport(models.Model):
|
|||||||
fingerprint = models.CharField(max_length=64, unique=True)
|
fingerprint = models.CharField(max_length=64, unique=True)
|
||||||
|
|
||||||
|
|
||||||
|
class PanelFeaturePolicy(models.Model):
|
||||||
|
disabled = models.JSONField(default=list, blank=True)
|
||||||
|
revision = models.PositiveBigIntegerField(default=0)
|
||||||
|
|
||||||
|
|
||||||
class DnsZoneDefaults(models.Model):
|
class DnsZoneDefaults(models.Model):
|
||||||
nameservers = models.JSONField(default=list, blank=True)
|
nameservers = models.JSONField(default=list, blank=True)
|
||||||
addresses = models.JSONField(default=list, blank=True)
|
addresses = models.JSONField(default=list, blank=True)
|
||||||
@@ -1354,3 +1360,40 @@ class PanelRecoveryCode(models.Model):
|
|||||||
name="hosting_unique_panel_recovery_code",
|
name="hosting_unique_panel_recovery_code",
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class PanelAccountSecurity(models.Model):
|
||||||
|
user = models.OneToOneField(
|
||||||
|
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
|
||||||
|
)
|
||||||
|
session_version = models.PositiveBigIntegerField(default=0)
|
||||||
|
|
||||||
|
|
||||||
|
class PanelEmailChange(models.Model):
|
||||||
|
user = models.OneToOneField(
|
||||||
|
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
|
||||||
|
)
|
||||||
|
email = models.EmailField()
|
||||||
|
digest = models.CharField(max_length=64)
|
||||||
|
session_digest = models.CharField(max_length=64)
|
||||||
|
expires_at = models.DateTimeField()
|
||||||
|
|
||||||
|
|
||||||
|
class PanelSecurityEvent(models.Model):
|
||||||
|
class Action(models.TextChoices):
|
||||||
|
PASSWORD = "password", "Password changed"
|
||||||
|
EMAIL = "email", "Email address changed"
|
||||||
|
FACTOR = "factor", "Authenticator updated"
|
||||||
|
RECOVERY = "recovery", "Recovery codes replaced"
|
||||||
|
RESET = "reset", "Operator-issued factor recovery"
|
||||||
|
SESSIONS = "sessions", "Other sessions signed out"
|
||||||
|
|
||||||
|
user = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
|
||||||
|
)
|
||||||
|
username = models.CharField(max_length=150)
|
||||||
|
action = models.CharField(max_length=12, choices=Action.choices)
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
indexes = [models.Index(fields=["user", "-id"])]
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import json
|
import json
|
||||||
import socket
|
import socket
|
||||||
|
from importlib.metadata import version
|
||||||
|
|
||||||
from django.views.decorators.debug import sensitive_variables
|
from django.views.decorators.debug import sensitive_variables
|
||||||
|
|
||||||
@@ -11,8 +12,10 @@ from coulobre.account_restore_request import (
|
|||||||
RESTORE_SOCKET,
|
RESTORE_SOCKET,
|
||||||
RESTORE_TIMEOUT_SECONDS,
|
RESTORE_TIMEOUT_SECONDS,
|
||||||
)
|
)
|
||||||
|
from coulobre.linked_updates import ROLES, UNIT_DIR, read_probe
|
||||||
from coulobre.mail_dns import dkim_key
|
from coulobre.mail_dns import dkim_key
|
||||||
from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest
|
from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest
|
||||||
|
from coulobre.node_probe import PROBE_BYTES, parse_status_probe
|
||||||
from coulobre.php_pool_settings import PhpPoolSettings
|
from coulobre.php_pool_settings import PhpPoolSettings
|
||||||
from coulobre.php_runtime import validate_php_version
|
from coulobre.php_runtime import validate_php_version
|
||||||
from coulobre.web_node import (
|
from coulobre.web_node import (
|
||||||
@@ -250,6 +253,7 @@ def encode_manifest(manifest):
|
|||||||
def apply_on_local_node(
|
def apply_on_local_node(
|
||||||
spec, socket_path, node, resource, *, identity=None, timeout=195
|
spec, socket_path, node, resource, *, identity=None, timeout=195
|
||||||
):
|
):
|
||||||
|
require_matching_receiver(socket_path)
|
||||||
manifest = spec.manifest()
|
manifest = spec.manifest()
|
||||||
expected = manifest if identity is None else identity
|
expected = manifest if identity is None else identity
|
||||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
|
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
|
||||||
@@ -284,3 +288,23 @@ def apply_on_local_node(
|
|||||||
if state == "failed" and isinstance(problem, str) and problem.strip():
|
if state == "failed" and isinstance(problem, str) and problem.strip():
|
||||||
raise ValueError(problem.strip()[:2000])
|
raise ValueError(problem.strip()[:2000])
|
||||||
raise NodeReplyError(invalid_response)
|
raise NodeReplyError(invalid_response)
|
||||||
|
|
||||||
|
|
||||||
|
def require_matching_receiver(socket_path):
|
||||||
|
for role in ROLES:
|
||||||
|
unit = f"coulobre-{role}-apply"
|
||||||
|
if str(socket_path) != f"/run/{unit}.sock":
|
||||||
|
continue
|
||||||
|
if not (UNIT_DIR / f"{unit}@.service.d/remote.conf").exists():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
report = parse_status_probe(read_probe(role, PROBE_BYTES), role)
|
||||||
|
if report["state"] == "configured" and report[
|
||||||
|
"release"
|
||||||
|
] == version("coulobre-panel"):
|
||||||
|
return
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
raise NodeReplyError(
|
||||||
|
f"The linked {role} receiver is not ready for this release."
|
||||||
|
)
|
||||||
@@ -17,7 +17,17 @@ from django_otp.models import Device
|
|||||||
from django_otp.plugins.otp_email.models import EmailDevice
|
from django_otp.plugins.otp_email.models import EmailDevice
|
||||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
|
||||||
from .models import PanelFactorEnrollment, PanelRecoveryCode
|
from .models import (
|
||||||
|
PanelFactorEnrollment,
|
||||||
|
PanelRecoveryCode,
|
||||||
|
PanelSecurityEvent,
|
||||||
|
)
|
||||||
|
from .panel_sessions import (
|
||||||
|
SESSION_VERSION,
|
||||||
|
record_security_event,
|
||||||
|
revoke_other_sessions,
|
||||||
|
session_version,
|
||||||
|
)
|
||||||
|
|
||||||
DEVICE_NAME = "Coulobre Panel"
|
DEVICE_NAME = "Coulobre Panel"
|
||||||
DEVICE_TYPES = {"authenticator": TOTPDevice, "email": EmailDevice}
|
DEVICE_TYPES = {"authenticator": TOTPDevice, "email": EmailDevice}
|
||||||
@@ -25,6 +35,7 @@ CHALLENGE_SESSION = "coulobre_panel_challenge"
|
|||||||
SETUP_SESSION = "coulobre_panel_factor_device"
|
SETUP_SESSION = "coulobre_panel_factor_device"
|
||||||
SETUP_EXPIRES = "coulobre_panel_factor_expiry"
|
SETUP_EXPIRES = "coulobre_panel_factor_expiry"
|
||||||
SETUP_DESTINATION = "coulobre_panel_factor_destination"
|
SETUP_DESTINATION = "coulobre_panel_factor_destination"
|
||||||
|
RECOVERY_SIGN_IN = "coulobre_panel_recovery_sign_in"
|
||||||
CHALLENGE_SECONDS = 300
|
CHALLENGE_SECONDS = 300
|
||||||
ENROLLMENT_MINUTES = 20
|
ENROLLMENT_MINUTES = 20
|
||||||
|
|
||||||
@@ -39,7 +50,12 @@ def privileged_user(user):
|
|||||||
|
|
||||||
|
|
||||||
def requires_panel_factor(user):
|
def requires_panel_factor(user):
|
||||||
return settings.REQUIRE_PRIVILEGED_MFA and privileged_user(user)
|
return user.is_authenticated and (
|
||||||
|
settings.REQUIRE_PRIVILEGED_MFA
|
||||||
|
and privileged_user(user)
|
||||||
|
or confirmed_device(user) is not None
|
||||||
|
or recovery_required(user)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def lock_user(user_id):
|
def lock_user(user_id):
|
||||||
@@ -111,6 +127,8 @@ def issue_recovery_enrollment(user):
|
|||||||
+ timedelta(minutes=ENROLLMENT_MINUTES),
|
+ timedelta(minutes=ENROLLMENT_MINUTES),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
revoke_other_sessions(user)
|
||||||
|
record_security_event(user, PanelSecurityEvent.Action.RESET)
|
||||||
return code
|
return code
|
||||||
|
|
||||||
|
|
||||||
@@ -162,10 +180,12 @@ def start_challenge(request, user, destination):
|
|||||||
request.session.cycle_key()
|
request.session.cycle_key()
|
||||||
rotate_token(request)
|
rotate_token(request)
|
||||||
request.session.pop(SETUP_SESSION, None)
|
request.session.pop(SETUP_SESSION, None)
|
||||||
|
request.session.pop(RECOVERY_SIGN_IN, None)
|
||||||
request.session[CHALLENGE_SESSION] = {
|
request.session[CHALLENGE_SESSION] = {
|
||||||
"user": user.pk,
|
"user": user.pk,
|
||||||
"backend": user.backend,
|
"backend": user.backend,
|
||||||
"auth_hash": user.get_session_auth_hash(),
|
"auth_hash": user.get_session_auth_hash(),
|
||||||
|
"session_version": session_version(user),
|
||||||
"expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS,
|
"expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS,
|
||||||
"next": destination,
|
"next": destination,
|
||||||
}
|
}
|
||||||
@@ -184,6 +204,7 @@ def pending_user(request):
|
|||||||
data["expires"] > int(timezone.now().timestamp())
|
data["expires"] > int(timezone.now().timestamp())
|
||||||
and user is not None
|
and user is not None
|
||||||
and requires_panel_factor(user)
|
and requires_panel_factor(user)
|
||||||
|
and data.get("session_version", 0) == session_version(user)
|
||||||
and constant_time_compare(
|
and constant_time_compare(
|
||||||
data["auth_hash"], user.get_session_auth_hash()
|
data["auth_hash"], user.get_session_auth_hash()
|
||||||
)
|
)
|
||||||
@@ -204,6 +225,7 @@ def complete_challenge(request, user, device):
|
|||||||
else:
|
else:
|
||||||
data = request.session.pop(CHALLENGE_SESSION)
|
data = request.session.pop(CHALLENGE_SESSION)
|
||||||
login(request, user, backend=data["backend"])
|
login(request, user, backend=data["backend"])
|
||||||
|
request.session[SESSION_VERSION] = data.get("session_version", 0)
|
||||||
destination = data["next"]
|
destination = data["next"]
|
||||||
django_otp.login(request, device)
|
django_otp.login(request, device)
|
||||||
return destination
|
return destination
|
||||||
@@ -223,6 +245,12 @@ def confirm_enrollment(user, device_id, token):
|
|||||||
device.confirmed = True
|
device.confirmed = True
|
||||||
device.save(update_fields=["confirmed"])
|
device.save(update_fields=["confirmed"])
|
||||||
PanelFactorEnrollment.objects.filter(user=user).delete()
|
PanelFactorEnrollment.objects.filter(user=user).delete()
|
||||||
|
return device, replace_recovery_codes(user)
|
||||||
|
|
||||||
|
|
||||||
|
@sensitive_variables("codes")
|
||||||
|
def replace_recovery_codes(user):
|
||||||
|
PanelRecoveryCode.objects.filter(user=user).delete()
|
||||||
codes = [secrets.token_hex(10) for _ in range(10)]
|
codes = [secrets.token_hex(10) for _ in range(10)]
|
||||||
PanelRecoveryCode.objects.bulk_create(
|
PanelRecoveryCode.objects.bulk_create(
|
||||||
[
|
[
|
||||||
@@ -232,7 +260,7 @@ def confirm_enrollment(user, device_id, token):
|
|||||||
for code in codes
|
for code in codes
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
return device, codes
|
return codes
|
||||||
|
|
||||||
|
|
||||||
@sensitive_variables("code")
|
@sensitive_variables("code")
|
||||||
|
|||||||
@@ -0,0 +1,207 @@
|
|||||||
|
from copy import copy
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
from django.contrib import messages
|
||||||
|
from django.contrib.admin.models import ADDITION, LogEntry
|
||||||
|
from django.contrib.auth import get_user_model, logout
|
||||||
|
from django.contrib.auth.middleware import get_user
|
||||||
|
from django.contrib.auth.mixins import UserPassesTestMixin
|
||||||
|
from django.core.exceptions import PermissionDenied
|
||||||
|
from django.db import transaction
|
||||||
|
from django.middleware.csrf import rotate_token
|
||||||
|
from django.shortcuts import redirect
|
||||||
|
from django.utils.cache import add_never_cache_headers
|
||||||
|
from django.utils.decorators import method_decorator
|
||||||
|
from django.views.decorators.cache import never_cache
|
||||||
|
from django.views.decorators.http import require_POST
|
||||||
|
from django.views.generic import FormView
|
||||||
|
|
||||||
|
from .access import PanelRole
|
||||||
|
from .models import Customer, Reseller, ResellerProfile
|
||||||
|
|
||||||
|
SESSION_ROLE = "coulobre_panel_role"
|
||||||
|
ROLE_LABELS = {
|
||||||
|
PanelRole.ADMIN: "Server administrator",
|
||||||
|
PanelRole.CUSTOMER: "Customer",
|
||||||
|
PanelRole.MANAGER: "Customer manager",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def assigned_roles(user):
|
||||||
|
if not user.is_authenticated or not user.is_active:
|
||||||
|
return {}
|
||||||
|
roles = {}
|
||||||
|
if user.is_superuser:
|
||||||
|
roles[PanelRole.ADMIN] = user.pk
|
||||||
|
customer = getattr(user, "hosting_customer", None)
|
||||||
|
if customer is not None:
|
||||||
|
roles[PanelRole.CUSTOMER] = customer.pk
|
||||||
|
manager = getattr(user, "hosting_reseller", None)
|
||||||
|
if manager is not None:
|
||||||
|
roles[PanelRole.MANAGER] = manager.pk
|
||||||
|
return roles
|
||||||
|
|
||||||
|
|
||||||
|
def deny_permission(*args, **kwargs):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def no_permissions(*args, **kwargs):
|
||||||
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
async def deny_async_permission(*args, **kwargs):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def no_async_permissions(*args, **kwargs):
|
||||||
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
def scoped_user(user, role):
|
||||||
|
actor = copy(user)
|
||||||
|
actor.panel_role = role
|
||||||
|
if role != PanelRole.ADMIN:
|
||||||
|
actor.is_staff = actor.is_superuser = False
|
||||||
|
actor.has_perm = actor.has_perms = actor.has_module_perms = (
|
||||||
|
deny_permission
|
||||||
|
)
|
||||||
|
actor.get_all_permissions = actor.get_user_permissions = (
|
||||||
|
actor.get_group_permissions
|
||||||
|
) = no_permissions
|
||||||
|
actor.ahas_perm = actor.ahas_perms = actor.ahas_module_perms = (
|
||||||
|
deny_async_permission
|
||||||
|
)
|
||||||
|
actor.aget_all_permissions = actor.aget_user_permissions = (
|
||||||
|
actor.aget_group_permissions
|
||||||
|
) = no_async_permissions
|
||||||
|
return actor
|
||||||
|
|
||||||
|
|
||||||
|
class PanelRoleMiddleware:
|
||||||
|
def __init__(self, get_response):
|
||||||
|
self.get_response = get_response
|
||||||
|
|
||||||
|
def __call__(self, request):
|
||||||
|
response = self.get_response(request)
|
||||||
|
if getattr(request, "active_panel_role", None):
|
||||||
|
add_never_cache_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
def process_view(self, request, view_func, view_args, view_kwargs):
|
||||||
|
if not request.user.is_authenticated:
|
||||||
|
return None
|
||||||
|
user = get_user(request)
|
||||||
|
roles = assigned_roles(user)
|
||||||
|
selection = request.session.get(SESSION_ROLE)
|
||||||
|
if selection is None:
|
||||||
|
if len(roles) < 2:
|
||||||
|
return None
|
||||||
|
role, assignment = next(iter(roles.items()))
|
||||||
|
request.session[SESSION_ROLE] = [role, assignment]
|
||||||
|
else:
|
||||||
|
role, assignment = selection
|
||||||
|
if roles.get(role) != assignment:
|
||||||
|
logout(request)
|
||||||
|
messages.warning(
|
||||||
|
request, "Your panel roles changed. Sign in again."
|
||||||
|
)
|
||||||
|
return redirect("panel:login")
|
||||||
|
|
||||||
|
request.active_panel_role = role
|
||||||
|
request.panel_role_options = [
|
||||||
|
(option, ROLE_LABELS[option]) for option in roles
|
||||||
|
]
|
||||||
|
request.user = scoped_user(user, role)
|
||||||
|
|
||||||
|
async def role_user():
|
||||||
|
return request.user
|
||||||
|
|
||||||
|
request.auser = role_user
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@require_POST
|
||||||
|
def switch_panel_role(request):
|
||||||
|
if not request.user.is_authenticated or getattr(
|
||||||
|
request, "impersonation", None
|
||||||
|
):
|
||||||
|
raise PermissionDenied
|
||||||
|
user = get_user(request)
|
||||||
|
roles = assigned_roles(user)
|
||||||
|
role = request.POST.get("role")
|
||||||
|
if role not in roles or len(roles) < 2:
|
||||||
|
raise PermissionDenied
|
||||||
|
if role == PanelRole.ADMIN and not request.user.is_verified():
|
||||||
|
raise PermissionDenied
|
||||||
|
if role != request.active_panel_role:
|
||||||
|
request.session.cycle_key()
|
||||||
|
request.session[SESSION_ROLE] = [role, roles[role]]
|
||||||
|
rotate_token(request)
|
||||||
|
return redirect("panel:accounts")
|
||||||
|
|
||||||
|
|
||||||
|
ROLE_MODELS = {PanelRole.CUSTOMER: Customer, PanelRole.MANAGER: Reseller}
|
||||||
|
|
||||||
|
|
||||||
|
class AssignPanelRoleForm(forms.Form):
|
||||||
|
username = forms.CharField(max_length=150, label="Existing username")
|
||||||
|
role = forms.ChoiceField(
|
||||||
|
choices=[(role, ROLE_LABELS[role]) for role in ROLE_MODELS],
|
||||||
|
label="Role to assign",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@method_decorator(never_cache, name="dispatch")
|
||||||
|
class AssignPanelRoleView(UserPassesTestMixin, FormView):
|
||||||
|
form_class = AssignPanelRoleForm
|
||||||
|
template_name = "hosting/assign_panel_role.html"
|
||||||
|
|
||||||
|
def test_func(self):
|
||||||
|
return (
|
||||||
|
self.request.user.is_superuser and self.request.user.is_verified()
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_initial(self):
|
||||||
|
role = self.request.GET.get("role")
|
||||||
|
return {"role": role} if role in ROLE_MODELS else {}
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def form_valid(self, form):
|
||||||
|
user = (
|
||||||
|
get_user_model()
|
||||||
|
.objects.select_for_update()
|
||||||
|
.filter(username=form.cleaned_data["username"], is_active=True)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if user is None:
|
||||||
|
form.add_error("username", "Choose an active panel login.")
|
||||||
|
return self.form_invalid(form)
|
||||||
|
role = form.cleaned_data["role"]
|
||||||
|
assignment, created = ROLE_MODELS[role].objects.get_or_create(
|
||||||
|
user=user
|
||||||
|
)
|
||||||
|
if not created:
|
||||||
|
form.add_error("role", "This login already has that role.")
|
||||||
|
return self.form_invalid(form)
|
||||||
|
if role == PanelRole.MANAGER:
|
||||||
|
profile = ResellerProfile.objects.filter(default_slot=1).first()
|
||||||
|
if profile is not None:
|
||||||
|
assignment.account_limit = profile.account_limit
|
||||||
|
assignment.manage_resources = profile.manage_resources
|
||||||
|
assignment.save(
|
||||||
|
update_fields=["account_limit", "manage_resources"]
|
||||||
|
)
|
||||||
|
assignment.hosting_plans.set(profile.hosting_plans.all())
|
||||||
|
LogEntry.objects.log_actions(
|
||||||
|
self.request.user.pk,
|
||||||
|
[assignment],
|
||||||
|
ADDITION,
|
||||||
|
"Assigned panel role.",
|
||||||
|
)
|
||||||
|
messages.success(
|
||||||
|
self.request, f"Assigned {ROLE_LABELS[role]} to {user}."
|
||||||
|
)
|
||||||
|
if role == PanelRole.MANAGER:
|
||||||
|
return redirect(assignment)
|
||||||
|
return redirect("panel:customers")
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
from django.contrib.auth import logout
|
||||||
|
from django.contrib.auth.views import redirect_to_login
|
||||||
|
from django.db.models import F
|
||||||
|
from django.middleware.csrf import rotate_token
|
||||||
|
|
||||||
|
from .models import (
|
||||||
|
PanelAccountSecurity,
|
||||||
|
PanelEmailChange,
|
||||||
|
PanelSecurityEvent,
|
||||||
|
PhpMyAdminGrant,
|
||||||
|
RoundcubeGrant,
|
||||||
|
)
|
||||||
|
|
||||||
|
SESSION_VERSION = "coulobre_account_session_version"
|
||||||
|
|
||||||
|
|
||||||
|
def session_version(user):
|
||||||
|
return (
|
||||||
|
PanelAccountSecurity.objects.filter(user=user)
|
||||||
|
.values_list("session_version", flat=True)
|
||||||
|
.first()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def session_is_current(request, user):
|
||||||
|
return request.session.get(SESSION_VERSION, 0) == session_version(user)
|
||||||
|
|
||||||
|
|
||||||
|
def revoke_other_sessions(user):
|
||||||
|
state, _ = PanelAccountSecurity.objects.get_or_create(user=user)
|
||||||
|
PanelAccountSecurity.objects.filter(pk=state.pk).update(
|
||||||
|
session_version=F("session_version") + 1
|
||||||
|
)
|
||||||
|
PanelEmailChange.objects.filter(user=user).delete()
|
||||||
|
for grants in (PhpMyAdminGrant, RoundcubeGrant):
|
||||||
|
grants.objects.filter(actor=user, redeemed_at__isnull=True).delete()
|
||||||
|
return session_version(user)
|
||||||
|
|
||||||
|
|
||||||
|
def preserve_session(request, new_version):
|
||||||
|
request.session.cycle_key()
|
||||||
|
request.session[SESSION_VERSION] = new_version
|
||||||
|
rotate_token(request)
|
||||||
|
|
||||||
|
|
||||||
|
def record_security_event(user, action):
|
||||||
|
PanelSecurityEvent.objects.create(
|
||||||
|
user=user, username=user.get_username(), action=action
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PanelSessionMiddleware:
|
||||||
|
def __init__(self, get_response):
|
||||||
|
self.get_response = get_response
|
||||||
|
|
||||||
|
def __call__(self, request):
|
||||||
|
return self.get_response(request)
|
||||||
|
|
||||||
|
def process_view(self, request, view_func, view_args, view_kwargs):
|
||||||
|
if request.user.is_authenticated and not session_is_current(
|
||||||
|
request, request.user
|
||||||
|
):
|
||||||
|
logout(request)
|
||||||
|
if request.resolver_match.view_name == "panel:logout":
|
||||||
|
return None
|
||||||
|
destination = (
|
||||||
|
request.get_full_path()
|
||||||
|
if request.method in {"GET", "HEAD"}
|
||||||
|
else "/"
|
||||||
|
)
|
||||||
|
return redirect_to_login(destination)
|
||||||
|
return None
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
from django.http import Http404, JsonResponse
|
from django.http import Http404, JsonResponse
|
||||||
from django.shortcuts import render
|
from django.shortcuts import render
|
||||||
from django.views.decorators.cache import never_cache
|
from django.views.decorators.cache import never_cache
|
||||||
@@ -11,6 +12,7 @@ from django.views.decorators.http import require_POST
|
|||||||
|
|
||||||
from .access import customer_for_user
|
from .access import customer_for_user
|
||||||
from .credential_views import DatabaseCredentialView
|
from .credential_views import DatabaseCredentialView
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import HostingDatabase, PhpMyAdminGrant, ServiceCredentialAccess
|
from .models import HostingDatabase, PhpMyAdminGrant, ServiceCredentialAccess
|
||||||
from .service_credentials import (
|
from .service_credentials import (
|
||||||
CredentialKind,
|
CredentialKind,
|
||||||
@@ -19,12 +21,17 @@ from .service_credentials import (
|
|||||||
enabled_credential_access,
|
enabled_credential_access,
|
||||||
fetch_service_credentials,
|
fetch_service_credentials,
|
||||||
)
|
)
|
||||||
from .signon import bridge_ticket, consume_signon_grant, issue_signon_grant
|
from .signon import (
|
||||||
|
bridge_ticket,
|
||||||
|
consume_signon_grant,
|
||||||
|
issue_signon_grant,
|
||||||
|
signon_actor,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def phpmyadmin_available(request):
|
def phpmyadmin_available(request):
|
||||||
return bool(
|
return bool(
|
||||||
settings.PHPMYADMIN_URL
|
panel_feature_allowed("PHPMYADMIN_URL")
|
||||||
and settings.PHPMYADMIN_BRIDGE_KEY
|
and settings.PHPMYADMIN_BRIDGE_KEY
|
||||||
and enabled_credential_access(request, CredentialKind.DATABASE)
|
and enabled_credential_access(request, CredentialKind.DATABASE)
|
||||||
)
|
)
|
||||||
@@ -79,9 +86,10 @@ def redeem_phpmyadmin(request):
|
|||||||
raise Http404
|
raise Http404
|
||||||
token = bridge_ticket(request, settings.PHPMYADMIN_BRIDGE_KEY)
|
token = bridge_ticket(request, settings.PHPMYADMIN_BRIDGE_KEY)
|
||||||
grant = consume_signon_grant(PhpMyAdminGrant, token, "database__account")
|
grant = consume_signon_grant(PhpMyAdminGrant, token, "database__account")
|
||||||
if grant is None or not actor_has_database_access(
|
if grant is None:
|
||||||
grant.actor, grant.database
|
raise Http404
|
||||||
):
|
actor = signon_actor(grant, grant.actor)
|
||||||
|
if actor is None or not actor_has_database_access(actor, grant.database):
|
||||||
raise Http404
|
raise Http404
|
||||||
|
|
||||||
database = grant.database
|
database = grant.database
|
||||||
@@ -107,10 +115,14 @@ def redeem_phpmyadmin(request):
|
|||||||
.filter(pk=database.pk)
|
.filter(pk=database.pk)
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
|
actor = signon_actor(
|
||||||
|
grant, get_user_model().objects.filter(pk=grant.actor_id).first()
|
||||||
|
)
|
||||||
if (
|
if (
|
||||||
current is None
|
current is None
|
||||||
|
or actor is None
|
||||||
or current.spec != database.spec
|
or current.spec != database.spec
|
||||||
or not actor_has_database_access(grant.actor, current)
|
or not actor_has_database_access(actor, current)
|
||||||
):
|
):
|
||||||
audit.outcome = CredentialOutcome.UNAVAILABLE
|
audit.outcome = CredentialOutcome.UNAVAILABLE
|
||||||
audit.save(update_fields=["outcome"])
|
audit.save(update_fields=["outcome"])
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
from django.core.exceptions import PermissionDenied, ValidationError
|
from django.core.exceptions import PermissionDenied, ValidationError
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
|
|
||||||
from .access import reseller_for_user
|
|
||||||
from .models import Customer, HostingAccount, Reseller, ResellerAuditEvent
|
from .models import Customer, HostingAccount, Reseller, ResellerAuditEvent
|
||||||
from .reseller_accounts import lock_resellers, record_event
|
from .reseller_accounts import lock_resellers, record_event
|
||||||
from .resource_requests import lock_hosting_account, require_open_account
|
from .resource_requests import lock_hosting_account, require_open_account
|
||||||
@@ -24,11 +23,7 @@ def lock_reseller_account(access, account_id, *, resources=False):
|
|||||||
reseller = lock_resellers(
|
reseller = lock_resellers(
|
||||||
Reseller.objects.filter(pk=access.pk, user_id=access.user_id)
|
Reseller.objects.filter(pk=access.pk, user_id=access.user_id)
|
||||||
).first()
|
).first()
|
||||||
if (
|
if reseller is None or not reseller.user.is_active:
|
||||||
reseller is None
|
|
||||||
or not reseller.user.is_active
|
|
||||||
or reseller_for_user(reseller.user) is None
|
|
||||||
):
|
|
||||||
raise PermissionDenied
|
raise PermissionDenied
|
||||||
if resources and not reseller.manage_resources:
|
if resources and not reseller.manage_resources:
|
||||||
raise PermissionDenied
|
raise PermissionDenied
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from django.views.decorators.http import require_POST
|
|||||||
|
|
||||||
from .access import customer_for_user
|
from .access import customer_for_user
|
||||||
from .credential_views import MailboxCredentialView
|
from .credential_views import MailboxCredentialView
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import HostingMailbox, RoundcubeGrant, ServiceCredentialAccess
|
from .models import HostingMailbox, RoundcubeGrant, ServiceCredentialAccess
|
||||||
from .service_credentials import (
|
from .service_credentials import (
|
||||||
CredentialKind,
|
CredentialKind,
|
||||||
@@ -20,12 +21,17 @@ from .service_credentials import (
|
|||||||
enabled_credential_access,
|
enabled_credential_access,
|
||||||
fetch_service_credentials,
|
fetch_service_credentials,
|
||||||
)
|
)
|
||||||
from .signon import bridge_ticket, consume_signon_grant, issue_signon_grant
|
from .signon import (
|
||||||
|
bridge_ticket,
|
||||||
|
consume_signon_grant,
|
||||||
|
issue_signon_grant,
|
||||||
|
signon_actor,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def roundcube_available(request):
|
def roundcube_available(request):
|
||||||
return bool(
|
return bool(
|
||||||
settings.ROUNDCUBE_URL
|
panel_feature_allowed("ROUNDCUBE_URL")
|
||||||
and settings.ROUNDCUBE_BRIDGE_KEY
|
and settings.ROUNDCUBE_BRIDGE_KEY
|
||||||
and enabled_credential_access(request, CredentialKind.MAILBOX)
|
and enabled_credential_access(request, CredentialKind.MAILBOX)
|
||||||
)
|
)
|
||||||
@@ -105,7 +111,10 @@ def redeem_roundcube(request):
|
|||||||
"mailbox__mail_domain__account",
|
"mailbox__mail_domain__account",
|
||||||
"mailbox__provisioning",
|
"mailbox__provisioning",
|
||||||
)
|
)
|
||||||
if grant is None or not actor_can_open_webmail(grant.actor, grant.mailbox):
|
if grant is None:
|
||||||
|
raise Http404
|
||||||
|
actor = signon_actor(grant, grant.actor)
|
||||||
|
if actor is None or not actor_can_open_webmail(actor, grant.mailbox):
|
||||||
raise Http404
|
raise Http404
|
||||||
mailbox = grant.mailbox
|
mailbox = grant.mailbox
|
||||||
spec = mailbox.spec
|
spec = mailbox.spec
|
||||||
@@ -136,7 +145,9 @@ def redeem_roundcube(request):
|
|||||||
.filter(pk=mailbox.pk)
|
.filter(pk=mailbox.pk)
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
actor = get_user_model().objects.filter(pk=grant.actor_id).first()
|
actor = signon_actor(
|
||||||
|
grant, get_user_model().objects.filter(pk=grant.actor_id).first()
|
||||||
|
)
|
||||||
if (
|
if (
|
||||||
current is None
|
current is None
|
||||||
or actor is None
|
or actor is None
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from django.contrib.auth import logout
|
|||||||
from django.contrib.auth.views import LoginView, redirect_to_login
|
from django.contrib.auth.views import LoginView, redirect_to_login
|
||||||
from django.shortcuts import redirect, render
|
from django.shortcuts import redirect, render
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
from django.utils.decorators import method_decorator
|
from django.utils.decorators import method_decorator
|
||||||
from django.views.decorators.cache import never_cache
|
from django.views.decorators.cache import never_cache
|
||||||
from django.views.decorators.debug import (
|
from django.views.decorators.debug import (
|
||||||
@@ -17,6 +18,8 @@ from django_otp.plugins.otp_email.models import EmailDevice
|
|||||||
from qrcode.image.svg import SvgPathFillImage
|
from qrcode.image.svg import SvgPathFillImage
|
||||||
|
|
||||||
from .panel_factors import (
|
from .panel_factors import (
|
||||||
|
CHALLENGE_SECONDS,
|
||||||
|
RECOVERY_SIGN_IN,
|
||||||
SETUP_SESSION,
|
SETUP_SESSION,
|
||||||
begin_enrollment,
|
begin_enrollment,
|
||||||
complete_challenge,
|
complete_challenge,
|
||||||
@@ -33,10 +36,24 @@ from .panel_factors import (
|
|||||||
start_initial_setup,
|
start_initial_setup,
|
||||||
verify_factor,
|
verify_factor,
|
||||||
)
|
)
|
||||||
|
from .panel_sessions import SESSION_VERSION, session_version
|
||||||
from .password_reset import reset_enabled
|
from .password_reset import reset_enabled
|
||||||
from .sign_in_limits import limit_attempt
|
from .sign_in_limits import limit_attempt
|
||||||
|
|
||||||
|
|
||||||
|
@sensitive_variables("configuration_url")
|
||||||
|
def authenticator_setup(device):
|
||||||
|
configuration_url = device.config_url
|
||||||
|
qr = qrcode.make(
|
||||||
|
configuration_url, image_factory=SvgPathFillImage
|
||||||
|
).to_string(encoding="utf-8")
|
||||||
|
return {
|
||||||
|
"setup_key": base64.b32encode(device.bin_key).decode(),
|
||||||
|
"configuration_url": configuration_url,
|
||||||
|
"qr_image": base64.b64encode(qr).decode("ascii"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class PrivilegedFactorMiddleware:
|
class PrivilegedFactorMiddleware:
|
||||||
def __init__(self, get_response):
|
def __init__(self, get_response):
|
||||||
self.get_response = get_response
|
self.get_response = get_response
|
||||||
@@ -88,13 +105,17 @@ class PanelLoginView(LoginView):
|
|||||||
|
|
||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
user = form.get_user()
|
user = form.get_user()
|
||||||
|
current_version = session_version(user)
|
||||||
if not requires_panel_factor(user):
|
if not requires_panel_factor(user):
|
||||||
return super().form_valid(form)
|
response = super().form_valid(form)
|
||||||
|
self.request.session[SESSION_VERSION] = current_version
|
||||||
|
return response
|
||||||
destination = self.get_success_url()
|
destination = self.get_success_url()
|
||||||
if confirmed_device(user) or recovery_required(user):
|
if confirmed_device(user) or recovery_required(user):
|
||||||
start_challenge(self.request, user, destination)
|
start_challenge(self.request, user, destination)
|
||||||
return redirect("panel:factor_verify")
|
return redirect("panel:factor_verify")
|
||||||
super().form_valid(form)
|
super().form_valid(form)
|
||||||
|
self.request.session[SESSION_VERSION] = current_version
|
||||||
start_initial_setup(self.request, destination)
|
start_initial_setup(self.request, destination)
|
||||||
if not email_factor_available(user):
|
if not email_factor_available(user):
|
||||||
device = begin_enrollment(user, "authenticator")
|
device = begin_enrollment(user, "authenticator")
|
||||||
@@ -234,12 +255,19 @@ class VerifyFactorView(FactorView):
|
|||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
if self.current_device() is None:
|
if self.current_device() is None:
|
||||||
return redirect("panel:factor_enroll")
|
return redirect("panel:factor_enroll")
|
||||||
verified = verify_factor(self.user, form.cleaned_data["code"])
|
code = form.cleaned_data["code"]
|
||||||
|
verified = verify_factor(self.user, code)
|
||||||
if verified is None:
|
if verified is None:
|
||||||
return self.rejected(
|
return self.rejected(
|
||||||
form, "Invalid or unavailable code. Try again."
|
form, "Invalid or unavailable code. Try again."
|
||||||
)
|
)
|
||||||
return redirect(complete_challenge(self.request, self.user, verified))
|
destination = complete_challenge(self.request, self.user, verified)
|
||||||
|
if len(code) == 20:
|
||||||
|
self.request.session[RECOVERY_SIGN_IN] = {
|
||||||
|
"device": verified.persistent_id,
|
||||||
|
"expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS,
|
||||||
|
}
|
||||||
|
return redirect(destination)
|
||||||
|
|
||||||
|
|
||||||
class EnrollFactorView(FactorView):
|
class EnrollFactorView(FactorView):
|
||||||
@@ -309,15 +337,7 @@ class ConfirmFactorView(FactorView):
|
|||||||
if isinstance(device, EmailDevice):
|
if isinstance(device, EmailDevice):
|
||||||
context["email_factor"] = True
|
context["email_factor"] = True
|
||||||
elif device:
|
elif device:
|
||||||
configuration_url = device.config_url
|
context = authenticator_setup(device)
|
||||||
qr = qrcode.make(
|
|
||||||
configuration_url, image_factory=SvgPathFillImage
|
|
||||||
).to_string(encoding="utf-8")
|
|
||||||
context = {
|
|
||||||
"setup_key": base64.b32encode(device.bin_key).decode(),
|
|
||||||
"configuration_url": configuration_url,
|
|
||||||
"qr_image": base64.b64encode(qr).decode("ascii"),
|
|
||||||
}
|
|
||||||
return super().get_context_data(**context, **kwargs)
|
return super().get_context_data(**context, **kwargs)
|
||||||
|
|
||||||
@sensitive_variables("codes")
|
@sensitive_variables("codes")
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ from django.http import Http404
|
|||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django.views.decorators.debug import sensitive_variables
|
from django.views.decorators.debug import sensitive_variables
|
||||||
|
|
||||||
|
from .panel_roles import assigned_roles, scoped_user
|
||||||
|
|
||||||
GRANT_LIFETIME = timedelta(seconds=45)
|
GRANT_LIFETIME = timedelta(seconds=45)
|
||||||
TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}")
|
TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}")
|
||||||
|
|
||||||
@@ -18,15 +20,28 @@ def issue_signon_grant(model, actor, **selection):
|
|||||||
now = timezone.now()
|
now = timezone.now()
|
||||||
model.objects.filter(expires_at__lte=now).delete()
|
model.objects.filter(expires_at__lte=now).delete()
|
||||||
token = secrets.token_urlsafe(32)
|
token = secrets.token_urlsafe(32)
|
||||||
|
roles = assigned_roles(actor)
|
||||||
|
role = getattr(actor, "panel_role", None) or next(iter(roles), None)
|
||||||
|
scope = [role, roles.get(role)] if role else []
|
||||||
model.objects.create(
|
model.objects.create(
|
||||||
token_digest=token_digest(token),
|
token_digest=token_digest(token),
|
||||||
actor=actor,
|
actor=actor,
|
||||||
|
actor_scope=scope,
|
||||||
expires_at=now + GRANT_LIFETIME,
|
expires_at=now + GRANT_LIFETIME,
|
||||||
**selection,
|
**selection,
|
||||||
)
|
)
|
||||||
return token
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def signon_actor(grant, actor):
|
||||||
|
if actor is None or not grant.actor_scope:
|
||||||
|
return actor
|
||||||
|
role, assignment = grant.actor_scope
|
||||||
|
if assignment is None or assigned_roles(actor).get(role) != assignment:
|
||||||
|
return None
|
||||||
|
return scoped_user(actor, role)
|
||||||
|
|
||||||
|
|
||||||
@sensitive_variables()
|
@sensitive_variables()
|
||||||
def token_digest(token):
|
def token_digest(token):
|
||||||
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||||
|
|||||||
@@ -326,6 +326,27 @@ button, input, select, textarea {
|
|||||||
font-weight: 650;
|
font-weight: 650;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.sidebar-account a {
|
||||||
|
color: inherit;
|
||||||
|
text-underline-offset: 0.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-role-switch {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.3rem;
|
||||||
|
margin: 0.6rem 0;
|
||||||
|
font-size: 0.82rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-role-switch select {
|
||||||
|
width: 100%;
|
||||||
|
background: var(--sidebar-active);
|
||||||
|
color: var(--sidebar-text);
|
||||||
|
border: 1px solid var(--sidebar-control-line);
|
||||||
|
border-radius: 0.35rem;
|
||||||
|
padding: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
.sidebar-account button {
|
.sidebar-account button {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
border: 0;
|
border: 0;
|
||||||
@@ -447,6 +468,55 @@ h2 {
|
|||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.update-release {
|
||||||
|
padding: 0.75rem 0.9rem;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.update-release > summary {
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 680;
|
||||||
|
}
|
||||||
|
|
||||||
|
.release-notes {
|
||||||
|
max-width: 80ch;
|
||||||
|
margin-top: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.release-notes :is(h1, h2, h3, h4, h5, h6) {
|
||||||
|
margin: 1rem 0 0.25rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.release-notes :is(p, ul, ol, pre, blockquote) {
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.release-notes :is(ul, ol) {
|
||||||
|
padding-inline-start: 1.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.release-notes pre {
|
||||||
|
padding: 0.7rem 0.85rem;
|
||||||
|
border-radius: 0.4rem;
|
||||||
|
background: var(--code-bg);
|
||||||
|
color: var(--code-text);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.update-release-form {
|
||||||
|
margin-top: 0.9rem;
|
||||||
|
padding-top: 0.85rem;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.update-release-form .button {
|
||||||
|
justify-self: start;
|
||||||
|
}
|
||||||
|
|
||||||
.account-toolbar {
|
.account-toolbar {
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
</p>
|
</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% if not account_backup_pending %}
|
{% if can_request_account_backup and not account_backup_pending %}
|
||||||
<form class="form-actions" method="post" action="{% url 'panel:account_backup_create' account.pk %}">
|
<form class="form-actions" method="post" action="{% url 'panel:account_backup_create' account.pk %}">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
{% if account_backup_allow_mail %}
|
{% if account_backup_allow_mail %}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
{% extends "hosting/base.html" %}
|
||||||
|
{% block title %}My account · Coulobre Panel{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<header class="page-heading"><h1>My account</h1></header>
|
||||||
|
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||||
|
<section class="surface" aria-labelledby="account-sign-in">
|
||||||
|
<header class="section-heading"><h2 id="account-sign-in">Sign-in and security</h2></header>
|
||||||
|
<dl class="section-text">
|
||||||
|
<dt>Username</dt><dd>{{ request.user.get_username }}</dd>
|
||||||
|
<dt>Email address</dt><dd>{{ request.user.email|default:"No email address" }}</dd>
|
||||||
|
<dt>Two-factor authentication</dt><dd>{{ factor }}</dd>
|
||||||
|
</dl>
|
||||||
|
{% if not email_available %}<p class="section-text muted">Email changes require configured panel email delivery.</p>{% endif %}
|
||||||
|
<div class="section-text form-actions">
|
||||||
|
<a class="button secondary" href="{% url 'panel:account_password' %}">Change password</a>
|
||||||
|
{% if email_available %}<a class="button secondary" href="{% url 'panel:account_email' %}">Change email address</a>{% endif %}
|
||||||
|
<a class="button secondary" href="{% url 'panel:account_authenticator' %}">{% if factor_enabled %}Change{% else %}Set up{% endif %} authenticator app</a>
|
||||||
|
{% if factor_enabled %}<a class="button secondary" href="{% url 'panel:account_recovery_codes' %}">Generate recovery codes</a>{% endif %}
|
||||||
|
<a class="button secondary" href="{% url 'panel:account_other_sessions' %}">Sign out other sessions</a>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% if events %}
|
||||||
|
<section class="surface" aria-labelledby="security-activity">
|
||||||
|
<header class="section-heading"><h2 id="security-activity">Recent security activity</h2></header>
|
||||||
|
<div class="table-scroll">
|
||||||
|
<table>
|
||||||
|
<thead><tr><th scope="col">Action</th><th scope="col">Time (UTC)</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for event in events %}<tr><td>{{ event.get_action_display }}</td><td>{{ event.created_at|date:"j M Y, H:i" }}</td></tr>{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{% extends "hosting/base.html" %}
|
||||||
|
{% block title %}{{ heading }} · Coulobre Panel{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<a class="back-link" href="{% url 'panel:account_security' %}">← My account</a>
|
||||||
|
<header class="page-heading"><h1>{{ heading }}</h1></header>
|
||||||
|
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||||
|
<section class="surface editor-surface">
|
||||||
|
{% if instructions %}<p>{{ instructions }}</p>{% endif %}
|
||||||
|
{% include "hosting/authenticator_setup.html" %}
|
||||||
|
<form method="post" class="editor">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form.as_div }}
|
||||||
|
<div class="form-actions">
|
||||||
|
<button class="button primary" type="submit">Continue</button>
|
||||||
|
{% if can_send_code %}
|
||||||
|
<button class="button secondary" type="submit" name="send_code" value="1" formnovalidate>Send email code</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{% extends "hosting/base.html" %}
|
||||||
|
{% block title %}Assign panel role · Coulobre Panel{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<header class="page-heading"><h1>Assign a role to an existing login</h1></header>
|
||||||
|
<div class="surface editor-surface">
|
||||||
|
<form class="editor" method="post">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form.as_div }}
|
||||||
|
<div class="form-actions">
|
||||||
|
<button class="button primary" type="submit">Assign role</button>
|
||||||
|
<a class="button secondary" href="{% url 'panel:accounts' %}">Cancel</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -1,23 +1,7 @@
|
|||||||
{% load static %}
|
|
||||||
<h1>{{ heading }}</h1>
|
<h1>{{ heading }}</h1>
|
||||||
{% if instructions %}<p>{{ instructions }}</p>{% endif %}
|
{% if instructions %}<p>{{ instructions }}</p>{% endif %}
|
||||||
{% if code_notice %}<p role="status">{{ code_notice }}</p>{% endif %}
|
{% if code_notice %}<p role="status">{{ code_notice }}</p>{% endif %}
|
||||||
{% if configuration_url %}
|
{% include "hosting/authenticator_setup.html" %}
|
||||||
<div class="authenticator-setup">
|
|
||||||
<p>Scan this QR code with your authenticator app.</p>
|
|
||||||
<img class="authenticator-qr" src="data:image/svg+xml;base64,{{ qr_image }}" width="192" height="192" alt="Authenticator setup QR code">
|
|
||||||
<p><a href="{{ configuration_url }}" rel="noreferrer">Open in an authenticator app</a></p>
|
|
||||||
<details>
|
|
||||||
<summary>Enter the setup key manually</summary>
|
|
||||||
<div class="form-actions">
|
|
||||||
<input id="setup-key" type="text" readonly autocomplete="off" spellcheck="false" aria-label="Setup key" value="{{ setup_key }}" data-secret>
|
|
||||||
<button class="button secondary" type="button" hidden data-copy-field="setup-key">Copy setup key</button>
|
|
||||||
</div>
|
|
||||||
<p id="copy-field-status" role="status"></p>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
<script src="{% static 'hosting/copy-field.js' %}" defer></script>
|
|
||||||
{% endif %}
|
|
||||||
{% if form %}
|
{% if form %}
|
||||||
<form method="post" class="editor">
|
<form method="post" class="editor">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{% load static %}
|
||||||
|
{% if configuration_url %}
|
||||||
|
<div class="authenticator-setup">
|
||||||
|
<p>Scan this QR code with your authenticator app.</p>
|
||||||
|
<img class="authenticator-qr" src="data:image/svg+xml;base64,{{ qr_image }}" width="192" height="192" alt="Authenticator setup QR code">
|
||||||
|
<p><a href="{{ configuration_url }}" rel="noreferrer">Open in an authenticator app</a></p>
|
||||||
|
<details>
|
||||||
|
<summary>Enter the setup key manually</summary>
|
||||||
|
<div class="form-actions">
|
||||||
|
<input id="setup-key" type="text" readonly autocomplete="off" spellcheck="false" aria-label="Setup key" value="{{ setup_key }}" data-secret>
|
||||||
|
<button class="button secondary" type="button" hidden data-copy-field="setup-key">Copy setup key</button>
|
||||||
|
</div>
|
||||||
|
<p id="copy-field-status" role="status"></p>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
<script src="{% static 'hosting/copy-field.js' %}" defer></script>
|
||||||
|
{% endif %}
|
||||||
@@ -86,7 +86,23 @@
|
|||||||
{% endwith %}
|
{% endwith %}
|
||||||
</nav>
|
</nav>
|
||||||
<div class="sidebar-account">
|
<div class="sidebar-account">
|
||||||
<span class="operator">{{ request.user.get_username }}</span>
|
{% if request.impersonation %}
|
||||||
|
<span class="operator">{{ request.user.get_username }}</span>
|
||||||
|
{% else %}
|
||||||
|
<a class="operator" href="{% url 'panel:account_security' %}" aria-label="My account for {{ request.user.get_username }}">{{ request.user.get_username }}</a>
|
||||||
|
{% if request.panel_role_options|length > 1 %}
|
||||||
|
<form method="post" class="panel-role-switch" action="{% url 'panel:switch_panel_role' %}">
|
||||||
|
{% csrf_token %}
|
||||||
|
<label for="panel-role">Panel role</label>
|
||||||
|
<select name="role" id="panel-role">
|
||||||
|
{% for value, label in request.panel_role_options %}
|
||||||
|
<option value="{{ value }}"{% if request.active_panel_role == value %} selected{% endif %}>{{ label }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
<button type="submit">Switch role</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
<form method="post" action="{% url 'panel:logout' %}">
|
<form method="post" action="{% url 'panel:logout' %}">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<button type="submit">Sign out</button>
|
<button type="submit">Sign out</button>
|
||||||
|
|||||||
@@ -7,7 +7,12 @@
|
|||||||
<p class="heading-meta">Manage the logins people use to access their assigned hosting.</p>
|
<p class="heading-meta">Manage the logins people use to access their assigned hosting.</p>
|
||||||
</div>
|
</div>
|
||||||
{% if is_operator and perms.hosting.add_customer %}
|
{% if is_operator and perms.hosting.add_customer %}
|
||||||
<a class="button primary" href="{% url 'panel:customer_create' %}">Add customer login</a>
|
<div class="form-actions">
|
||||||
|
{% if request.user.is_superuser and request.user.is_verified %}
|
||||||
|
<a class="button secondary" href="{% url 'panel:assign_panel_role' %}?role=customer">Assign to existing login</a>
|
||||||
|
{% endif %}
|
||||||
|
<a class="button primary" href="{% url 'panel:customer_create' %}">Add customer login</a>
|
||||||
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</header>
|
</header>
|
||||||
<section class="surface" aria-label="Customer list">
|
<section class="surface" aria-label="Customer list">
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
{% extends "hosting/base.html" %}
|
||||||
|
{% block title %}Configure features · Coulobre Panel{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<a class="back-link" href="{% url 'panel:installation' %}">← About Coulobre</a>
|
||||||
|
<header class="page-heading"><h1>Configure features</h1></header>
|
||||||
|
<div class="surface editor-surface">
|
||||||
|
<p>Choose which configured features the panel can use for new requests. Existing sites, mailboxes, scheduled tasks and backups keep running.</p>
|
||||||
|
<form class="editor" method="post">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form.non_field_errors }}
|
||||||
|
{{ form.revision }}
|
||||||
|
{% for field in form.visible_fields %}
|
||||||
|
<div>
|
||||||
|
<label for="{{ field.id_for_label }}">{{ field }} {{ field.label }}</label>
|
||||||
|
{{ field.errors }}
|
||||||
|
<p class="heading-meta" id="{{ field.id_for_label }}_helptext">{{ field.help_text }}</p>
|
||||||
|
</div>
|
||||||
|
{% empty %}
|
||||||
|
<p>No installed features can be configured here yet.</p>
|
||||||
|
{% endfor %}
|
||||||
|
<div class="form-actions">
|
||||||
|
{% if form.visible_fields %}<button class="button primary" type="submit">Save configuration</button>{% endif %}
|
||||||
|
<a class="button secondary" href="{% url 'panel:installation' %}">Cancel</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<header class="page-heading"><h1>About Coulobre</h1></header>
|
<header class="page-heading"><h1>About Coulobre</h1></header>
|
||||||
|
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||||
<section class="surface" aria-labelledby="installation-heading">
|
<section class="surface" aria-labelledby="installation-heading">
|
||||||
<header class="section-heading"><h2 id="installation-heading">Installation</h2></header>
|
<header class="section-heading"><h2 id="installation-heading">Installation</h2></header>
|
||||||
<dl class="details">
|
<dl class="details">
|
||||||
@@ -17,22 +18,28 @@
|
|||||||
<h2 id="features-heading">Feature configuration</h2>
|
<h2 id="features-heading">Feature configuration</h2>
|
||||||
<p class="muted">See <a href="{% url 'panel:service_health' %}">Service health</a> for the latest local and remote checks.</p>
|
<p class="muted">See <a href="{% url 'panel:service_health' %}">Service health</a> for the latest local and remote checks.</p>
|
||||||
</div>
|
</div>
|
||||||
|
{% if request.user.is_superuser and request.user.is_verified %}
|
||||||
|
<a class="button secondary" href="{% url 'panel:feature_configuration' %}">Configure features</a>
|
||||||
|
{% endif %}
|
||||||
</header>
|
</header>
|
||||||
<div class="table-scroll">
|
<div class="table-scroll">
|
||||||
<table>
|
<table>
|
||||||
<thead><tr><th scope="col">Feature</th><th scope="col">Configuration</th></tr></thead>
|
<thead><tr><th scope="col">Feature</th><th scope="col">Configuration</th><th scope="col">Prerequisites</th></tr></thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for name, enabled in features %}
|
{% for feature, configured, enabled in features %}
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="row">{{ name }}</th>
|
<th scope="row">{{ feature.label }}</th>
|
||||||
<td>
|
<td>
|
||||||
<div class="table-actions">
|
<div class="table-actions">
|
||||||
{% if enabled %}<span class="status active">Enabled</span>{% else %}<span>Disabled</span>{% endif %}
|
{% if enabled %}<span class="status active">Enabled</span>{% elif configured %}<span>Paused in panel</span>{% else %}<span>Requires setup</span>{% endif %}
|
||||||
{% if request.user.is_superuser and name == 'Default managed DNS zones for new accounts' %}
|
{% if enabled and not feature.socket_ready %}<span class="muted">Service socket unavailable</span>{% endif %}
|
||||||
|
{% if configured and feature.role %}<span>{% if feature.linked %}Linked receiver{% else %}Local{% endif %}</span>{% endif %}
|
||||||
|
{% if request.user.is_superuser and feature.setting == 'DEFAULT_DNS_ZONES' %}
|
||||||
<a class="record-link" href="{% url 'panel:dns_defaults' %}">Configure DNS defaults</a>
|
<a class="record-link" href="{% url 'panel:dns_defaults' %}">Configure DNS defaults</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
|
<td>{{ feature.prerequisite }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
@@ -8,6 +8,9 @@
|
|||||||
<a class="button secondary" href="{% url 'panel:reseller_profiles' %}">Profiles</a>
|
<a class="button secondary" href="{% url 'panel:reseller_profiles' %}">Profiles</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if perms.hosting.add_reseller %}
|
{% if perms.hosting.add_reseller %}
|
||||||
|
{% if request.user.is_superuser and request.user.is_verified %}
|
||||||
|
<a class="button secondary" href="{% url 'panel:assign_panel_role' %}?role=manager">Assign to existing login</a>
|
||||||
|
{% endif %}
|
||||||
<a class="button primary" href="{% url 'panel:reseller_create' %}">Add customer manager</a>
|
<a class="button primary" href="{% url 'panel:reseller_create' %}">Add customer manager</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
{% extends "hosting/base.html" %}
|
{% extends "hosting/base.html" %}
|
||||||
|
{% load release_notes %}
|
||||||
{% block title %}Updates · Coulobre Panel{% endblock %}
|
{% block title %}Updates · Coulobre Panel{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<header class="page-heading">
|
<header class="page-heading">
|
||||||
<div><h1>Updates</h1><p class="heading-meta">Installed version {{ installed_version|default:"unknown" }}</p></div>
|
<div><h1>Updates</h1><p class="heading-meta">Installed version {{ installed_version|default:"unknown" }}</p></div>
|
||||||
<a class="button secondary" href="{% url 'panel:updates' %}">Refresh status</a>
|
<a class="button secondary" href="{% url 'panel:updates' %}?refresh=1">Refresh status</a>
|
||||||
</header>
|
</header>
|
||||||
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||||
{% if form.errors %}<div class="notice">{{ form.errors }}</div>{% endif %}
|
{% if form.errors %}<div class="notice">{{ form.errors }}</div>{% endif %}
|
||||||
@@ -18,18 +19,39 @@
|
|||||||
</section>
|
</section>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% if not updater_enabled %}
|
{% if not updater_enabled %}
|
||||||
<section class="surface"><p class="empty">Enable the local updater socket on an installer-managed single server to use web updates.</p></section>
|
<section class="surface"><p class="empty">Enable the local updater socket on an installer-managed panel to use web updates.</p></section>
|
||||||
{% elif catalog_problem %}
|
{% elif catalog_problem %}
|
||||||
<section class="surface"><p class="empty">{{ catalog_problem }}</p></section>
|
<section class="surface"><p class="empty">{{ catalog_problem }}</p></section>
|
||||||
{% else %}
|
{% else %}
|
||||||
|
{% if preflight_problem %}
|
||||||
|
<section class="surface"><p class="empty">{{ preflight_problem }}</p></section>
|
||||||
|
{% endif %}
|
||||||
|
{% if linked_nodes %}
|
||||||
|
<section class="surface" aria-labelledby="linked-updates">
|
||||||
|
<header class="section-heading"><h2 id="linked-updates">Linked receivers</h2></header>
|
||||||
|
<p class="section-text">Account for every panel using a shared receiver. Stage receivers at the target release in maintenance mode, then upgrade the panels. Resume the receivers when all panels are verified.</p>
|
||||||
|
<div class="table-scroll">
|
||||||
|
<table>
|
||||||
|
<thead><tr><th scope="col">Role</th><th scope="col">Host</th><th scope="col">Release</th><th scope="col">Probe protocol</th><th scope="col">Status</th><th scope="col">Staged target</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for node in linked_nodes %}
|
||||||
|
<tr><td>{{ node.role|upper }}</td><td>{{ node.host }}</td><td>{{ node.release|default:"Unknown" }}</td><td>{{ node.protocol|default:"Unknown" }}</td><td>{{ node.state|capfirst }}</td><td>{{ node.upgrade_target|default:"—" }}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
<section class="surface" aria-labelledby="available-updates">
|
<section class="surface" aria-labelledby="available-updates">
|
||||||
<header class="section-heading"><h2 id="available-updates">Compatible releases</h2></header>
|
<header class="section-heading"><h2 id="available-updates">Compatible releases</h2></header>
|
||||||
{% for release in releases %}
|
{% for release in releases %}
|
||||||
<details class="section-text">
|
<details class="section-text update-release">
|
||||||
<summary>{{ release.version }}{% if release.prerelease %} · Prerelease{% endif %}</summary>
|
<summary>{{ release.version }}{% if release.prerelease %} · Prerelease{% endif %}</summary>
|
||||||
{{ release.notes|linebreaks }}
|
{% if release.notes %}
|
||||||
{% if may_apply and update_status.state != "running" and update_status.state != "recovery_required" %}
|
<div class="release-notes">{{ release.notes|release_notes_html }}</div>
|
||||||
<form method="post" class="editor">
|
{% endif %}
|
||||||
|
{% if may_apply and release.version in applyable_versions and update_status.state != "running" and update_status.state != "recovery_required" %}
|
||||||
|
<form method="post" class="editor update-release-form">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<input type="hidden" name="version" value="{{ release.version }}">
|
<input type="hidden" name="version" value="{{ release.version }}">
|
||||||
<input type="hidden" name="sha256" value="{{ release.sha256 }}">
|
<input type="hidden" name="sha256" value="{{ release.sha256 }}">
|
||||||
@@ -37,6 +59,8 @@
|
|||||||
<p class="heading-meta">The panel goes offline while the updater creates a recovery backup and installs the release.</p>
|
<p class="heading-meta">The panel goes offline while the updater creates a recovery backup and installs the release.</p>
|
||||||
<button class="button primary" type="submit">Install {{ release.version }}</button>
|
<button class="button primary" type="submit">Install {{ release.version }}</button>
|
||||||
</form>
|
</form>
|
||||||
|
{% elif linked_nodes and release.version not in applyable_versions %}
|
||||||
|
<p>Stage all linked receivers for this release before installing it.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</details>
|
</details>
|
||||||
{% empty %}
|
{% empty %}
|
||||||
|
|||||||
Whitespace-only changes.
@@ -0,0 +1,29 @@
|
|||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
from django import template
|
||||||
|
from django.utils.safestring import mark_safe
|
||||||
|
from markdown_it import MarkdownIt
|
||||||
|
|
||||||
|
register = template.Library()
|
||||||
|
|
||||||
|
|
||||||
|
class ReleaseNotesMarkdown(MarkdownIt):
|
||||||
|
def validateLink(self, url): # noqa: N802 - markdown-it-py hook
|
||||||
|
try:
|
||||||
|
link = urlsplit(url)
|
||||||
|
return (
|
||||||
|
link.scheme in {"https", "http"}
|
||||||
|
and bool(link.hostname)
|
||||||
|
and link.username is None
|
||||||
|
and link.password is None
|
||||||
|
)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
markdown = ReleaseNotesMarkdown("js-default").disable("image")
|
||||||
|
|
||||||
|
|
||||||
|
@register.filter
|
||||||
|
def release_notes_html(notes):
|
||||||
|
return mark_safe(markdown.render(notes))
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
import re
|
||||||
|
from datetime import timedelta
|
||||||
|
from secrets import token_urlsafe
|
||||||
|
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.core import mail
|
||||||
|
from django.test import Client, TestCase, override_settings
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
|
from django_otp.oath import totp
|
||||||
|
from django_otp.plugins.otp_email.models import EmailDevice
|
||||||
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
|
||||||
|
from .impersonation import SESSION_DURATION, SESSION_KEY
|
||||||
|
from .models import (
|
||||||
|
Customer,
|
||||||
|
CustomerImpersonation,
|
||||||
|
PanelEmailChange,
|
||||||
|
PanelRecoveryCode,
|
||||||
|
PanelSecurityEvent,
|
||||||
|
)
|
||||||
|
from .panel_factors import DEVICE_NAME, secret_digest
|
||||||
|
|
||||||
|
PASSWORD = token_urlsafe(24)
|
||||||
|
NEW_PASSWORD = token_urlsafe(24)
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(
|
||||||
|
EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
|
||||||
|
EMAIL_HOST="mail.example.test",
|
||||||
|
REQUIRE_PRIVILEGED_MFA=False,
|
||||||
|
)
|
||||||
|
class AccountSecurityTests(TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpTestData(cls):
|
||||||
|
cls.user = get_user_model().objects.create_user(
|
||||||
|
"customer", email="old@example.test", password=PASSWORD
|
||||||
|
)
|
||||||
|
cls.customer = Customer.objects.create(user=cls.user)
|
||||||
|
cls.operator = get_user_model().objects.create_superuser(
|
||||||
|
"operator", password=PASSWORD
|
||||||
|
)
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.profile = reverse("panel:account_security")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
|
def authorize_factor(self, device):
|
||||||
|
session = self.client.session
|
||||||
|
session["otp_device_id"] = device.persistent_id
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
def test_profile_is_private_and_reachable_for_both_roles(self):
|
||||||
|
response = self.client.get(self.profile)
|
||||||
|
self.assertContains(response, "old@example.test")
|
||||||
|
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||||
|
operator = Client()
|
||||||
|
operator.force_login(self.operator)
|
||||||
|
self.assertContains(operator.get(self.profile), "My account")
|
||||||
|
self.assertRedirects(
|
||||||
|
Client().get(self.profile),
|
||||||
|
f"{reverse('panel:login')}?next={self.profile}",
|
||||||
|
fetch_redirect_response=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_password_change_keeps_current_session_and_revokes_others(self):
|
||||||
|
other = Client()
|
||||||
|
other.force_login(self.user)
|
||||||
|
path = reverse("panel:account_password")
|
||||||
|
data = {
|
||||||
|
"password": PASSWORD,
|
||||||
|
"new_password": NEW_PASSWORD,
|
||||||
|
"confirm_password": NEW_PASSWORD,
|
||||||
|
}
|
||||||
|
self.assertRedirects(self.client.post(path, data), self.profile)
|
||||||
|
self.user.refresh_from_db()
|
||||||
|
self.assertTrue(self.user.check_password(NEW_PASSWORD))
|
||||||
|
self.assertEqual(other.get(self.profile).status_code, 302)
|
||||||
|
self.assertContains(self.client.get(self.profile), "Password changed")
|
||||||
|
event = PanelSecurityEvent.objects.get(user=self.user)
|
||||||
|
self.assertEqual(event.action, PanelSecurityEvent.Action.PASSWORD)
|
||||||
|
|
||||||
|
def test_other_session_sign_out_checks_credentials_and_csrf(self):
|
||||||
|
other = Client()
|
||||||
|
other.force_login(self.user)
|
||||||
|
path = reverse("panel:account_other_sessions")
|
||||||
|
self.assertContains(
|
||||||
|
self.client.post(path, {"password": "incorrect"}),
|
||||||
|
"The current password is incorrect.",
|
||||||
|
)
|
||||||
|
self.assertEqual(other.get(self.profile).status_code, 200)
|
||||||
|
browser = Client(enforce_csrf_checks=True)
|
||||||
|
browser.force_login(self.user)
|
||||||
|
self.assertEqual(
|
||||||
|
browser.post(path, {"password": PASSWORD}).status_code, 403
|
||||||
|
)
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(path, {"password": PASSWORD}), self.profile
|
||||||
|
)
|
||||||
|
self.assertEqual(other.get(self.profile).status_code, 302)
|
||||||
|
self.assertEqual(self.client.get(self.profile).status_code, 200)
|
||||||
|
|
||||||
|
def test_email_verification_is_bound_to_requesting_session(self):
|
||||||
|
device = EmailDevice.objects.create(
|
||||||
|
user=self.user,
|
||||||
|
name=DEVICE_NAME,
|
||||||
|
email=self.user.email,
|
||||||
|
token="510280",
|
||||||
|
valid_until=timezone.now() + timedelta(minutes=5),
|
||||||
|
)
|
||||||
|
self.authorize_factor(device)
|
||||||
|
other = Client()
|
||||||
|
other.force_login(self.user)
|
||||||
|
session = other.session
|
||||||
|
session["otp_device_id"] = device.persistent_id
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
start = reverse("panel:account_email")
|
||||||
|
verify = reverse("panel:account_email_verify")
|
||||||
|
response = self.client.post(
|
||||||
|
start,
|
||||||
|
{
|
||||||
|
"password": PASSWORD,
|
||||||
|
"email": "new@example.test",
|
||||||
|
"code": "510280",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertRedirects(response, verify)
|
||||||
|
self.user.refresh_from_db()
|
||||||
|
self.assertEqual(self.user.email, "old@example.test")
|
||||||
|
self.assertEqual(mail.outbox[0].to, ["new@example.test"])
|
||||||
|
code = re.search(r"\b[0-9a-f]{12}\b", mail.outbox[0].body)[0]
|
||||||
|
self.assertNotEqual(PanelEmailChange.objects.get().digest, code)
|
||||||
|
self.assertContains(
|
||||||
|
other.post(verify, {"code": code}), "invalid or expired"
|
||||||
|
)
|
||||||
|
with self.captureOnCommitCallbacks(execute=True):
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(verify, {"code": code}), self.profile
|
||||||
|
)
|
||||||
|
self.user.refresh_from_db()
|
||||||
|
device.refresh_from_db()
|
||||||
|
self.assertEqual(self.user.email, "new@example.test")
|
||||||
|
self.assertEqual(device.email, self.user.email)
|
||||||
|
self.assertIsNone(device.token)
|
||||||
|
self.assertFalse(PanelEmailChange.objects.exists())
|
||||||
|
self.assertEqual(mail.outbox[1].to, ["old@example.test"])
|
||||||
|
self.assertEqual(other.get(self.profile).status_code, 302)
|
||||||
|
|
||||||
|
def test_optional_authenticator_becomes_required_after_enrollment(self):
|
||||||
|
start = reverse("panel:account_authenticator")
|
||||||
|
confirm = reverse("panel:account_authenticator_confirm")
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(start, {"password": PASSWORD}), confirm
|
||||||
|
)
|
||||||
|
device = TOTPDevice.objects.get(user=self.user)
|
||||||
|
token = f"{totp(device.bin_key):06d}"
|
||||||
|
self.assertContains(
|
||||||
|
self.client.post(confirm, {"code": token}),
|
||||||
|
"Save your recovery codes",
|
||||||
|
)
|
||||||
|
device.refresh_from_db()
|
||||||
|
self.assertTrue(device.confirmed)
|
||||||
|
self.assertEqual(
|
||||||
|
PanelRecoveryCode.objects.filter(user=self.user).count(), 10
|
||||||
|
)
|
||||||
|
|
||||||
|
fresh = Client()
|
||||||
|
self.assertRedirects(
|
||||||
|
fresh.post(
|
||||||
|
reverse("panel:login"),
|
||||||
|
{"username": "customer", "password": PASSWORD},
|
||||||
|
),
|
||||||
|
reverse("panel:factor_verify"),
|
||||||
|
)
|
||||||
|
self.assertNotIn("_auth_user_id", fresh.session)
|
||||||
|
|
||||||
|
def test_last_recovery_code_can_authorize_authenticator_replacement(self):
|
||||||
|
original = TOTPDevice.objects.create(user=self.user, name=DEVICE_NAME)
|
||||||
|
code = "b" * 20
|
||||||
|
PanelRecoveryCode.objects.create(
|
||||||
|
user=self.user, digest=secret_digest("recovery", code)
|
||||||
|
)
|
||||||
|
self.client.logout()
|
||||||
|
self.client.post(
|
||||||
|
reverse("panel:login"),
|
||||||
|
{"username": "customer", "password": PASSWORD},
|
||||||
|
)
|
||||||
|
self.client.post(reverse("panel:factor_verify"), {"code": code})
|
||||||
|
self.assertFalse(
|
||||||
|
PanelRecoveryCode.objects.filter(user=self.user).exists()
|
||||||
|
)
|
||||||
|
|
||||||
|
start = reverse("panel:account_authenticator")
|
||||||
|
confirm = reverse("panel:account_authenticator_confirm")
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(start, {"password": PASSWORD}), confirm
|
||||||
|
)
|
||||||
|
self.assertTrue(TOTPDevice.objects.filter(pk=original.pk).exists())
|
||||||
|
pending = TOTPDevice.objects.get(user=self.user, confirmed=False)
|
||||||
|
token = f"{totp(pending.bin_key):06d}"
|
||||||
|
self.assertContains(
|
||||||
|
self.client.post(confirm, {"code": token}),
|
||||||
|
"Save your recovery codes",
|
||||||
|
)
|
||||||
|
self.assertFalse(TOTPDevice.objects.filter(pk=original.pk).exists())
|
||||||
|
self.assertEqual(
|
||||||
|
PanelRecoveryCode.objects.filter(user=self.user).count(), 10
|
||||||
|
)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.profile), "Authenticator updated"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_impersonation_cannot_open_account_settings(self):
|
||||||
|
self.client.force_login(self.operator)
|
||||||
|
started = timezone.now()
|
||||||
|
impersonation = CustomerImpersonation.objects.create(
|
||||||
|
operator=self.operator,
|
||||||
|
customer=self.customer,
|
||||||
|
operator_username=self.operator.username,
|
||||||
|
customer_username=self.user.username,
|
||||||
|
write_enabled=True,
|
||||||
|
started_at=started,
|
||||||
|
expires_at=started + SESSION_DURATION,
|
||||||
|
)
|
||||||
|
session = self.client.session
|
||||||
|
session[SESSION_KEY] = impersonation.pk
|
||||||
|
session.save()
|
||||||
|
self.assertEqual(self.client.get(self.profile).status_code, 403)
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.post(
|
||||||
|
reverse("panel:account_other_sessions"), {"password": PASSWORD}
|
||||||
|
).status_code,
|
||||||
|
403,
|
||||||
|
)
|
||||||
|
self.assertFalse(PanelSecurityEvent.objects.exists())
|
||||||
|
|
||||||
|
def test_new_recovery_codes_invalidate_previous_codes(self):
|
||||||
|
device = TOTPDevice.objects.create(user=self.user, name=DEVICE_NAME)
|
||||||
|
self.authorize_factor(device)
|
||||||
|
previous = PanelRecoveryCode.objects.create(
|
||||||
|
user=self.user, digest=secret_digest("recovery", "b" * 20)
|
||||||
|
)
|
||||||
|
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("panel:account_recovery_codes"),
|
||||||
|
{"password": PASSWORD, "code": f"{totp(device.bin_key):06d}"},
|
||||||
|
)
|
||||||
|
self.assertContains(response, "Save your recovery codes")
|
||||||
|
self.assertFalse(
|
||||||
|
PanelRecoveryCode.objects.filter(pk=previous.pk).exists()
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
PanelRecoveryCode.objects.filter(user=self.user).count(), 10
|
||||||
|
)
|
||||||
|
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
from unittest.mock import PropertyMock, patch
|
||||||
|
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.test import TestCase, override_settings
|
||||||
|
from django.urls import reverse
|
||||||
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
|
||||||
|
from .models import AccountBackupJob, HostingAccount, PanelFeaturePolicy
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_DNS_PUBLISHING=True)
|
||||||
|
class FeatureConfigurationTests(TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpTestData(cls):
|
||||||
|
cls.operator = get_user_model().objects.create_superuser("operator")
|
||||||
|
cls.device = TOTPDevice.objects.create(user=cls.operator, name="Panel")
|
||||||
|
cls.account = HostingAccount.objects.create(
|
||||||
|
name="Existing account", primary_domain="site.example"
|
||||||
|
)
|
||||||
|
|
||||||
|
def sign_in(self, *, verified=True):
|
||||||
|
self.client.force_login(self.operator)
|
||||||
|
if verified:
|
||||||
|
session = self.client.session
|
||||||
|
session["otp_device_id"] = self.device.persistent_id
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
def save(self, **data):
|
||||||
|
return self.client.post(reverse("panel:feature_configuration"), data)
|
||||||
|
|
||||||
|
def test_paused_backup_option_blocks_new_jobs_but_archives_stay_visible(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
self.sign_in()
|
||||||
|
result = self.save(revision=0, LOCAL_DNS_PUBLISHING="on")
|
||||||
|
self.assertRedirects(result, reverse("panel:installation"))
|
||||||
|
self.assertEqual(
|
||||||
|
PanelFeaturePolicy.objects.get().disabled,
|
||||||
|
["LOCAL_ACCOUNT_BACKUPS"],
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.post(
|
||||||
|
reverse("panel:account_backup_create", args=[self.account.pk])
|
||||||
|
).status_code,
|
||||||
|
404,
|
||||||
|
)
|
||||||
|
self.assertFalse(AccountBackupJob.objects.exists())
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.get(
|
||||||
|
reverse(
|
||||||
|
"panel:account_backup_archives", args=[self.account.pk]
|
||||||
|
)
|
||||||
|
).status_code,
|
||||||
|
200,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_preflight_preserves_all_choices_and_revision(self):
|
||||||
|
self.sign_in()
|
||||||
|
policy = PanelFeaturePolicy.objects.create(
|
||||||
|
pk=1, disabled=["LOCAL_DNS_PUBLISHING"], revision=2
|
||||||
|
)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.installation_features.Feature.socket_ready",
|
||||||
|
new_callable=PropertyMock,
|
||||||
|
return_value=False,
|
||||||
|
):
|
||||||
|
response = self.save(revision=2, LOCAL_DNS_PUBLISHING="on")
|
||||||
|
self.assertContains(
|
||||||
|
response, "Start the configured service before enabling"
|
||||||
|
)
|
||||||
|
policy.refresh_from_db()
|
||||||
|
self.assertEqual(policy.disabled, ["LOCAL_DNS_PUBLISHING"])
|
||||||
|
self.assertEqual(policy.revision, 2)
|
||||||
|
self.assertEqual(self.save(revision=1).status_code, 409)
|
||||||
|
|
||||||
|
def test_linked_receiver_must_match_panel_release_before_enabling(self):
|
||||||
|
self.sign_in()
|
||||||
|
policy = PanelFeaturePolicy.objects.create(
|
||||||
|
pk=1, disabled=["LOCAL_DNS_PUBLISHING"]
|
||||||
|
)
|
||||||
|
module = "coulobre.hosting.installation_features.Feature"
|
||||||
|
update = "coulobre.hosting.installation_views"
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
f"{module}.linked",
|
||||||
|
new_callable=PropertyMock,
|
||||||
|
return_value=True,
|
||||||
|
),
|
||||||
|
patch(
|
||||||
|
f"{module}.socket_ready",
|
||||||
|
new_callable=PropertyMock,
|
||||||
|
return_value=True,
|
||||||
|
),
|
||||||
|
patch(f"{update}.version", return_value="1.0.0"),
|
||||||
|
patch(
|
||||||
|
f"{update}.inspect_linked_nodes",
|
||||||
|
return_value={
|
||||||
|
"nodes": [
|
||||||
|
{
|
||||||
|
"role": "dns",
|
||||||
|
"release": "0.9.0",
|
||||||
|
"state": "configured",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
) as linked,
|
||||||
|
):
|
||||||
|
response = self.save(
|
||||||
|
revision=0,
|
||||||
|
LOCAL_DNS_PUBLISHING="on",
|
||||||
|
LOCAL_ACCOUNT_BACKUPS="on",
|
||||||
|
)
|
||||||
|
self.assertContains(response, "linked receiver must be ready")
|
||||||
|
linked.return_value["nodes"][0]["release"] = "1.0.0"
|
||||||
|
response = self.save(
|
||||||
|
revision=0,
|
||||||
|
LOCAL_DNS_PUBLISHING="on",
|
||||||
|
LOCAL_ACCOUNT_BACKUPS="on",
|
||||||
|
)
|
||||||
|
self.assertRedirects(response, reverse("panel:installation"))
|
||||||
|
policy.refresh_from_db()
|
||||||
|
self.assertEqual(policy.disabled, [])
|
||||||
|
self.assertEqual(policy.revision, 1)
|
||||||
|
|
||||||
|
@override_settings(LOCAL_WEB_HTTPS=False)
|
||||||
|
def test_requires_verified_admin_and_never_enables_unconfigured_service(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
self.sign_in(verified=False)
|
||||||
|
response = self.save(revision=0)
|
||||||
|
self.assertEqual(response.status_code, 403)
|
||||||
|
self.sign_in()
|
||||||
|
response = self.save(
|
||||||
|
revision=0,
|
||||||
|
LOCAL_DNS_PUBLISHING="on",
|
||||||
|
LOCAL_ACCOUNT_BACKUPS="on",
|
||||||
|
LOCAL_WEB_HTTPS="on",
|
||||||
|
)
|
||||||
|
self.assertRedirects(response, reverse("panel:installation"))
|
||||||
|
self.assertFalse(PanelFeaturePolicy.objects.exists())
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.test import Client, TestCase
|
||||||
|
from django.urls import reverse
|
||||||
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
|
||||||
|
from .access import PanelRole, customer_for_user
|
||||||
|
from .models import (
|
||||||
|
Customer,
|
||||||
|
HostingAccount,
|
||||||
|
HostingDatabase,
|
||||||
|
PhpMyAdminGrant,
|
||||||
|
Reseller,
|
||||||
|
)
|
||||||
|
from .panel_roles import scoped_user
|
||||||
|
from .signon import consume_signon_grant, issue_signon_grant, signon_actor
|
||||||
|
|
||||||
|
|
||||||
|
class PanelRoleTests(TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpTestData(cls):
|
||||||
|
users = get_user_model().objects
|
||||||
|
cls.admin = users.create_superuser("operator")
|
||||||
|
cls.device = TOTPDevice.objects.create(user=cls.admin, name="Panel")
|
||||||
|
cls.customer = Customer.objects.create(user=cls.admin)
|
||||||
|
cls.manager = Reseller.objects.create(user=cls.admin)
|
||||||
|
cls.private_site = HostingAccount.objects.create(
|
||||||
|
name="Personal",
|
||||||
|
primary_domain="mine.example",
|
||||||
|
customer=cls.customer,
|
||||||
|
)
|
||||||
|
cls.managed_site = HostingAccount.objects.create(
|
||||||
|
name="Managed",
|
||||||
|
primary_domain="managed.example",
|
||||||
|
reseller=cls.manager,
|
||||||
|
)
|
||||||
|
cls.other_site = HostingAccount.objects.create(
|
||||||
|
name="Other", primary_domain="other.example"
|
||||||
|
)
|
||||||
|
|
||||||
|
def sign_in(self, *, verified=True):
|
||||||
|
self.client.force_login(self.admin)
|
||||||
|
if verified:
|
||||||
|
session = self.client.session
|
||||||
|
session["otp_device_id"] = self.device.persistent_id
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
def switch(self, role):
|
||||||
|
return self.client.post(
|
||||||
|
reverse("panel:switch_panel_role"), {"role": role}
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_switch_enforces_assigned_scope_on_lists_and_direct_urls(self):
|
||||||
|
self.sign_in()
|
||||||
|
home = reverse("panel:accounts")
|
||||||
|
response = self.client.get(home)
|
||||||
|
self.assertContains(response, "Server administrator")
|
||||||
|
self.assertContains(response, "other.example")
|
||||||
|
self.assertRedirects(self.switch("manager"), home)
|
||||||
|
response = self.client.get(home)
|
||||||
|
self.assertContains(response, "managed.example")
|
||||||
|
self.assertNotContains(response, "mine.example")
|
||||||
|
self.assertNotContains(response, "other.example")
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.get(reverse("panel:updates")).status_code, 403
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.get(self.private_site.get_absolute_url()).status_code,
|
||||||
|
404,
|
||||||
|
)
|
||||||
|
self.assertRedirects(self.switch("customer"), home)
|
||||||
|
response = self.client.get(home)
|
||||||
|
self.assertContains(response, "mine.example")
|
||||||
|
self.assertNotContains(response, "managed.example")
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.get(self.managed_site.get_absolute_url()).status_code,
|
||||||
|
404,
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.post(
|
||||||
|
reverse("panel:account_edit", args=[self.other_site.pk]), {}
|
||||||
|
).status_code,
|
||||||
|
403,
|
||||||
|
)
|
||||||
|
self.assertRedirects(self.switch("administrator"), home)
|
||||||
|
self.assertContains(self.client.get(home), "other.example")
|
||||||
|
self.admin.refresh_from_db()
|
||||||
|
self.assertTrue(self.admin.is_superuser)
|
||||||
|
|
||||||
|
def test_admin_cannot_be_restored_without_verified_second_factor(self):
|
||||||
|
self.sign_in(verified=False)
|
||||||
|
self.assertEqual(self.switch("customer").status_code, 302)
|
||||||
|
self.assertEqual(self.switch("administrator").status_code, 403)
|
||||||
|
self.assertEqual(self.switch("forged-role").status_code, 403)
|
||||||
|
|
||||||
|
def test_removed_assignment_signs_out_before_processing_request(self):
|
||||||
|
self.sign_in()
|
||||||
|
self.assertEqual(self.switch("manager").status_code, 302)
|
||||||
|
self.managed_site.delete()
|
||||||
|
self.manager.delete()
|
||||||
|
response = self.client.get(reverse("panel:updates"))
|
||||||
|
self.assertRedirects(response, reverse("panel:login"))
|
||||||
|
self.assertNotIn("_auth_user_id", self.client.session)
|
||||||
|
|
||||||
|
def test_assignment_requires_verified_superuser(self):
|
||||||
|
user = get_user_model().objects.create_user("another")
|
||||||
|
url = reverse("panel:assign_panel_role")
|
||||||
|
self.sign_in(verified=False)
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.post(
|
||||||
|
url, {"username": user.username, "role": "customer"}
|
||||||
|
).status_code,
|
||||||
|
403,
|
||||||
|
)
|
||||||
|
self.sign_in()
|
||||||
|
self.assertRedirects(
|
||||||
|
self.client.post(
|
||||||
|
url, {"username": user.username, "role": "customer"}
|
||||||
|
),
|
||||||
|
reverse("panel:customers"),
|
||||||
|
)
|
||||||
|
self.assertTrue(Customer.objects.filter(user=user).exists())
|
||||||
|
|
||||||
|
def test_role_switch_requires_csrf(self):
|
||||||
|
client = Client(enforce_csrf_checks=True)
|
||||||
|
client.force_login(self.admin)
|
||||||
|
response = client.post(
|
||||||
|
reverse("panel:switch_panel_role"), {"role": "manager"}
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 403)
|
||||||
|
|
||||||
|
def test_signon_ticket_keeps_the_scope_under_which_it_was_issued(self):
|
||||||
|
database = HostingDatabase.objects.create(
|
||||||
|
account=self.private_site, suffix="test"
|
||||||
|
)
|
||||||
|
actor = scoped_user(self.admin, PanelRole.CUSTOMER)
|
||||||
|
token = issue_signon_grant(PhpMyAdminGrant, actor, database=database)
|
||||||
|
grant = consume_signon_grant(PhpMyAdminGrant, token)
|
||||||
|
effective = signon_actor(grant, grant.actor)
|
||||||
|
self.assertFalse(effective.is_superuser)
|
||||||
|
self.assertEqual(customer_for_user(effective), self.customer)
|
||||||
|
self.private_site.customer = None
|
||||||
|
self.private_site.save(update_fields=["customer"])
|
||||||
|
self.customer.delete()
|
||||||
|
self.assertIsNone(
|
||||||
|
signon_actor(grant, get_user_model().objects.get(pk=self.admin.pk))
|
||||||
|
)
|
||||||
@@ -171,6 +171,7 @@ class ServiceHealthPanelTests(TestCase):
|
|||||||
HOSTING_PUBLIC_ADDRESSES=("192.0.2.20",),
|
HOSTING_PUBLIC_ADDRESSES=("192.0.2.20",),
|
||||||
ROUNDCUBE_URL="https://webmail.example.net",
|
ROUNDCUBE_URL="https://webmail.example.net",
|
||||||
ROUNDCUBE_BRIDGE_KEY="test-only-bridge-key",
|
ROUNDCUBE_BRIDGE_KEY="test-only-bridge-key",
|
||||||
|
LOCAL_MAILBOX_CREDENTIALS=True,
|
||||||
)
|
)
|
||||||
def test_installation_reports_configuration_to_operators(self):
|
def test_installation_reports_configuration_to_operators(self):
|
||||||
url = reverse("panel:installation")
|
url = reverse("panel:installation")
|
||||||
@@ -190,7 +191,10 @@ class ServiceHealthPanelTests(TestCase):
|
|||||||
self.assertContains(response, "1.2.3")
|
self.assertContains(response, "1.2.3")
|
||||||
self.assertContains(response, "Apache License 2.0")
|
self.assertContains(response, "Apache License 2.0")
|
||||||
self.assertContains(response, reverse("panel:service_health"))
|
self.assertContains(response, reverse("panel:service_health"))
|
||||||
features = dict(response.context["features"])
|
features = {
|
||||||
|
feature.label: enabled
|
||||||
|
for feature, _, enabled in response.context["features"]
|
||||||
|
}
|
||||||
self.assertTrue(features["Default managed DNS zones for new accounts"])
|
self.assertTrue(features["Default managed DNS zones for new accounts"])
|
||||||
self.assertTrue(features["Roundcube sign-in"])
|
self.assertTrue(features["Roundcube sign-in"])
|
||||||
self.assertNotContains(response, "test-only-bridge-key")
|
self.assertNotContains(response, "test-only-bridge-key")
|
||||||
@@ -207,11 +211,11 @@ class ServiceHealthPanelTests(TestCase):
|
|||||||
)
|
)
|
||||||
self.client.force_login(self.admin)
|
self.client.force_login(self.admin)
|
||||||
response = self.client.get(reverse("panel:installation"))
|
response = self.client.get(reverse("panel:installation"))
|
||||||
self.assertTrue(
|
features = {
|
||||||
dict(response.context["features"])[
|
feature.label: enabled
|
||||||
"Default managed DNS zones for new accounts"
|
for feature, _, enabled in response.context["features"]
|
||||||
]
|
}
|
||||||
)
|
self.assertTrue(features["Default managed DNS zones for new accounts"])
|
||||||
self.assertContains(response, "Configure DNS defaults")
|
self.assertContains(response, "Configure DNS defaults")
|
||||||
|
|
||||||
def test_view_marks_missing_and_old_observations_distinctly(self):
|
def test_view_marks_missing_and_old_observations_distinctly(self):
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.core.cache import cache
|
||||||
|
from django.test import TestCase
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from coulobre.release_updates import Release
|
||||||
|
|
||||||
|
|
||||||
|
class UpdateViewTests(TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpTestData(cls):
|
||||||
|
cls.admin = get_user_model().objects.create_superuser("operator")
|
||||||
|
|
||||||
|
def test_catalog_renders_markdown_and_escapes_untrusted_content(self):
|
||||||
|
checksum = "a" * 64
|
||||||
|
notes = f"""## Changes
|
||||||
|
|
||||||
|
- **Upgrade** from the previous release.
|
||||||
|
- Follow the [deployment guide](https://example.test/docs#upgrade).
|
||||||
|
|
||||||
|
```text
|
||||||
|
{checksum} coulobre_panel-0.11.1rc1.tar.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
<script>Should stay visible as text.</script>
|
||||||
|
|
||||||
|
[Unsafe](javascript:invalid) [Local action](/updates/)
|
||||||
|
|
||||||
|

|
||||||
|
"""
|
||||||
|
release = Release("0.11.1rc1", notes, True, checksum)
|
||||||
|
self.client.force_login(self.admin)
|
||||||
|
cache.clear()
|
||||||
|
self.addCleanup(cache.clear)
|
||||||
|
path = "coulobre.hosting.update_views"
|
||||||
|
with (
|
||||||
|
patch(f"{path}.SOCKET", **{"is_socket.return_value": True}),
|
||||||
|
patch(f"{path}.inspect_linked_nodes", return_value={"nodes": []}),
|
||||||
|
patch(f"{path}.available_releases", return_value=[release]),
|
||||||
|
):
|
||||||
|
response = self.client.get(reverse("panel:updates"))
|
||||||
|
|
||||||
|
self.assertContains(response, "<h2>Changes</h2>", html=True)
|
||||||
|
self.assertContains(response, "<strong>Upgrade</strong>", html=True)
|
||||||
|
self.assertContains(response, '<pre><code class="language-text">')
|
||||||
|
self.assertContains(response, f"{checksum} coulobre_panel-")
|
||||||
|
self.assertContains(
|
||||||
|
response, 'href="https://example.test/docs#upgrade"'
|
||||||
|
)
|
||||||
|
self.assertContains(response, "<script>")
|
||||||
|
self.assertNotContains(response, "<script>Should stay")
|
||||||
|
self.assertNotContains(response, 'href="javascript:')
|
||||||
|
self.assertNotContains(response, 'href="/updates/">Local action')
|
||||||
|
self.assertNotContains(response, '<img src="https://example.test/')
|
||||||
@@ -12,7 +12,8 @@ from django.utils.decorators import method_decorator
|
|||||||
from django.views.decorators.cache import never_cache
|
from django.views.decorators.cache import never_cache
|
||||||
from django.views.generic import FormView
|
from django.views.generic import FormView
|
||||||
|
|
||||||
from coulobre.local_update import SOCKET, display_status
|
from coulobre.linked_updates import staged_for_release
|
||||||
|
from coulobre.local_update import SOCKET
|
||||||
from coulobre.release_updates import (
|
from coulobre.release_updates import (
|
||||||
UpdateError,
|
UpdateError,
|
||||||
available_releases,
|
available_releases,
|
||||||
@@ -30,6 +31,30 @@ class UpdateForm(forms.Form):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def request_updater(payload, *, timeout=6):
|
||||||
|
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||||
|
peer.settimeout(timeout)
|
||||||
|
peer.connect(str(SOCKET))
|
||||||
|
peer.sendall(json.dumps(payload).encode() + b"\n")
|
||||||
|
with peer.makefile("rb") as reply:
|
||||||
|
result = json.loads(reply.readline(4096))
|
||||||
|
if not isinstance(result, dict) or result.get("accepted") is not True:
|
||||||
|
message = result.get("message") if isinstance(result, dict) else None
|
||||||
|
raise UpdateError(message or "The local updater could not be reached.")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_linked_nodes():
|
||||||
|
try:
|
||||||
|
return request_updater({"action": "linked-nodes"}, timeout=10)
|
||||||
|
except (OSError, ValueError, UpdateError) as error:
|
||||||
|
return {
|
||||||
|
"problem": str(error)
|
||||||
|
if isinstance(error, UpdateError)
|
||||||
|
else "The linked node preflight is unavailable."
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@method_decorator(never_cache, name="dispatch")
|
@method_decorator(never_cache, name="dispatch")
|
||||||
class UpdateView(UserPassesTestMixin, FormView):
|
class UpdateView(UserPassesTestMixin, FormView):
|
||||||
form_class = UpdateForm
|
form_class = UpdateForm
|
||||||
@@ -41,7 +66,6 @@ class UpdateView(UserPassesTestMixin, FormView):
|
|||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super().get_context_data(**kwargs)
|
context = super().get_context_data(**kwargs)
|
||||||
context["update_status"] = display_status()
|
|
||||||
context["updater_enabled"] = SOCKET.is_socket()
|
context["updater_enabled"] = SOCKET.is_socket()
|
||||||
context["may_apply"] = self.request.user.is_verified()
|
context["may_apply"] = self.request.user.is_verified()
|
||||||
try:
|
try:
|
||||||
@@ -53,12 +77,33 @@ class UpdateView(UserPassesTestMixin, FormView):
|
|||||||
return context
|
return context
|
||||||
context["installed_version"] = installed
|
context["installed_version"] = installed
|
||||||
if context["updater_enabled"]:
|
if context["updater_enabled"]:
|
||||||
|
if self.request.GET.get("refresh") == "1":
|
||||||
|
cache.delete(f"coulobre-updates:{installed}")
|
||||||
|
cache.delete("coulobre-update-linked-nodes")
|
||||||
|
topology = cache.get_or_set(
|
||||||
|
"coulobre-update-linked-nodes",
|
||||||
|
inspect_linked_nodes,
|
||||||
|
timeout=30,
|
||||||
|
)
|
||||||
|
nodes = topology.get("nodes", [])
|
||||||
|
context["update_status"] = topology.get("status", {})
|
||||||
|
context["linked_nodes"] = nodes
|
||||||
|
context["preflight_problem"] = topology.get("problem")
|
||||||
try:
|
try:
|
||||||
context["releases"] = cache.get_or_set(
|
context["releases"] = cache.get_or_set(
|
||||||
f"coulobre-updates:{installed}",
|
f"coulobre-updates:{installed}",
|
||||||
lambda: available_releases(installed),
|
lambda: available_releases(installed),
|
||||||
timeout=300,
|
timeout=300,
|
||||||
)
|
)
|
||||||
|
if not context["preflight_problem"]:
|
||||||
|
context["applyable_versions"] = {
|
||||||
|
release.version
|
||||||
|
for release in context["releases"]
|
||||||
|
if all(
|
||||||
|
staged_for_release(node, release.version)
|
||||||
|
for node in nodes
|
||||||
|
)
|
||||||
|
}
|
||||||
except UpdateError as error:
|
except UpdateError as error:
|
||||||
context["catalog_problem"] = str(error)
|
context["catalog_problem"] = str(error)
|
||||||
return context
|
return context
|
||||||
@@ -73,14 +118,8 @@ class UpdateView(UserPassesTestMixin, FormView):
|
|||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
version_key(payload["version"])
|
version_key(payload["version"])
|
||||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
request_updater(payload, timeout=10)
|
||||||
peer.settimeout(6)
|
cache.delete("coulobre-update-linked-nodes")
|
||||||
peer.connect(str(SOCKET))
|
|
||||||
peer.sendall(json.dumps(payload).encode() + b"\n")
|
|
||||||
with peer.makefile("rb") as reply:
|
|
||||||
result = json.loads(reply.readline(4096))
|
|
||||||
if not result.get("accepted"):
|
|
||||||
raise UpdateError(result["message"])
|
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
form.add_error(
|
form.add_error(
|
||||||
None,
|
None,
|
||||||
|
|||||||
@@ -2,6 +2,16 @@ from django.contrib.auth.views import LogoutView
|
|||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
|
||||||
from . import themes, views
|
from . import themes, views
|
||||||
|
from .account_security import (
|
||||||
|
AccountSecurityView,
|
||||||
|
ChangeEmailView,
|
||||||
|
ChangePasswordView,
|
||||||
|
ConfirmAuthenticatorView,
|
||||||
|
ReplaceRecoveryCodesView,
|
||||||
|
SignOutOtherSessionsView,
|
||||||
|
StartAuthenticatorView,
|
||||||
|
VerifyEmailView,
|
||||||
|
)
|
||||||
from .backup_restores import RestoreKind
|
from .backup_restores import RestoreKind
|
||||||
from .credential_views import DatabaseCredentialView, MailboxCredentialView
|
from .credential_views import DatabaseCredentialView, MailboxCredentialView
|
||||||
from .dns_defaults_views import DnsDefaultsView
|
from .dns_defaults_views import DnsDefaultsView
|
||||||
@@ -12,11 +22,12 @@ from .independent_website_views import (
|
|||||||
IndependentWebsiteManifest,
|
IndependentWebsiteManifest,
|
||||||
IndependentWebsiteOperation,
|
IndependentWebsiteOperation,
|
||||||
)
|
)
|
||||||
from .installation_views import InstallationView
|
from .installation_views import FeatureConfigurationView, InstallationView
|
||||||
from .invitations import AcceptInvitation, ManageInvitation
|
from .invitations import AcceptInvitation, ManageInvitation
|
||||||
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
|
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
|
||||||
from .mail_policy_views import MailRoutingEditor, MailVacationEditor
|
from .mail_policy_views import MailRoutingEditor, MailVacationEditor
|
||||||
from .mail_queue_views import MailQueueView
|
from .mail_queue_views import MailQueueView
|
||||||
|
from .panel_roles import AssignPanelRoleView, switch_panel_role
|
||||||
from .password_reset import (
|
from .password_reset import (
|
||||||
CustomerPasswordResetView,
|
CustomerPasswordResetView,
|
||||||
CustomerResetCompleteView,
|
CustomerResetCompleteView,
|
||||||
@@ -78,6 +89,17 @@ urlpatterns = [
|
|||||||
"service-health/", ServiceHealthView.as_view(), name="service_health"
|
"service-health/", ServiceHealthView.as_view(), name="service_health"
|
||||||
),
|
),
|
||||||
path("about/", InstallationView.as_view(), name="installation"),
|
path("about/", InstallationView.as_view(), name="installation"),
|
||||||
|
path(
|
||||||
|
"about/features/",
|
||||||
|
FeatureConfigurationView.as_view(),
|
||||||
|
name="feature_configuration",
|
||||||
|
),
|
||||||
|
path("account/role/", switch_panel_role, name="switch_panel_role"),
|
||||||
|
path(
|
||||||
|
"logins/assign-role/",
|
||||||
|
AssignPanelRoleView.as_view(),
|
||||||
|
name="assign_panel_role",
|
||||||
|
),
|
||||||
path("sign-in/", PanelLoginView.as_view(), name="login"),
|
path("sign-in/", PanelLoginView.as_view(), name="login"),
|
||||||
path(
|
path(
|
||||||
"welcome/<uidb64>/<token>/",
|
"welcome/<uidb64>/<token>/",
|
||||||
@@ -115,6 +137,40 @@ urlpatterns = [
|
|||||||
name="password_reset_complete",
|
name="password_reset_complete",
|
||||||
),
|
),
|
||||||
path("sign-out/", LogoutView.as_view(), name="logout"),
|
path("sign-out/", LogoutView.as_view(), name="logout"),
|
||||||
|
path(
|
||||||
|
"my-account/", AccountSecurityView.as_view(), name="account_security"
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"my-account/password/",
|
||||||
|
ChangePasswordView.as_view(),
|
||||||
|
name="account_password",
|
||||||
|
),
|
||||||
|
path("my-account/email/", ChangeEmailView.as_view(), name="account_email"),
|
||||||
|
path(
|
||||||
|
"my-account/email/verify/",
|
||||||
|
VerifyEmailView.as_view(),
|
||||||
|
name="account_email_verify",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"my-account/authenticator/",
|
||||||
|
StartAuthenticatorView.as_view(),
|
||||||
|
name="account_authenticator",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"my-account/authenticator/verify/",
|
||||||
|
ConfirmAuthenticatorView.as_view(),
|
||||||
|
name="account_authenticator_confirm",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"my-account/recovery-codes/",
|
||||||
|
ReplaceRecoveryCodesView.as_view(),
|
||||||
|
name="account_recovery_codes",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"my-account/sessions/",
|
||||||
|
SignOutOtherSessionsView.as_view(),
|
||||||
|
name="account_other_sessions",
|
||||||
|
),
|
||||||
path(
|
path(
|
||||||
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
|
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
|
||||||
),
|
),
|
||||||
|
|||||||
+116
-68
@@ -93,6 +93,11 @@ from .independent_websites import (
|
|||||||
website_actions,
|
website_actions,
|
||||||
website_limit,
|
website_limit,
|
||||||
)
|
)
|
||||||
|
from .installation_features import (
|
||||||
|
default_dns_zones_allowed,
|
||||||
|
panel_feature_allowed,
|
||||||
|
panel_feature_paused,
|
||||||
|
)
|
||||||
from .invitations import InviteLoginForm, queue_invitation
|
from .invitations import InviteLoginForm, queue_invitation
|
||||||
from .mail_policy_views import mail_policy_enabled
|
from .mail_policy_views import mail_policy_enabled
|
||||||
from .models import (
|
from .models import (
|
||||||
@@ -249,7 +254,7 @@ def missing_account_setup(account, actor):
|
|||||||
defaults = zone_defaults()
|
defaults = zone_defaults()
|
||||||
options = []
|
options = []
|
||||||
if (
|
if (
|
||||||
settings.LOCAL_WEB_ACTIVATION
|
panel_feature_allowed("LOCAL_WEB_ACTIVATION")
|
||||||
and actor.has_perms(ACTIVATE_WEB)
|
and actor.has_perms(ACTIVATE_WEB)
|
||||||
and not account.webprovisioningplan_set.filter(
|
and not account.webprovisioningplan_set.filter(
|
||||||
primary_domain=domain, activation__isnull=False
|
primary_domain=domain, activation__isnull=False
|
||||||
@@ -257,16 +262,14 @@ def missing_account_setup(account, actor):
|
|||||||
):
|
):
|
||||||
options.append(("setup_website", "Set up the primary website"))
|
options.append(("setup_website", "Set up the primary website"))
|
||||||
if (
|
if (
|
||||||
settings.LOCAL_DNS_PUBLISHING
|
default_dns_zones_allowed(defaults)
|
||||||
and defaults.nameservers
|
|
||||||
and defaults.addresses
|
|
||||||
and actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone"))
|
and actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone"))
|
||||||
and not HostingDnsZone.objects.filter(domain=domain).exists()
|
and not HostingDnsZone.objects.filter(domain=domain).exists()
|
||||||
):
|
):
|
||||||
options.append(("setup_dns", "Publish a Coulobre DNS zone"))
|
options.append(("setup_dns", "Publish a Coulobre DNS zone"))
|
||||||
if (
|
if (
|
||||||
settings.LOCAL_MAILBOX_PROVISIONING
|
panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
|
||||||
and settings.MANAGE_MAIL_DNS
|
and panel_feature_allowed("MANAGE_MAIL_DNS")
|
||||||
and actor.has_perms(PROVISION_MAILBOX)
|
and actor.has_perms(PROVISION_MAILBOX)
|
||||||
and not account.mail_domains.filter(domain=domain).exists()
|
and not account.mail_domains.filter(domain=domain).exists()
|
||||||
):
|
):
|
||||||
@@ -313,7 +316,7 @@ class ExistingAccountSetup(
|
|||||||
and bool(form["setup_email"].value())
|
and bool(form["setup_email"].value())
|
||||||
)
|
)
|
||||||
or (
|
or (
|
||||||
settings.MANAGE_MAIL_DNS
|
panel_feature_allowed("MANAGE_MAIL_DNS")
|
||||||
and self.account.mail_domains.filter(
|
and self.account.mail_domains.filter(
|
||||||
domain=self.account.primary_domain
|
domain=self.account.primary_domain
|
||||||
).exists()
|
).exists()
|
||||||
@@ -481,19 +484,12 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
|
|||||||
actor = self.request.user
|
actor = self.request.user
|
||||||
reseller = reseller_for_user(actor) is not None
|
reseller = reseller_for_user(actor) is not None
|
||||||
defaults = zone_defaults()
|
defaults = zone_defaults()
|
||||||
web = settings.LOCAL_WEB_ACTIVATION and (
|
web = panel_feature_allowed("LOCAL_WEB_ACTIVATION") and (
|
||||||
reseller or actor.has_perms(ACTIVATE_WEB)
|
reseller or actor.has_perms(ACTIVATE_WEB)
|
||||||
)
|
)
|
||||||
dns = (
|
dns = default_dns_zones_allowed(defaults) and (
|
||||||
settings.LOCAL_DNS_PUBLISHING
|
reseller
|
||||||
and defaults.nameservers
|
or actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone"))
|
||||||
and defaults.addresses
|
|
||||||
and (
|
|
||||||
reseller
|
|
||||||
or actor.has_perms(
|
|
||||||
(*PUBLISH_DNS, "hosting.add_hostingdnszone")
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
choices = {
|
choices = {
|
||||||
"setup_website": (web, "Set up the primary website"),
|
"setup_website": (web, "Set up the primary website"),
|
||||||
@@ -505,8 +501,8 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
|
|||||||
"setup_www": (web or dns, "Include the www hostname"),
|
"setup_www": (web or dns, "Include the www hostname"),
|
||||||
"setup_wildcard": (dns, "Include a wildcard (*) DNS record"),
|
"setup_wildcard": (dns, "Include a wildcard (*) DNS record"),
|
||||||
"setup_email": (
|
"setup_email": (
|
||||||
settings.LOCAL_MAILBOX_PROVISIONING
|
panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
|
||||||
and settings.MANAGE_MAIL_DNS
|
and panel_feature_allowed("MANAGE_MAIL_DNS")
|
||||||
and (reseller or actor.has_perms(PROVISION_MAILBOX)),
|
and (reseller or actor.has_perms(PROVISION_MAILBOX)),
|
||||||
"Set up email DNS for this domain",
|
"Set up email DNS for this domain",
|
||||||
),
|
),
|
||||||
@@ -620,7 +616,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
)
|
)
|
||||||
context["show_mail_queue"] = (
|
context["show_mail_queue"] = (
|
||||||
not tenant
|
not tenant
|
||||||
and settings.LOCAL_MAILBOX_PROVISIONING
|
and panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
|
||||||
and user.has_perm("hosting.view_hostingmaildomain")
|
and user.has_perm("hosting.view_hostingmaildomain")
|
||||||
)
|
)
|
||||||
manage_resources = reseller is not None and reseller.manage_resources
|
manage_resources = reseller is not None and reseller.manage_resources
|
||||||
@@ -645,10 +641,11 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
context["primary_file_access"] = manage_files and site_is_active(
|
context["primary_file_access"] = manage_files and site_is_active(
|
||||||
self.object
|
self.object
|
||||||
)
|
)
|
||||||
|
website_provisioning = panel_feature_allowed("LOCAL_WEB_ACTIVATION")
|
||||||
if settings.LOCAL_WEB_ACTIVATION or manage_files:
|
if settings.LOCAL_WEB_ACTIVATION or manage_files:
|
||||||
websites = list(account_websites(self.object))
|
websites = list(account_websites(self.object))
|
||||||
can_manage = (
|
can_manage = (
|
||||||
settings.LOCAL_WEB_ACTIVATION
|
website_provisioning
|
||||||
and not self.object.services_suspended
|
and not self.object.services_suspended
|
||||||
and (tenant or user.has_perm(CHANGE_ACCOUNTS))
|
and (tenant or user.has_perm(CHANGE_ACCOUNTS))
|
||||||
and getattr(self.request, "impersonation", None) is None
|
and getattr(self.request, "impersonation", None) is None
|
||||||
@@ -687,7 +684,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
):
|
):
|
||||||
context["website_storage"] = storage
|
context["website_storage"] = storage
|
||||||
context["can_measure_site_storage"] = (
|
context["can_measure_site_storage"] = (
|
||||||
settings.LOCAL_WEB_ACTIVATION
|
panel_feature_allowed("LOCAL_WEB_ACTIVATION")
|
||||||
and not tenant
|
and not tenant
|
||||||
and user.has_perms(MEASURE_SITE_STORAGE)
|
and user.has_perms(MEASURE_SITE_STORAGE)
|
||||||
)
|
)
|
||||||
@@ -698,7 +695,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
if quota is not None and quota.domain == self.object.primary_domain:
|
if quota is not None and quota.domain == self.object.primary_domain:
|
||||||
context["website_limit"] = quota
|
context["website_limit"] = quota
|
||||||
context["can_change_site_storage_limit"] = (
|
context["can_change_site_storage_limit"] = (
|
||||||
settings.LOCAL_WEB_ACTIVATION
|
panel_feature_allowed("LOCAL_WEB_ACTIVATION")
|
||||||
and not tenant
|
and not tenant
|
||||||
and user.has_perms(CHANGE_SITE_STORAGE_LIMIT)
|
and user.has_perms(CHANGE_SITE_STORAGE_LIMIT)
|
||||||
)
|
)
|
||||||
@@ -721,7 +718,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
)
|
)
|
||||||
context["website_php_job"] = php_job
|
context["website_php_job"] = php_job
|
||||||
context["can_change_php_settings"] = (
|
context["can_change_php_settings"] = (
|
||||||
not tenant and user.has_perms(CHANGE_SITE_PHP_SETTINGS)
|
website_provisioning
|
||||||
|
and not tenant
|
||||||
|
and user.has_perms(CHANGE_SITE_PHP_SETTINGS)
|
||||||
)
|
)
|
||||||
version_job = getattr(self.object, "php_version_job", None)
|
version_job = getattr(self.object, "php_version_job", None)
|
||||||
if (
|
if (
|
||||||
@@ -734,7 +733,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
)
|
)
|
||||||
context["website_php_version_job"] = version_job
|
context["website_php_version_job"] = version_job
|
||||||
context["can_change_php_version"] = (
|
context["can_change_php_version"] = (
|
||||||
can_change_php_version(self.request)
|
website_provisioning
|
||||||
|
and can_change_php_version(self.request)
|
||||||
and not self.object.services_suspended
|
and not self.object.services_suspended
|
||||||
and (
|
and (
|
||||||
version_job is None
|
version_job is None
|
||||||
@@ -746,13 +746,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
.select_related("reservation")
|
.select_related("reservation")
|
||||||
.order_by("reservation__domain")
|
.order_by("reservation__domain")
|
||||||
)
|
)
|
||||||
if not tenant and user.has_perms(MANAGE_WEBSITE_ALIASES):
|
if (
|
||||||
|
website_provisioning
|
||||||
|
and not tenant
|
||||||
|
and user.has_perms(MANAGE_WEBSITE_ALIASES)
|
||||||
|
):
|
||||||
context["manage_website_aliases"] = True
|
context["manage_website_aliases"] = True
|
||||||
context["can_add_website_alias"] = site_active
|
context["can_add_website_alias"] = site_active
|
||||||
context["can_enable_alias_https"] = (
|
context["can_enable_alias_https"] = panel_feature_allowed(
|
||||||
settings.LOCAL_WEB_HTTPS
|
"LOCAL_WEB_HTTPS"
|
||||||
and user.has_perms(ENABLE_WEB_HTTPS)
|
) and user.has_perms(ENABLE_WEB_HTTPS)
|
||||||
)
|
|
||||||
context["export_backup_manifest"] = not tenant and user.has_perms(
|
context["export_backup_manifest"] = not tenant and user.has_perms(
|
||||||
EXPORT_BACKUP_MANIFEST
|
EXPORT_BACKUP_MANIFEST
|
||||||
)
|
)
|
||||||
@@ -766,7 +769,12 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
):
|
):
|
||||||
can_view_mailboxes = user.has_perm(VIEW_MAILBOXES)
|
can_view_mailboxes = user.has_perm(VIEW_MAILBOXES)
|
||||||
context["show_account_backups"] = True
|
context["show_account_backups"] = True
|
||||||
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP)
|
context["can_request_account_backup"] = panel_feature_allowed(
|
||||||
|
"LOCAL_ACCOUNT_BACKUPS"
|
||||||
|
)
|
||||||
|
context["can_retry_offsite"] = panel_feature_allowed(
|
||||||
|
"OFFSITE_BACKUP_DESTINATIONS"
|
||||||
|
) and user.has_perms(RETRY_OFFSITE_BACKUP)
|
||||||
context["manage_backup_retention"] = (
|
context["manage_backup_retention"] = (
|
||||||
settings.LOCAL_BACKUP_RETENTION
|
settings.LOCAL_BACKUP_RETENTION
|
||||||
and user.has_perms(MANAGE_BACKUP_RETENTION)
|
and user.has_perms(MANAGE_BACKUP_RETENTION)
|
||||||
@@ -799,9 +807,10 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
or can_view_mailboxes
|
or can_view_mailboxes
|
||||||
):
|
):
|
||||||
context["account_backup_schedule"] = schedule
|
context["account_backup_schedule"] = schedule
|
||||||
context["edit_account_backup_schedule"] = user.has_perms(
|
context["edit_account_backup_schedule"] = (
|
||||||
MANAGE_BACKUP_SCHEDULE
|
schedule is not None
|
||||||
)
|
or context["can_request_account_backup"]
|
||||||
|
) and user.has_perms(MANAGE_BACKUP_SCHEDULE)
|
||||||
context["manage_sftp"] = (
|
context["manage_sftp"] = (
|
||||||
settings.LOCAL_WEB_SFTP
|
settings.LOCAL_WEB_SFTP
|
||||||
and can_manage_sftp(user)
|
and can_manage_sftp(user)
|
||||||
@@ -831,7 +840,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
context["automatic_database_provisioning"] = (
|
context["automatic_database_provisioning"] = (
|
||||||
automatic_resource_provisioning(
|
automatic_resource_provisioning(
|
||||||
user,
|
user,
|
||||||
settings.LOCAL_DATABASE_PROVISIONING,
|
panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"),
|
||||||
PROVISION_DATABASE,
|
PROVISION_DATABASE,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -840,8 +849,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
not tenant and user.has_perms(PROVISION_DATABASE)
|
not tenant and user.has_perms(PROVISION_DATABASE)
|
||||||
):
|
):
|
||||||
context["manage_database_provisioning"] = True
|
context["manage_database_provisioning"] = True
|
||||||
context["local_database_enabled"] = (
|
context["local_database_enabled"] = panel_feature_allowed(
|
||||||
settings.LOCAL_DATABASE_PROVISIONING
|
"LOCAL_DATABASE_PROVISIONING"
|
||||||
)
|
)
|
||||||
context["databases"] = databases
|
context["databases"] = databases
|
||||||
if tenant or user.has_perm(VIEW_DNS_ZONES):
|
if tenant or user.has_perm(VIEW_DNS_ZONES):
|
||||||
@@ -851,15 +860,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
"publication__manifest"
|
"publication__manifest"
|
||||||
)
|
)
|
||||||
context["tenant_dns_editing"] = True
|
context["tenant_dns_editing"] = True
|
||||||
context["tenant_dns_publishing"] = (
|
context["tenant_dns_publishing"] = panel_feature_allowed(
|
||||||
settings.LOCAL_DNS_PUBLISHING
|
"LOCAL_DNS_PUBLISHING"
|
||||||
)
|
)
|
||||||
if not tenant and user.has_perms(PUBLISH_DNS):
|
if not tenant and user.has_perms(PUBLISH_DNS):
|
||||||
zone_list = zone_list.select_related("publication").defer(
|
zone_list = zone_list.select_related("publication").defer(
|
||||||
"publication__manifest"
|
"publication__manifest"
|
||||||
)
|
)
|
||||||
context["manage_dns_publishing"] = True
|
context["manage_dns_publishing"] = True
|
||||||
context["local_dns_enabled"] = settings.LOCAL_DNS_PUBLISHING
|
context["local_dns_enabled"] = panel_feature_allowed(
|
||||||
|
"LOCAL_DNS_PUBLISHING"
|
||||||
|
)
|
||||||
zones = list(zone_list)
|
zones = list(zone_list)
|
||||||
context["dns_zones"] = zones
|
context["dns_zones"] = zones
|
||||||
context["dns_zone_records"] = [
|
context["dns_zone_records"] = [
|
||||||
@@ -876,11 +887,15 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
context["has_primary_zone"] = primary_zone is not None
|
context["has_primary_zone"] = primary_zone is not None
|
||||||
if primary_zone is None:
|
if primary_zone is None:
|
||||||
context["dns_readiness"] = "No managed zone"
|
context["dns_readiness"] = "No managed zone"
|
||||||
if not tenant and settings.LOCAL_DNS_PUBLISHING:
|
if not tenant and panel_feature_allowed(
|
||||||
|
"LOCAL_DNS_PUBLISHING"
|
||||||
|
):
|
||||||
try:
|
try:
|
||||||
draft = default_dns_zone(
|
draft = default_dns_zone(
|
||||||
self.object,
|
self.object,
|
||||||
managed_mail=settings.MANAGE_MAIL_DNS
|
managed_mail=panel_feature_allowed(
|
||||||
|
"MANAGE_MAIL_DNS"
|
||||||
|
)
|
||||||
and self.object.mail_domains.filter(
|
and self.object.mail_domains.filter(
|
||||||
domain=self.object.primary_domain
|
domain=self.object.primary_domain
|
||||||
).exists(),
|
).exists(),
|
||||||
@@ -904,7 +919,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
context["automatic_mailbox_provisioning"] = (
|
context["automatic_mailbox_provisioning"] = (
|
||||||
automatic_resource_provisioning(
|
automatic_resource_provisioning(
|
||||||
user,
|
user,
|
||||||
settings.LOCAL_MAILBOX_PROVISIONING,
|
panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"),
|
||||||
PROVISION_MAILBOX,
|
PROVISION_MAILBOX,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -929,8 +944,8 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
not tenant and user.has_perms(PROVISION_MAILBOX)
|
not tenant and user.has_perms(PROVISION_MAILBOX)
|
||||||
):
|
):
|
||||||
context["manage_mailbox_provisioning"] = True
|
context["manage_mailbox_provisioning"] = True
|
||||||
context["local_mailbox_enabled"] = (
|
context["local_mailbox_enabled"] = panel_feature_allowed(
|
||||||
settings.LOCAL_MAILBOX_PROVISIONING
|
"LOCAL_MAILBOX_PROVISIONING"
|
||||||
)
|
)
|
||||||
context["change_mailbox_quota"] = (
|
context["change_mailbox_quota"] = (
|
||||||
not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA)
|
not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA)
|
||||||
@@ -1002,7 +1017,7 @@ class SiteStorageLimitEdit(
|
|||||||
template_name = "hosting/site_storage_limit_form.html"
|
template_name = "hosting/site_storage_limit_form.html"
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
if not settings.LOCAL_WEB_ACTIVATION:
|
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
|
||||||
raise Http404
|
raise Http404
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
@@ -1051,7 +1066,7 @@ class SitePhpSettingsEdit(
|
|||||||
template_name = "hosting/site_php_settings_form.html"
|
template_name = "hosting/site_php_settings_form.html"
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
if not settings.LOCAL_WEB_ACTIVATION:
|
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
|
||||||
raise Http404
|
raise Http404
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
@@ -1098,7 +1113,7 @@ class SitePhpVersionEdit(PermissionRequiredMixin, FormView):
|
|||||||
template_name = "hosting/site_php_version_form.html"
|
template_name = "hosting/site_php_version_form.html"
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
if not settings.LOCAL_WEB_ACTIVATION:
|
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
|
||||||
raise Http404
|
raise Http404
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
@@ -1160,7 +1175,7 @@ class WebsiteAliasEditor(OperatorOnlyMixin, PermissionRequiredMixin, FormView):
|
|||||||
template_name = "hosting/website_alias_form.html"
|
template_name = "hosting/website_alias_form.html"
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
if not settings.LOCAL_WEB_ACTIVATION:
|
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
|
||||||
raise Http404
|
raise Http404
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
@@ -1214,9 +1229,9 @@ class WebsiteAliasAction(WebsiteAliasEditor):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def can_enable_https(self):
|
def can_enable_https(self):
|
||||||
return settings.LOCAL_WEB_HTTPS and self.request.user.has_perms(
|
return panel_feature_allowed(
|
||||||
ENABLE_WEB_HTTPS
|
"LOCAL_WEB_HTTPS"
|
||||||
)
|
) and self.request.user.has_perms(ENABLE_WEB_HTTPS)
|
||||||
|
|
||||||
def has_permission(self):
|
def has_permission(self):
|
||||||
if not super().has_permission():
|
if not super().has_permission():
|
||||||
@@ -1259,7 +1274,7 @@ class RequestSiteStorageMeasurement(
|
|||||||
permission_required = MEASURE_SITE_STORAGE
|
permission_required = MEASURE_SITE_STORAGE
|
||||||
|
|
||||||
def post(self, request, pk):
|
def post(self, request, pk):
|
||||||
if not settings.LOCAL_WEB_ACTIVATION:
|
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
|
||||||
raise Http404
|
raise Http404
|
||||||
try:
|
try:
|
||||||
queue_site_storage_measurement(pk)
|
queue_site_storage_measurement(pk)
|
||||||
@@ -1305,7 +1320,7 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
permission_required = MANAGE_ACCOUNT_BACKUPS
|
permission_required = MANAGE_ACCOUNT_BACKUPS
|
||||||
|
|
||||||
def post(self, request, pk):
|
def post(self, request, pk):
|
||||||
if not settings.LOCAL_ACCOUNT_BACKUPS:
|
if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
|
||||||
raise Http404
|
raise Http404
|
||||||
include_mailboxes = request.POST.get("include_mail") == "1"
|
include_mailboxes = request.POST.get("include_mail") == "1"
|
||||||
if include_mailboxes:
|
if include_mailboxes:
|
||||||
@@ -1354,7 +1369,9 @@ class AccountBackupArchiveList(
|
|||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
context = super().get_context_data(account=self.account, **kwargs)
|
context = super().get_context_data(account=self.account, **kwargs)
|
||||||
user = self.request.user
|
user = self.request.user
|
||||||
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP)
|
context["can_retry_offsite"] = panel_feature_allowed(
|
||||||
|
"OFFSITE_BACKUP_DESTINATIONS"
|
||||||
|
) and user.has_perms(RETRY_OFFSITE_BACKUP)
|
||||||
context["manage_backup_retention"] = (
|
context["manage_backup_retention"] = (
|
||||||
settings.LOCAL_BACKUP_RETENTION
|
settings.LOCAL_BACKUP_RETENTION
|
||||||
and user.has_perms(MANAGE_BACKUP_RETENTION)
|
and user.has_perms(MANAGE_BACKUP_RETENTION)
|
||||||
@@ -1378,7 +1395,9 @@ class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
permission_required = RETRY_OFFSITE_BACKUP
|
permission_required = RETRY_OFFSITE_BACKUP
|
||||||
|
|
||||||
def post(self, request, pk, backup_pk):
|
def post(self, request, pk, backup_pk):
|
||||||
if not settings.LOCAL_ACCOUNT_BACKUPS:
|
if not settings.LOCAL_ACCOUNT_BACKUPS or not panel_feature_allowed(
|
||||||
|
"OFFSITE_BACKUP_DESTINATIONS"
|
||||||
|
):
|
||||||
raise Http404
|
raise Http404
|
||||||
account = get_object_or_404(HostingAccount, pk=pk)
|
account = get_object_or_404(HostingAccount, pk=pk)
|
||||||
backup = get_object_or_404(
|
backup = get_object_or_404(
|
||||||
@@ -1689,6 +1708,8 @@ class EditAccountBackupSchedule(
|
|||||||
def get_initial(self):
|
def get_initial(self):
|
||||||
schedule = getattr(self.account, "backup_schedule", None)
|
schedule = getattr(self.account, "backup_schedule", None)
|
||||||
if schedule is None:
|
if schedule is None:
|
||||||
|
if not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS"):
|
||||||
|
raise Http404
|
||||||
return {
|
return {
|
||||||
"enabled": True,
|
"enabled": True,
|
||||||
"frequency": AccountBackupSchedule.Frequency.DAILY,
|
"frequency": AccountBackupSchedule.Frequency.DAILY,
|
||||||
@@ -1711,6 +1732,15 @@ class EditAccountBackupSchedule(
|
|||||||
return super().get_context_data(account=self.account, **kwargs)
|
return super().get_context_data(account=self.account, **kwargs)
|
||||||
|
|
||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
|
if (
|
||||||
|
form.cleaned_data["enabled"]
|
||||||
|
and not self.get_initial()["enabled"]
|
||||||
|
and not panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
|
||||||
|
):
|
||||||
|
form.add_error(
|
||||||
|
"enabled", "New backup requests are paused in the panel."
|
||||||
|
)
|
||||||
|
return self.form_invalid(form)
|
||||||
try:
|
try:
|
||||||
save_backup_schedule(
|
save_backup_schedule(
|
||||||
self.account.pk,
|
self.account.pk,
|
||||||
@@ -1977,7 +2007,7 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
|
|||||||
def auto_provision(self):
|
def auto_provision(self):
|
||||||
return automatic_resource_provisioning(
|
return automatic_resource_provisioning(
|
||||||
self.request.user,
|
self.request.user,
|
||||||
getattr(settings, self.provisioning_setting),
|
panel_feature_allowed(self.provisioning_setting),
|
||||||
self.provisioning_permissions,
|
self.provisioning_permissions,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -2070,7 +2100,7 @@ class ResourceProvisioningRequest(PermissionRequiredMixin, View):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def post(self, request, pk):
|
def post(self, request, pk):
|
||||||
if not getattr(settings, self.enabled_setting):
|
if not panel_feature_allowed(self.enabled_setting):
|
||||||
raise Http404
|
raise Http404
|
||||||
queryset = self.queryset.all()
|
queryset = self.queryset.all()
|
||||||
if self.reseller is not None:
|
if self.reseller is not None:
|
||||||
@@ -2141,7 +2171,7 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
|
|||||||
try:
|
try:
|
||||||
draft = default_dns_zone(
|
draft = default_dns_zone(
|
||||||
self.account,
|
self.account,
|
||||||
managed_mail=settings.MANAGE_MAIL_DNS
|
managed_mail=panel_feature_allowed("MANAGE_MAIL_DNS")
|
||||||
and self.account.mail_domains.filter(
|
and self.account.mail_domains.filter(
|
||||||
domain=self.domain
|
domain=self.domain
|
||||||
).exists(),
|
).exists(),
|
||||||
@@ -2157,9 +2187,9 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
|
|||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def publish_on_create(self):
|
def publish_on_create(self):
|
||||||
return settings.LOCAL_DNS_PUBLISHING and self.request.user.has_perms(
|
return panel_feature_allowed(
|
||||||
PUBLISH_DNS
|
"LOCAL_DNS_PUBLISHING"
|
||||||
)
|
) and self.request.user.has_perms(PUBLISH_DNS)
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
return super().get_context_data(
|
return super().get_context_data(
|
||||||
@@ -2167,6 +2197,13 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
|
if form.cleaned_data["manage_mail_dns"] and panel_feature_paused(
|
||||||
|
"MANAGE_MAIL_DNS"
|
||||||
|
):
|
||||||
|
form.add_error(
|
||||||
|
"manage_mail_dns", "Managed mail DNS is paused in the panel."
|
||||||
|
)
|
||||||
|
return self.form_invalid(form)
|
||||||
try:
|
try:
|
||||||
with transaction.atomic():
|
with transaction.atomic():
|
||||||
account = lock_hosting_account(
|
account = lock_hosting_account(
|
||||||
@@ -2272,6 +2309,15 @@ class DnsZoneEdit(DnsZoneEditor):
|
|||||||
|
|
||||||
def form_valid(self, form):
|
def form_valid(self, form):
|
||||||
values = form.cleaned_data
|
values = form.cleaned_data
|
||||||
|
if (
|
||||||
|
values["manage_mail_dns"]
|
||||||
|
and not self.zone.manage_mail_dns
|
||||||
|
and panel_feature_paused("MANAGE_MAIL_DNS")
|
||||||
|
):
|
||||||
|
form.add_error(
|
||||||
|
"manage_mail_dns", "Managed mail DNS is paused in the panel."
|
||||||
|
)
|
||||||
|
return self.form_invalid(form)
|
||||||
serial = values["serial"]
|
serial = values["serial"]
|
||||||
if all(
|
if all(
|
||||||
getattr(self.zone, field) == value
|
getattr(self.zone, field) == value
|
||||||
@@ -2344,7 +2390,7 @@ class RequestDnsPublication(PermissionRequiredMixin, View):
|
|||||||
return super().has_permission()
|
return super().has_permission()
|
||||||
|
|
||||||
def post(self, request, pk):
|
def post(self, request, pk):
|
||||||
if not settings.LOCAL_DNS_PUBLISHING:
|
if not panel_feature_allowed("LOCAL_DNS_PUBLISHING"):
|
||||||
raise Http404
|
raise Http404
|
||||||
try:
|
try:
|
||||||
zone = queue_dns_publication(
|
zone = queue_dns_publication(
|
||||||
@@ -2569,10 +2615,12 @@ class PlanDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
return super().get_context_data(
|
return super().get_context_data(
|
||||||
manage_activation=not is_tenant(user)
|
manage_activation=not is_tenant(user)
|
||||||
and user.has_perms(ACTIVATE_WEB),
|
and user.has_perms(ACTIVATE_WEB),
|
||||||
local_activation_enabled=settings.LOCAL_WEB_ACTIVATION,
|
local_activation_enabled=panel_feature_allowed(
|
||||||
|
"LOCAL_WEB_ACTIVATION"
|
||||||
|
),
|
||||||
manage_https=not is_tenant(user)
|
manage_https=not is_tenant(user)
|
||||||
and user.has_perms(ENABLE_WEB_HTTPS),
|
and user.has_perms(ENABLE_WEB_HTTPS),
|
||||||
local_https_enabled=settings.LOCAL_WEB_HTTPS,
|
local_https_enabled=panel_feature_allowed("LOCAL_WEB_HTTPS"),
|
||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -2584,7 +2632,7 @@ class RequestWebActivation(
|
|||||||
permission_required = ACTIVATE_WEB
|
permission_required = ACTIVATE_WEB
|
||||||
|
|
||||||
def post(self, request, *args, **kwargs):
|
def post(self, request, *args, **kwargs):
|
||||||
if not settings.LOCAL_WEB_ACTIVATION:
|
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
|
||||||
raise Http404
|
raise Http404
|
||||||
plan = self.get_object()
|
plan = self.get_object()
|
||||||
if not plan.can_export:
|
if not plan.can_export:
|
||||||
@@ -2610,7 +2658,7 @@ class RequestWebHTTPS(
|
|||||||
permission_required = ENABLE_WEB_HTTPS
|
permission_required = ENABLE_WEB_HTTPS
|
||||||
|
|
||||||
def post(self, request, *args, **kwargs):
|
def post(self, request, *args, **kwargs):
|
||||||
if not settings.LOCAL_WEB_HTTPS:
|
if not panel_feature_allowed("LOCAL_WEB_HTTPS"):
|
||||||
raise Http404
|
raise Http404
|
||||||
plan = self.get_object()
|
plan = self.get_object()
|
||||||
if not plan.can_enable_https:
|
if not plan.can_enable_https:
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
from django import forms
|
from django import forms
|
||||||
from django.conf import settings
|
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.http import Http404, StreamingHttpResponse
|
from django.http import Http404, StreamingHttpResponse
|
||||||
@@ -22,6 +21,7 @@ from coulobre.website_files import (
|
|||||||
|
|
||||||
from .access import TenantScopeMixin, is_tenant
|
from .access import TenantScopeMixin, is_tenant
|
||||||
from .independent_websites import active_websites
|
from .independent_websites import active_websites
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import HostingAccount
|
from .models import HostingAccount
|
||||||
from .resource_requests import require_active_services
|
from .resource_requests import require_active_services
|
||||||
from .sftp import site_is_active
|
from .sftp import site_is_active
|
||||||
@@ -34,7 +34,7 @@ UNAVAILABLE = "The website files service is unavailable. Try again later."
|
|||||||
def can_manage_website_files(request):
|
def can_manage_website_files(request):
|
||||||
user = request.user
|
user = request.user
|
||||||
return (
|
return (
|
||||||
settings.WEB_FILE_MANAGER
|
panel_feature_allowed("WEB_FILE_MANAGER")
|
||||||
and getattr(request, "impersonation", None) is None
|
and getattr(request, "impersonation", None) is None
|
||||||
and (is_tenant(user) or user.has_perms(MANAGE_FILES))
|
and (is_tenant(user) or user.has_perms(MANAGE_FILES))
|
||||||
)
|
)
|
||||||
@@ -75,7 +75,7 @@ class WebsiteFilesView(
|
|||||||
permission_required = MANAGE_FILES
|
permission_required = MANAGE_FILES
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
if not settings.WEB_FILE_MANAGER:
|
if not panel_feature_allowed("WEB_FILE_MANAGER"):
|
||||||
raise Http404
|
raise Http404
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
from django import forms
|
from django import forms
|
||||||
from django.conf import settings
|
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
@@ -18,6 +17,7 @@ from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command
|
|||||||
|
|
||||||
from .access import TenantScopeMixin, is_tenant
|
from .access import TenantScopeMixin, is_tenant
|
||||||
from .independent_websites import check_actor
|
from .independent_websites import check_actor
|
||||||
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import HostingAccount
|
from .models import HostingAccount
|
||||||
from .resource_requests import lock_hosting_account
|
from .resource_requests import lock_hosting_account
|
||||||
from .website_job_schedule import next_website_run
|
from .website_job_schedule import next_website_run
|
||||||
@@ -33,7 +33,7 @@ MANAGE_JOBS = ("hosting.view_hostingaccount", "hosting.manage_website_jobs")
|
|||||||
def can_manage_website_jobs(request):
|
def can_manage_website_jobs(request):
|
||||||
user = request.user
|
user = request.user
|
||||||
return (
|
return (
|
||||||
settings.WEBSITE_JOBS
|
panel_feature_allowed("WEBSITE_JOBS")
|
||||||
and getattr(request, "impersonation", None) is None
|
and getattr(request, "impersonation", None) is None
|
||||||
and (is_tenant(user) or user.has_perms(MANAGE_JOBS))
|
and (is_tenant(user) or user.has_perms(MANAGE_JOBS))
|
||||||
)
|
)
|
||||||
@@ -104,7 +104,7 @@ class WebsiteJobAccountView(
|
|||||||
permission_required = MANAGE_JOBS
|
permission_required = MANAGE_JOBS
|
||||||
|
|
||||||
def dispatch(self, request, *args, **kwargs):
|
def dispatch(self, request, *args, **kwargs):
|
||||||
if not settings.WEBSITE_JOBS:
|
if not panel_feature_allowed("WEBSITE_JOBS"):
|
||||||
raise Http404
|
raise Http404
|
||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import socket
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .node_files import read_root_file, require_root_directory
|
||||||
|
from .node_probe import (
|
||||||
|
PROBE_BYTES,
|
||||||
|
PROBE_LIMIT,
|
||||||
|
STATUS_PROBE_BYTES,
|
||||||
|
parse_status_probe,
|
||||||
|
)
|
||||||
|
|
||||||
|
ROLES = ("dns", "mail")
|
||||||
|
LOCAL_MODES = {"local", "off"}
|
||||||
|
REMOTE_MODES = {"remote", "remote-install"}
|
||||||
|
RELAY_DIR = Path("/etc/coulobre-remote")
|
||||||
|
UNIT_DIR = Path("/etc/systemd/system")
|
||||||
|
|
||||||
|
|
||||||
|
def relay_is_installed(role):
|
||||||
|
drop_in = UNIT_DIR / f"coulobre-{role}-apply@.service.d/remote.conf"
|
||||||
|
require_root_directory(drop_in.parent)
|
||||||
|
read_root_file(drop_in, mode=0o644)
|
||||||
|
directory = RELAY_DIR / role
|
||||||
|
require_root_directory(directory)
|
||||||
|
for name in ("known_hosts", "ssh_config"):
|
||||||
|
read_root_file(directory / name, mode=0o640)
|
||||||
|
|
||||||
|
|
||||||
|
def read_probe(role, payload):
|
||||||
|
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||||
|
peer.settimeout(3)
|
||||||
|
peer.connect(f"/run/coulobre-{role}-apply.sock")
|
||||||
|
peer.sendall(payload)
|
||||||
|
peer.shutdown(socket.SHUT_WR)
|
||||||
|
with peer.makefile("rb") as stream:
|
||||||
|
return stream.read(PROBE_LIMIT + 1)
|
||||||
|
|
||||||
|
|
||||||
|
def receiver_status(role, host):
|
||||||
|
status = {
|
||||||
|
"role": role,
|
||||||
|
"host": host,
|
||||||
|
"release": None,
|
||||||
|
"protocol": None,
|
||||||
|
"state": "unavailable",
|
||||||
|
"upgrade_target": None,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
relay_is_installed(role)
|
||||||
|
body = read_probe(role, STATUS_PROBE_BYTES)
|
||||||
|
try:
|
||||||
|
report = parse_status_probe(body, role)
|
||||||
|
except ValueError:
|
||||||
|
report = parse_status_probe(read_probe(role, PROBE_BYTES), role)
|
||||||
|
except (ValueError, OSError):
|
||||||
|
return status
|
||||||
|
return status | report
|
||||||
|
|
||||||
|
|
||||||
|
def linked_roles(plan):
|
||||||
|
roles = []
|
||||||
|
for role in ROLES:
|
||||||
|
config = plan[role]
|
||||||
|
mode = config["mode"]
|
||||||
|
installed = (
|
||||||
|
UNIT_DIR / f"coulobre-{role}-apply@.service.d/remote.conf"
|
||||||
|
).exists()
|
||||||
|
if mode in REMOTE_MODES:
|
||||||
|
roles.append((role, config["host"]))
|
||||||
|
elif (
|
||||||
|
mode not in LOCAL_MODES or installed or (RELAY_DIR / role).exists()
|
||||||
|
):
|
||||||
|
raise ValueError("Check manually configured linked receivers.")
|
||||||
|
if RELAY_DIR.exists() and any(
|
||||||
|
child.name not in ROLES for child in RELAY_DIR.iterdir()
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"Use the manual procedure for additional remote mail services."
|
||||||
|
)
|
||||||
|
return roles
|
||||||
|
|
||||||
|
|
||||||
|
def staged_for_release(node, target):
|
||||||
|
return (
|
||||||
|
node["protocol"] == 2
|
||||||
|
and node["state"] == "maintenance"
|
||||||
|
and node["release"] == target == node["upgrade_target"]
|
||||||
|
)
|
||||||
@@ -15,7 +15,14 @@ from pathlib import Path
|
|||||||
from pwd import getpwnam
|
from pwd import getpwnam
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
|
|
||||||
from .release_updates import UpdateError, download_wheel, selected_release
|
from .linked_updates import linked_roles, receiver_status, staged_for_release
|
||||||
|
from .release_updates import (
|
||||||
|
SHA256,
|
||||||
|
UpdateError,
|
||||||
|
download_wheel,
|
||||||
|
selected_release,
|
||||||
|
version_key,
|
||||||
|
)
|
||||||
|
|
||||||
LOGGER = logging.getLogger(__name__)
|
LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -63,11 +70,6 @@ VENV = Path("/opt/coulobre")
|
|||||||
PYTHON = VENV / "bin/python"
|
PYTHON = VENV / "bin/python"
|
||||||
CONFIG = Path("/etc/coulobre/panel.env")
|
CONFIG = Path("/etc/coulobre/panel.env")
|
||||||
INSTALLATION = Path("/var/lib/coulobre-installer/installation.json")
|
INSTALLATION = Path("/var/lib/coulobre-installer/installation.json")
|
||||||
SYSTEMD = Path("/etc/systemd/system")
|
|
||||||
REMOTE_RELAY = (
|
|
||||||
"coulobre-dns-apply@.service.d/remote.conf",
|
|
||||||
"coulobre-mail-apply@.service.d/remote.conf",
|
|
||||||
)
|
|
||||||
ROOT_COMMAND_ENV = {
|
ROOT_COMMAND_ENV = {
|
||||||
"PATH": "/usr/sbin:/usr/bin:/sbin:/bin",
|
"PATH": "/usr/sbin:/usr/bin:/sbin:/bin",
|
||||||
"LC_ALL": "C.UTF-8",
|
"LC_ALL": "C.UTF-8",
|
||||||
@@ -90,7 +92,7 @@ def publish_status(status, state, message):
|
|||||||
with staged.open("w", encoding="utf-8") as stream:
|
with staged.open("w", encoding="utf-8") as stream:
|
||||||
json.dump(status, stream)
|
json.dump(status, stream)
|
||||||
stream.write("\n")
|
stream.write("\n")
|
||||||
os.fchmod(stream.fileno(), 0o644)
|
os.fchmod(stream.fileno(), 0o600)
|
||||||
stream.flush()
|
stream.flush()
|
||||||
os.fsync(stream.fileno())
|
os.fsync(stream.fileno())
|
||||||
staged.replace(STATUS)
|
staged.replace(STATUS)
|
||||||
@@ -138,33 +140,46 @@ def root_controlled(path):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def check_installation():
|
def installation_plan():
|
||||||
try:
|
try:
|
||||||
if not all(
|
if not all(
|
||||||
root_controlled(path) for path in (VENV, CONFIG, INSTALLATION)
|
root_controlled(path) for path in (VENV, CONFIG, INSTALLATION)
|
||||||
):
|
):
|
||||||
raise ValueError
|
raise ValueError
|
||||||
installation = json.loads(INSTALLATION.read_text())
|
installation = json.loads(INSTALLATION.read_text())
|
||||||
plan = installation["plan"]
|
|
||||||
if installation.get("complete") is not True or not all(
|
|
||||||
plan[role]["mode"] in {"local", "off"} for role in ("dns", "mail")
|
|
||||||
):
|
|
||||||
raise ValueError
|
|
||||||
if (
|
if (
|
||||||
any((SYSTEMD / relay).exists() for relay in REMOTE_RELAY)
|
installation.get("complete") is not True
|
||||||
or Path("/etc/coulobre-remote").exists()
|
or os.environ.get("COULOBRE_DB_NAME") != "coulobre_panel"
|
||||||
):
|
|
||||||
raise ValueError
|
|
||||||
if (
|
|
||||||
os.environ.get("COULOBRE_DB_NAME") != "coulobre_panel"
|
|
||||||
or os.environ.get("COULOBRE_DB_HOST") != "/run/mysqld/mysqld.sock"
|
or os.environ.get("COULOBRE_DB_HOST") != "/run/mysqld/mysqld.sock"
|
||||||
):
|
):
|
||||||
raise ValueError
|
raise ValueError
|
||||||
|
return installation["plan"]
|
||||||
|
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||||
|
raise UpdateError(
|
||||||
|
"Web updates require a complete installer-managed panel "
|
||||||
|
"with a local MariaDB database."
|
||||||
|
) from error
|
||||||
|
|
||||||
|
|
||||||
|
def linked_status(plan):
|
||||||
|
try:
|
||||||
|
roles = linked_roles(plan)
|
||||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||||
raise UpdateError(
|
raise UpdateError(
|
||||||
"Web updates require a complete single-server installation "
|
"Use the manual upgrade procedure for this remote configuration."
|
||||||
"with the installer-managed MariaDB database."
|
|
||||||
) from error
|
) from error
|
||||||
|
return [receiver_status(role, host) for role, host in roles]
|
||||||
|
|
||||||
|
|
||||||
|
def check_installation(target):
|
||||||
|
plan = installation_plan()
|
||||||
|
if not all(
|
||||||
|
staged_for_release(node, target) for node in linked_status(plan)
|
||||||
|
):
|
||||||
|
raise UpdateError(
|
||||||
|
"Stage every linked receiver at the selected release before "
|
||||||
|
"upgrading the panel."
|
||||||
|
)
|
||||||
return plan["hostname"]
|
return plan["hostname"]
|
||||||
|
|
||||||
|
|
||||||
@@ -281,6 +296,26 @@ def back_up(backup, log):
|
|||||||
raise UpdateError("The database recovery dump is empty.")
|
raise UpdateError("The database recovery dump is empty.")
|
||||||
|
|
||||||
|
|
||||||
|
def check_dependencies(wheel, log):
|
||||||
|
try:
|
||||||
|
run(
|
||||||
|
PYTHON,
|
||||||
|
"-m",
|
||||||
|
"pip",
|
||||||
|
"--isolated",
|
||||||
|
"install",
|
||||||
|
"--dry-run",
|
||||||
|
"--no-index",
|
||||||
|
wheel,
|
||||||
|
log=log,
|
||||||
|
)
|
||||||
|
except UpdateError:
|
||||||
|
raise UpdateError(
|
||||||
|
"The installed dependencies cannot satisfy this release. "
|
||||||
|
"Use the manual upgrade procedure."
|
||||||
|
) from None
|
||||||
|
|
||||||
|
|
||||||
def apply_update(status, request, hostname):
|
def apply_update(status, request, hostname):
|
||||||
backup = STATE / datetime.now(UTC).strftime("recovery-%Y%m%dT%H%M%S%fZ")
|
backup = STATE / datetime.now(UTC).strftime("recovery-%Y%m%dT%H%M%S%fZ")
|
||||||
backup.mkdir(mode=0o700)
|
backup.mkdir(mode=0o700)
|
||||||
@@ -299,6 +334,8 @@ def apply_update(status, request, hostname):
|
|||||||
)
|
)
|
||||||
publish_status(status, "running", "Verifying the release package.")
|
publish_status(status, "running", "Verifying the release package.")
|
||||||
wheel = download_wheel(release, download)
|
wheel = download_wheel(release, download)
|
||||||
|
check_dependencies(wheel, log)
|
||||||
|
check_installation(release.version)
|
||||||
active = active_units(log)
|
active = active_units(log)
|
||||||
if not {PANEL, BEAT, WORKER} <= set(active):
|
if not {PANEL, BEAT, WORKER} <= set(active):
|
||||||
raise UpdateError(
|
raise UpdateError(
|
||||||
@@ -417,6 +454,8 @@ def read_request(peer):
|
|||||||
raise UpdateError("Only the Coulobre panel can request updates.")
|
raise UpdateError("Only the Coulobre panel can request updates.")
|
||||||
with peer.makefile("rb") as stream:
|
with peer.makefile("rb") as stream:
|
||||||
request = json.loads(stream.readline(2048))
|
request = json.loads(stream.readline(2048))
|
||||||
|
if request == {"action": "linked-nodes"}:
|
||||||
|
return request
|
||||||
if not isinstance(request, dict) or set(request) != {
|
if not isinstance(request, dict) or set(request) != {
|
||||||
"version",
|
"version",
|
||||||
"sha256",
|
"sha256",
|
||||||
@@ -431,6 +470,9 @@ def read_request(peer):
|
|||||||
for value in request.values()
|
for value in request.values()
|
||||||
):
|
):
|
||||||
raise UpdateError("The update request is invalid.")
|
raise UpdateError("The update request is invalid.")
|
||||||
|
version_key(request["version"])
|
||||||
|
if not SHA256.fullmatch(request["sha256"]):
|
||||||
|
raise UpdateError("The update request is invalid.")
|
||||||
return request
|
return request
|
||||||
|
|
||||||
|
|
||||||
@@ -440,12 +482,25 @@ def reply(peer, **payload):
|
|||||||
|
|
||||||
def handle_request(peer):
|
def handle_request(peer):
|
||||||
request = read_request(peer)
|
request = read_request(peer)
|
||||||
|
if request.get("action") == "linked-nodes":
|
||||||
|
try:
|
||||||
|
nodes = linked_status(installation_plan())
|
||||||
|
except UpdateError as error:
|
||||||
|
reply(
|
||||||
|
peer,
|
||||||
|
accepted=True,
|
||||||
|
status=display_status(),
|
||||||
|
problem=str(error),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
reply(peer, accepted=True, status=display_status(), nodes=nodes)
|
||||||
|
return
|
||||||
with LOCK.open("a") as lock:
|
with LOCK.open("a") as lock:
|
||||||
try:
|
try:
|
||||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
except BlockingIOError as error:
|
except BlockingIOError as error:
|
||||||
raise UpdateError("An update is already running.") from error
|
raise UpdateError("An update is already running.") from error
|
||||||
os.fchmod(lock.fileno(), 0o644)
|
os.fchmod(lock.fileno(), 0o600)
|
||||||
previous = read_status()
|
previous = read_status()
|
||||||
if previous.get("state") == "running":
|
if previous.get("state") == "running":
|
||||||
publish_status(
|
publish_status(
|
||||||
@@ -471,7 +526,7 @@ def handle_request(peer):
|
|||||||
status["actor"],
|
status["actor"],
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
hostname = check_installation()
|
hostname = check_installation(request["version"])
|
||||||
except UpdateError as error:
|
except UpdateError as error:
|
||||||
publish_status(status, "failed", str(error))
|
publish_status(status, "failed", str(error))
|
||||||
raise
|
raise
|
||||||
|
|||||||
@@ -201,12 +201,14 @@ def serve_mail_archive(operation):
|
|||||||
from .account_restore_request import apply_restore_once
|
from .account_restore_request import apply_restore_once
|
||||||
from .mail_node_backup import backup_mailbox, restore_mailbox
|
from .mail_node_backup import backup_mailbox, restore_mailbox
|
||||||
from .node_files import require_root_directory
|
from .node_files import require_root_directory
|
||||||
|
from .receiver_scope import check_mail_service_peer
|
||||||
|
|
||||||
source, output = sys.stdin.buffer, sys.stdout.buffer
|
source, output = sys.stdin.buffer, sys.stdout.buffer
|
||||||
identity = {"version": 1, "operation": operation}
|
identity = {"version": 1, "operation": operation}
|
||||||
try:
|
try:
|
||||||
if os.geteuid() != 0:
|
if os.geteuid() != 0:
|
||||||
raise ValueError("Run the mail archive service as root.")
|
raise ValueError("Run the mail archive service as root.")
|
||||||
|
check_mail_service_peer()
|
||||||
request = MailArchiveRequest.parse(read_header(source), operation)
|
request = MailArchiveRequest.parse(read_header(source), operation)
|
||||||
identity = request.manifest()
|
identity = request.manifest()
|
||||||
require_root_directory(WORK_DIRECTORY)
|
require_root_directory(WORK_DIRECTORY)
|
||||||
|
|||||||
@@ -74,13 +74,13 @@ def replace_configuration(path, content, *, mode=0o644):
|
|||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def locked_root_directory(path):
|
def locked_root_directory(path, *, shared=False):
|
||||||
import fcntl
|
import fcntl
|
||||||
|
|
||||||
require_root_directory(path)
|
require_root_directory(path)
|
||||||
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||||
try:
|
try:
|
||||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
fcntl.flock(fd, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
|
||||||
yield fd
|
yield fd
|
||||||
finally:
|
finally:
|
||||||
os.close(fd)
|
os.close(fd)
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import shlex
|
||||||
|
from importlib.metadata import version
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .node_files import (
|
||||||
|
locked_root_directory,
|
||||||
|
read_root_file,
|
||||||
|
require_root_directory,
|
||||||
|
write_new_file,
|
||||||
|
)
|
||||||
|
from .release_updates import UpdateError, version_key
|
||||||
|
|
||||||
|
NODE_KEYS = Path("/etc/ssh/coulobre-node-keys")
|
||||||
|
|
||||||
|
|
||||||
|
def maintenance_path(role):
|
||||||
|
return NODE_KEYS / f".{role}-upgrade.json"
|
||||||
|
|
||||||
|
|
||||||
|
def rollout_target(role):
|
||||||
|
path = maintenance_path(role)
|
||||||
|
try:
|
||||||
|
path.lstat()
|
||||||
|
require_root_directory(NODE_KEYS)
|
||||||
|
data = json.loads(read_root_file(path, mode=0o600))
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
if (
|
||||||
|
not isinstance(data, dict)
|
||||||
|
or set(data) != {"target", "panels"}
|
||||||
|
or not isinstance(data["panels"], dict)
|
||||||
|
):
|
||||||
|
raise ValueError("Invalid receiver maintenance record.")
|
||||||
|
try:
|
||||||
|
version_key(data["target"])
|
||||||
|
except UpdateError as error:
|
||||||
|
raise ValueError(str(error)) from None
|
||||||
|
return data["target"]
|
||||||
|
|
||||||
|
|
||||||
|
def receiver_panel_keys(role):
|
||||||
|
require_root_directory(NODE_KEYS)
|
||||||
|
accounts = sorted(NODE_KEYS.glob(f"coulobre-{role}-p-*"))
|
||||||
|
unrestricted = NODE_KEYS / f"coulobre-{role}-request"
|
||||||
|
if unrestricted.exists():
|
||||||
|
accounts.append(unrestricted)
|
||||||
|
fingerprints = set()
|
||||||
|
for account in accounts:
|
||||||
|
for line in read_root_file(account, mode=0o644).splitlines():
|
||||||
|
if not line.strip() or line.lstrip().startswith("#"):
|
||||||
|
continue
|
||||||
|
_, key_type, key = shlex.split(line)
|
||||||
|
if key_type != "ssh-ed25519":
|
||||||
|
raise ValueError("Expected an Ed25519 key for every panel.")
|
||||||
|
digest = hashlib.sha256(
|
||||||
|
base64.b64decode(key, validate=True)
|
||||||
|
).digest()
|
||||||
|
fingerprint = base64.b64encode(digest).decode().rstrip("=")
|
||||||
|
fingerprints.add(f"SHA256:{fingerprint}")
|
||||||
|
if not fingerprints:
|
||||||
|
raise ValueError("No authorized panel keys were found.")
|
||||||
|
return fingerprints
|
||||||
|
|
||||||
|
|
||||||
|
def verify_inventory(role, source):
|
||||||
|
require_root_directory(source.parent)
|
||||||
|
plan = json.loads(read_root_file(source, mode=0o600))
|
||||||
|
if (
|
||||||
|
not isinstance(plan, dict)
|
||||||
|
or set(plan) != {"target", "panels"}
|
||||||
|
or not isinstance(plan["panels"], dict)
|
||||||
|
or set(plan["panels"]) != receiver_panel_keys(role)
|
||||||
|
):
|
||||||
|
raise ValueError("Account for every authorized panel key in the plan.")
|
||||||
|
try:
|
||||||
|
target = version_key(plan["target"])
|
||||||
|
releases = {
|
||||||
|
version_key(release) for release in plan["panels"].values()
|
||||||
|
}
|
||||||
|
except UpdateError as error:
|
||||||
|
raise ValueError(str(error)) from None
|
||||||
|
if len(releases) != 1:
|
||||||
|
raise ValueError("All linked panels must agree on their release.")
|
||||||
|
return plan, target, releases.pop()
|
||||||
|
|
||||||
|
|
||||||
|
def begin_maintenance(role, source):
|
||||||
|
with locked_root_directory(NODE_KEYS):
|
||||||
|
plan, target, panels = verify_inventory(role, source)
|
||||||
|
receiver = version_key(version("coulobre-panel"))
|
||||||
|
if not panels <= receiver <= target or panels == target:
|
||||||
|
raise ValueError(
|
||||||
|
"Use an upgrade target and the current linked panel versions."
|
||||||
|
)
|
||||||
|
write_new_file(
|
||||||
|
maintenance_path(role), json.dumps(plan) + "\n", mode=0o600
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def finish_maintenance(role, source):
|
||||||
|
with locked_root_directory(NODE_KEYS):
|
||||||
|
plan, target, panels = verify_inventory(role, source)
|
||||||
|
receiver = version("coulobre-panel")
|
||||||
|
if not (
|
||||||
|
rollout_target(role) == plan["target"] == receiver
|
||||||
|
and target == panels
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"The receiver and every linked panel must be at the target."
|
||||||
|
)
|
||||||
|
maintenance_path(role).unlink()
|
||||||
@@ -4,6 +4,8 @@ from importlib.metadata import version
|
|||||||
|
|
||||||
PROBE = {"version": 1, "operation": "probe"}
|
PROBE = {"version": 1, "operation": "probe"}
|
||||||
PROBE_BYTES = (json.dumps(PROBE) + "\n").encode()
|
PROBE_BYTES = (json.dumps(PROBE) + "\n").encode()
|
||||||
|
STATUS_PROBE = PROBE | {"version": 2}
|
||||||
|
STATUS_PROBE_BYTES = (json.dumps(STATUS_PROBE) + "\n").encode()
|
||||||
PROBE_LIMIT = 4096
|
PROBE_LIMIT = 4096
|
||||||
|
|
||||||
|
|
||||||
@@ -11,6 +13,44 @@ def probe_identity(role):
|
|||||||
return PROBE | {"role": role, "release": version("coulobre-panel")}
|
return PROBE | {"role": role, "release": version("coulobre-panel")}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_status_probe(body, role):
|
||||||
|
from .release_updates import UpdateError, version_key
|
||||||
|
|
||||||
|
try:
|
||||||
|
if len(body) > PROBE_LIMIT:
|
||||||
|
raise ValueError
|
||||||
|
reply = json.loads(body)
|
||||||
|
if (
|
||||||
|
not isinstance(reply, dict)
|
||||||
|
or type(reply.get("version")) is not int
|
||||||
|
or reply["version"] not in {1, 2}
|
||||||
|
or reply.get("operation") != "probe"
|
||||||
|
or reply.get("role") != role
|
||||||
|
or reply.get("state")
|
||||||
|
not in {"configured", "maintenance", "failed"}
|
||||||
|
):
|
||||||
|
raise ValueError
|
||||||
|
version_key(reply.get("release"))
|
||||||
|
target = reply.get("upgrade_target")
|
||||||
|
if reply["state"] == "maintenance":
|
||||||
|
if reply["version"] != 2:
|
||||||
|
raise ValueError
|
||||||
|
version_key(target)
|
||||||
|
else:
|
||||||
|
target = None
|
||||||
|
except (ValueError, TypeError, UpdateError, RecursionError) as error:
|
||||||
|
raise ValueError(
|
||||||
|
"The receiver returned no trusted release status."
|
||||||
|
) from error
|
||||||
|
return {
|
||||||
|
"role": role,
|
||||||
|
"protocol": reply["version"],
|
||||||
|
"release": reply["release"],
|
||||||
|
"state": reply["state"],
|
||||||
|
"upgrade_target": target,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def check_receiver(role):
|
def check_receiver(role):
|
||||||
if role == "dns":
|
if role == "dns":
|
||||||
from .dns_node_apply import RNDC, ZONE_DIRECTORY, run
|
from .dns_node_apply import RNDC, ZONE_DIRECTORY, run
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
|
from contextlib import nullcontext
|
||||||
|
|
||||||
|
from .receiver_scope import authorized_request
|
||||||
|
|
||||||
MAX_REQUEST_BYTES = 4096
|
MAX_REQUEST_BYTES = 4096
|
||||||
|
|
||||||
@@ -14,6 +17,8 @@ def serve_apply_request(
|
|||||||
include_result=False,
|
include_result=False,
|
||||||
probe_role=None,
|
probe_role=None,
|
||||||
):
|
):
|
||||||
|
from .node_maintenance import rollout_target
|
||||||
|
|
||||||
report = {"version": manifest_version}
|
report = {"version": manifest_version}
|
||||||
try:
|
try:
|
||||||
body = sys.stdin.buffer.read(limit + 1)
|
body = sys.stdin.buffer.read(limit + 1)
|
||||||
@@ -28,16 +33,52 @@ def serve_apply_request(
|
|||||||
and isinstance(payload, dict)
|
and isinstance(payload, dict)
|
||||||
and payload.get("operation") == "probe"
|
and payload.get("operation") == "probe"
|
||||||
):
|
):
|
||||||
from .node_probe import PROBE, check_receiver, probe_identity
|
from .node_probe import (
|
||||||
|
PROBE,
|
||||||
|
STATUS_PROBE,
|
||||||
|
check_receiver,
|
||||||
|
probe_identity,
|
||||||
|
)
|
||||||
|
|
||||||
if payload != PROBE or type(payload.get("version")) is not int:
|
if (
|
||||||
raise ValueError("Expected a version 1 node probe.")
|
payload not in (PROBE, STATUS_PROBE)
|
||||||
report = probe_identity(probe_role)
|
or type(payload.get("version")) is not int
|
||||||
check_receiver(probe_role)
|
):
|
||||||
|
raise ValueError("Expected a supported node probe.")
|
||||||
|
report = probe_identity(probe_role) | {
|
||||||
|
"version": payload["version"]
|
||||||
|
}
|
||||||
|
with authorized_request(probe_role):
|
||||||
|
check_receiver(probe_role)
|
||||||
|
target = rollout_target(probe_role)
|
||||||
|
if target and payload == PROBE:
|
||||||
|
raise ValueError("The receiver is in upgrade maintenance.")
|
||||||
|
if target:
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
report
|
||||||
|
| {
|
||||||
|
"state": "maintenance",
|
||||||
|
"upgrade_target": target,
|
||||||
|
"problem": None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return 0
|
||||||
else:
|
else:
|
||||||
|
if probe_role is not None and rollout_target(probe_role):
|
||||||
|
raise ValueError("The receiver is in upgrade maintenance.")
|
||||||
spec = parse_manifest(payload)
|
spec = parse_manifest(payload)
|
||||||
report = spec.manifest() if identity is None else identity(spec)
|
report = spec.manifest() if identity is None else identity(spec)
|
||||||
result = apply(spec)
|
guard = (
|
||||||
|
nullcontext()
|
||||||
|
if probe_role is None
|
||||||
|
else authorized_request(probe_role, spec)
|
||||||
|
)
|
||||||
|
with guard:
|
||||||
|
if probe_role is not None and rollout_target(probe_role):
|
||||||
|
raise ValueError("The receiver is in upgrade maintenance.")
|
||||||
|
result = apply(spec)
|
||||||
if include_result and result is not None:
|
if include_result and result is not None:
|
||||||
report.update(result)
|
report.update(result)
|
||||||
except (OSError, ValueError) as error:
|
except (OSError, ValueError) as error:
|
||||||
|
|||||||
+162
-8
@@ -1,6 +1,7 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import grp
|
import grp
|
||||||
import ipaddress
|
import ipaddress
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
import pwd
|
import pwd
|
||||||
import re
|
import re
|
||||||
@@ -22,11 +23,23 @@ from .node_files import (
|
|||||||
require_root_directory,
|
require_root_directory,
|
||||||
write_new_file,
|
write_new_file,
|
||||||
)
|
)
|
||||||
|
from .node_maintenance import (
|
||||||
|
NODE_KEYS,
|
||||||
|
begin_maintenance,
|
||||||
|
finish_maintenance,
|
||||||
|
receiver_panel_keys,
|
||||||
|
rollout_target,
|
||||||
|
)
|
||||||
from .node_probe import PROBE_BYTES, PROBE_LIMIT, check_receiver, verify_probe
|
from .node_probe import PROBE_BYTES, PROBE_LIMIT, check_receiver, verify_probe
|
||||||
|
from .receiver_scope import (
|
||||||
|
scope_files,
|
||||||
|
scope_path,
|
||||||
|
scoped_account,
|
||||||
|
scoped_domains,
|
||||||
|
)
|
||||||
from .sftp_keys import read_public_keys
|
from .sftp_keys import read_public_keys
|
||||||
|
|
||||||
PANEL_SSH = Path("/etc/coulobre-remote")
|
PANEL_SSH = Path("/etc/coulobre-remote")
|
||||||
NODE_KEYS = Path("/etc/ssh/coulobre-node-keys")
|
|
||||||
SSH_DROP_IN = Path("/etc/ssh/sshd_config.d/00-coulobre-node-requests.conf")
|
SSH_DROP_IN = Path("/etc/ssh/sshd_config.d/00-coulobre-node-requests.conf")
|
||||||
SYSTEMD = Path("/etc/systemd/system")
|
SYSTEMD = Path("/etc/systemd/system")
|
||||||
COMMAND_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
|
COMMAND_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
|
||||||
@@ -172,7 +185,21 @@ def install_receivers(assets, roles):
|
|||||||
for role in roles:
|
for role in roles:
|
||||||
install_receiver(assets, role)
|
install_receiver(assets, role)
|
||||||
config = assets / "openssh/coulobre-node-requests.conf.example"
|
config = assets / "openssh/coulobre-node-requests.conf.example"
|
||||||
added = put_file(SSH_DROP_IN, config.read_text())
|
desired = config.read_text()
|
||||||
|
original = (
|
||||||
|
read_root_file(SSH_DROP_IN) if SSH_DROP_IN.exists() else None
|
||||||
|
)
|
||||||
|
legacy = (
|
||||||
|
desired.replace(",coulobre-dns-p-*,coulobre-mail-p-*", "")
|
||||||
|
.replace(",coulobre-dns-p-*", "")
|
||||||
|
.replace(",coulobre-mail-p-*", "")
|
||||||
|
)
|
||||||
|
migrated = original == legacy
|
||||||
|
if migrated:
|
||||||
|
replace_configuration(SSH_DROP_IN, desired)
|
||||||
|
added = False
|
||||||
|
else:
|
||||||
|
added = put_file(SSH_DROP_IN, desired)
|
||||||
try:
|
try:
|
||||||
require_root_directory(Path("/run/sshd"), create_mode=0o755)
|
require_root_directory(Path("/run/sshd"), create_mode=0o755)
|
||||||
run("/usr/sbin/sshd", "-t")
|
run("/usr/sbin/sshd", "-t")
|
||||||
@@ -182,6 +209,8 @@ def install_receivers(assets, roles):
|
|||||||
except (OSError, ValueError, subprocess.TimeoutExpired):
|
except (OSError, ValueError, subprocess.TimeoutExpired):
|
||||||
if added:
|
if added:
|
||||||
SSH_DROP_IN.unlink()
|
SSH_DROP_IN.unlink()
|
||||||
|
elif migrated:
|
||||||
|
replace_configuration(SSH_DROP_IN, original)
|
||||||
raise
|
raise
|
||||||
run("systemctl", "daemon-reload")
|
run("systemctl", "daemon-reload")
|
||||||
run(
|
run(
|
||||||
@@ -192,12 +221,13 @@ def install_receivers(assets, roles):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def check_ssh_receiver(role):
|
def check_ssh_receiver(role, account=None):
|
||||||
|
account = account or role.receiver
|
||||||
live = run(
|
live = run(
|
||||||
"/usr/sbin/sshd",
|
"/usr/sbin/sshd",
|
||||||
"-T",
|
"-T",
|
||||||
"-C",
|
"-C",
|
||||||
f"user={role.receiver},host=localhost,addr=127.0.0.1",
|
f"user={account},host=localhost,addr=127.0.0.1",
|
||||||
).decode()
|
).decode()
|
||||||
expected = {
|
expected = {
|
||||||
f"forcecommand {role.relay}",
|
f"forcecommand {role.relay}",
|
||||||
@@ -205,6 +235,8 @@ def check_ssh_receiver(role):
|
|||||||
"authenticationmethods publickey",
|
"authenticationmethods publickey",
|
||||||
"disableforwarding yes",
|
"disableforwarding yes",
|
||||||
"permituserrc no",
|
"permituserrc no",
|
||||||
|
"permituserenvironment no",
|
||||||
|
"permittunnel no",
|
||||||
"permittty no",
|
"permittty no",
|
||||||
"pubkeyauthentication yes",
|
"pubkeyauthentication yes",
|
||||||
"passwordauthentication no",
|
"passwordauthentication no",
|
||||||
@@ -213,8 +245,15 @@ def check_ssh_receiver(role):
|
|||||||
"authorizedkeyscommand none",
|
"authorizedkeyscommand none",
|
||||||
}
|
}
|
||||||
if not expected <= set(live.splitlines()):
|
if not expected <= set(live.splitlines()):
|
||||||
|
raise ValueError(f"Check the effective SSH policy for {account}.")
|
||||||
|
if account != role.receiver and any(
|
||||||
|
line.startswith("acceptenv ")
|
||||||
|
and set(line.split()[1:]) - {"LANG", "LC_*", "COLORTERM", "NO_COLOR"}
|
||||||
|
for line in live.splitlines()
|
||||||
|
):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Check the effective SSH policy for {role.receiver}."
|
"Restrict accepted SSH environment variables to locale and "
|
||||||
|
"terminal color settings."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -229,6 +268,10 @@ def one_public_key(path):
|
|||||||
def authorize_panel(role, key_path):
|
def authorize_panel(role, key_path):
|
||||||
key = one_public_key(key_path)
|
key = one_public_key(key_path)
|
||||||
with locked_root_directory(NODE_KEYS):
|
with locked_root_directory(NODE_KEYS):
|
||||||
|
if rollout_target(role.name):
|
||||||
|
raise ValueError("The receiver is in upgrade maintenance.")
|
||||||
|
if scope_files(role.name):
|
||||||
|
raise ValueError("Use domain-scoped keys on this receiver.")
|
||||||
check_ssh_receiver(role)
|
check_ssh_receiver(role)
|
||||||
destination = NODE_KEYS / role.receiver
|
destination = NODE_KEYS / role.receiver
|
||||||
old = (
|
old = (
|
||||||
@@ -245,6 +288,60 @@ def authorize_panel(role, key_path):
|
|||||||
write_new_file(destination, entry, mode=0o644)
|
write_new_file(destination, entry, mode=0o644)
|
||||||
|
|
||||||
|
|
||||||
|
def authorize_scoped_panel(role, panel, key_path, domains):
|
||||||
|
account = scoped_account(role.name, panel)
|
||||||
|
key = one_public_key(key_path)
|
||||||
|
if not key.startswith("ssh-ed25519 "):
|
||||||
|
raise ValueError("Use an Ed25519 panel public key.")
|
||||||
|
domains = {canonical_domain(domain) for domain in domains}
|
||||||
|
path = scope_path(account)
|
||||||
|
destination = NODE_KEYS / account
|
||||||
|
with locked_root_directory(NODE_KEYS):
|
||||||
|
if rollout_target(role.name):
|
||||||
|
raise ValueError("The receiver is in upgrade maintenance.")
|
||||||
|
legacy = NODE_KEYS / role.receiver
|
||||||
|
if legacy.exists() and any(
|
||||||
|
line.strip() and not line.lstrip().startswith("#")
|
||||||
|
for line in read_root_file(legacy, mode=0o644).splitlines()
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"Remove unrestricted panel keys before enabling scopes."
|
||||||
|
)
|
||||||
|
for other in scope_files(role.name):
|
||||||
|
if other == path:
|
||||||
|
continue
|
||||||
|
assigned = scoped_domains(other)
|
||||||
|
if (
|
||||||
|
domains & assigned
|
||||||
|
or role.name == "dns"
|
||||||
|
and any(
|
||||||
|
domain.endswith(f".{existing}")
|
||||||
|
or existing.endswith(f".{domain}")
|
||||||
|
for domain in domains
|
||||||
|
for existing in assigned
|
||||||
|
)
|
||||||
|
):
|
||||||
|
raise ValueError("A domain overlaps another panel's scope.")
|
||||||
|
scoped_peers = NODE_KEYS.glob(f"coulobre-{role.name}-p-*")
|
||||||
|
for peer in scoped_peers:
|
||||||
|
if peer != destination and any(
|
||||||
|
has_authorized_key(line, key)
|
||||||
|
for line in read_root_file(peer, mode=0o644).splitlines()
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"A panel key may have only one scope per role."
|
||||||
|
)
|
||||||
|
ensure_identity(account, home="/", shell="/bin/sh", group=role.group)
|
||||||
|
check_ssh_receiver(role, account)
|
||||||
|
entry = f'command="{role.relay}",restrict {key}\n'
|
||||||
|
contents = json.dumps(sorted(domains)) + "\n"
|
||||||
|
if path.exists():
|
||||||
|
scoped_domains(path)
|
||||||
|
put_file(destination, entry)
|
||||||
|
replace_configuration(path, contents, mode=0o600)
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
def has_authorized_key(line, key):
|
def has_authorized_key(line, key):
|
||||||
if line.lstrip().startswith("#"):
|
if line.lstrip().startswith("#"):
|
||||||
return False
|
return False
|
||||||
@@ -315,10 +412,14 @@ def normalize_host(host):
|
|||||||
return canonical_domain(host)
|
return canonical_domain(host)
|
||||||
|
|
||||||
|
|
||||||
def ssh_setup(assets, role, host, port):
|
def ssh_setup(assets, role, host, port, *, scope=None):
|
||||||
config = (
|
config = (
|
||||||
assets / f"openssh/{role.name}-node-client.conf.example"
|
assets / f"openssh/{role.name}-node-client.conf.example"
|
||||||
).read_text()
|
).read_text()
|
||||||
|
if scope is not None:
|
||||||
|
config = config.replace(
|
||||||
|
f"User {role.receiver}", f"User {scoped_account(role.name, scope)}"
|
||||||
|
)
|
||||||
return config.replace(
|
return config.replace(
|
||||||
f"HostName {role.name}.example.org", f"HostName {host}"
|
f"HostName {role.name}.example.org", f"HostName {host}"
|
||||||
).replace("Port 22", f"Port {port}")
|
).replace("Port 22", f"Port {port}")
|
||||||
@@ -367,12 +468,12 @@ def stage_ssh_settings(role, config, known_hosts, group):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def enrol_panel(assets, role, host, port, host_key):
|
def enrol_panel(assets, role, host, port, host_key, *, scope=None):
|
||||||
host = normalize_host(host)
|
host = normalize_host(host)
|
||||||
key = one_public_key(host_key)
|
key = one_public_key(host_key)
|
||||||
entry = host if port == 22 else f"[{host}]:{port}"
|
entry = host if port == 22 else f"[{host}]:{port}"
|
||||||
known_hosts = f"{entry} {key}\n"
|
known_hosts = f"{entry} {key}\n"
|
||||||
config = ssh_setup(assets, role, host, port)
|
config = ssh_setup(assets, role, host, port, scope=scope)
|
||||||
_, group = prepare_panel(role)
|
_, group = prepare_panel(role)
|
||||||
require_root_directory(SYSTEMD)
|
require_root_directory(SYSTEMD)
|
||||||
with locked_root_directory(PANEL_SSH):
|
with locked_root_directory(PANEL_SSH):
|
||||||
@@ -438,6 +539,22 @@ def ssh_port(value):
|
|||||||
return port
|
return port
|
||||||
|
|
||||||
|
|
||||||
|
def check_receiver_drained(role):
|
||||||
|
active = run(
|
||||||
|
"systemctl",
|
||||||
|
"list-units",
|
||||||
|
"--state=active,activating,deactivating",
|
||||||
|
"--no-legend",
|
||||||
|
"--plain",
|
||||||
|
f"{role.unit}.socket",
|
||||||
|
f"{role.unit}@*.service",
|
||||||
|
)
|
||||||
|
if active.strip():
|
||||||
|
raise ValueError(
|
||||||
|
"Stop the receiver socket and let its requests drain."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def main(argv=None):
|
def main(argv=None):
|
||||||
parser = argparse.ArgumentParser(prog="coulobre-node-setup")
|
parser = argparse.ArgumentParser(prog="coulobre-node-setup")
|
||||||
parser.add_argument("--source", type=Path, default=Path.cwd())
|
parser.add_argument("--source", type=Path, default=Path.cwd())
|
||||||
@@ -449,7 +566,17 @@ def main(argv=None):
|
|||||||
for command, help_text in (
|
for command, help_text in (
|
||||||
("prepare-panel", "Prepare and print the panel's public SSH key."),
|
("prepare-panel", "Prepare and print the panel's public SSH key."),
|
||||||
("authorize-panel", "Authorize a panel public key on this receiver."),
|
("authorize-panel", "Authorize a panel public key on this receiver."),
|
||||||
|
(
|
||||||
|
"authorize-scoped-panel",
|
||||||
|
"Assign exact domains to one panel identity.",
|
||||||
|
),
|
||||||
("check-receiver", "Check the service configuration on this node."),
|
("check-receiver", "Check the service configuration on this node."),
|
||||||
|
("list-panels", "List the authorized panel key fingerprints."),
|
||||||
|
("begin-maintenance", "Stage a verified receiver upgrade plan."),
|
||||||
|
(
|
||||||
|
"finish-maintenance",
|
||||||
|
"Verify the final plan and resume the receiver.",
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"enrol-panel",
|
"enrol-panel",
|
||||||
"Verify and install a remote relay on the panel host.",
|
"Verify and install a remote relay on the panel host.",
|
||||||
@@ -463,10 +590,17 @@ def main(argv=None):
|
|||||||
action.add_argument("role", choices=ROLES)
|
action.add_argument("role", choices=ROLES)
|
||||||
if command == "authorize-panel":
|
if command == "authorize-panel":
|
||||||
action.add_argument("public_key", type=Path)
|
action.add_argument("public_key", type=Path)
|
||||||
|
if command == "authorize-scoped-panel":
|
||||||
|
action.add_argument("panel")
|
||||||
|
action.add_argument("public_key", type=Path)
|
||||||
|
action.add_argument("domains", nargs="+")
|
||||||
|
if command in {"begin-maintenance", "finish-maintenance"}:
|
||||||
|
action.add_argument("inventory", type=Path)
|
||||||
if command == "enrol-panel":
|
if command == "enrol-panel":
|
||||||
action.add_argument("host")
|
action.add_argument("host")
|
||||||
action.add_argument("host_key", type=Path)
|
action.add_argument("host_key", type=Path)
|
||||||
action.add_argument("--port", type=ssh_port, default=22)
|
action.add_argument("--port", type=ssh_port, default=22)
|
||||||
|
action.add_argument("--scope")
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
if os.geteuid() != 0:
|
if os.geteuid() != 0:
|
||||||
parser.exit(1, "coulobre-node-setup: Run this command as root.\n")
|
parser.exit(1, "coulobre-node-setup: Run this command as root.\n")
|
||||||
@@ -489,9 +623,28 @@ def main(argv=None):
|
|||||||
elif args.command == "authorize-panel":
|
elif args.command == "authorize-panel":
|
||||||
authorize_panel(role, args.public_key)
|
authorize_panel(role, args.public_key)
|
||||||
print(f"Authorized the panel key for the {role.name} receiver.")
|
print(f"Authorized the panel key for the {role.name} receiver.")
|
||||||
|
elif args.command == "authorize-scoped-panel":
|
||||||
|
account = authorize_scoped_panel(
|
||||||
|
role, args.panel, args.public_key, args.domains
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
f"Authorized {account}. Use --scope {args.panel} on the panel."
|
||||||
|
)
|
||||||
elif args.command == "check-receiver":
|
elif args.command == "check-receiver":
|
||||||
check_receiver(role.name)
|
check_receiver(role.name)
|
||||||
print(f"The local {role.name} services are ready.")
|
print(f"The local {role.name} services are ready.")
|
||||||
|
elif args.command == "list-panels":
|
||||||
|
print("\n".join(sorted(receiver_panel_keys(role.name))))
|
||||||
|
elif args.command == "begin-maintenance":
|
||||||
|
check_ssh_receiver(role)
|
||||||
|
check_receiver_drained(role)
|
||||||
|
begin_maintenance(role.name, args.inventory)
|
||||||
|
print(f"The {role.name} receiver is in upgrade maintenance.")
|
||||||
|
elif args.command == "finish-maintenance":
|
||||||
|
check_ssh_receiver(role)
|
||||||
|
check_receiver(role.name)
|
||||||
|
finish_maintenance(role.name, args.inventory)
|
||||||
|
print(f"The {role.name} receiver is accepting requests.")
|
||||||
elif args.command == "enrol-panel":
|
elif args.command == "enrol-panel":
|
||||||
enrol_panel(
|
enrol_panel(
|
||||||
release_assets(args.source),
|
release_assets(args.source),
|
||||||
@@ -499,6 +652,7 @@ def main(argv=None):
|
|||||||
args.host,
|
args.host,
|
||||||
args.port,
|
args.port,
|
||||||
args.host_key,
|
args.host_key,
|
||||||
|
scope=args.scope,
|
||||||
)
|
)
|
||||||
print(
|
print(
|
||||||
f"Verified the {role.name} receiver. "
|
f"Verified the {role.name} receiver. "
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import pwd
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import stat
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
from .domain_names import canonical_domain
|
||||||
|
from .node_files import (
|
||||||
|
locked_root_directory,
|
||||||
|
read_root_file,
|
||||||
|
require_root_directory,
|
||||||
|
)
|
||||||
|
from .node_maintenance import NODE_KEYS, rollout_target
|
||||||
|
|
||||||
|
LOCAL_WORKERS = {
|
||||||
|
"dns": "coulobre-dns-publisher",
|
||||||
|
"mail": "coulobre-mail-provisioner",
|
||||||
|
}
|
||||||
|
MAIL_SERVICE_PEERS = {
|
||||||
|
"coulobre-mail-archive-backup",
|
||||||
|
"coulobre-mail-archive-restore",
|
||||||
|
"coulobre-mail-credential-request",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def scoped_account(role, panel):
|
||||||
|
if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,11}", panel):
|
||||||
|
raise ValueError(
|
||||||
|
"Use 1 to 12 lowercase letters, digits or hyphens for the panel."
|
||||||
|
)
|
||||||
|
return f"coulobre-{role}-p-{panel}"
|
||||||
|
|
||||||
|
|
||||||
|
def scope_files(role):
|
||||||
|
return sorted(NODE_KEYS.glob(f".scope-coulobre-{role}-p-*.json"))
|
||||||
|
|
||||||
|
|
||||||
|
def scope_path(account):
|
||||||
|
return NODE_KEYS / f".scope-{account}.json"
|
||||||
|
|
||||||
|
|
||||||
|
def scoped_domains(path):
|
||||||
|
require_root_directory(path.parent)
|
||||||
|
domains = json.loads(read_root_file(path, mode=0o600))
|
||||||
|
if (
|
||||||
|
not isinstance(domains, list)
|
||||||
|
or not domains
|
||||||
|
or any(
|
||||||
|
not isinstance(domain, str) or canonical_domain(domain) != domain
|
||||||
|
for domain in domains
|
||||||
|
)
|
||||||
|
):
|
||||||
|
raise ValueError("The receiver has an invalid domain scope.")
|
||||||
|
return set(domains)
|
||||||
|
|
||||||
|
|
||||||
|
def socket_peer():
|
||||||
|
try:
|
||||||
|
descriptor = sys.stdin.fileno()
|
||||||
|
except (AttributeError, OSError, ValueError):
|
||||||
|
return None
|
||||||
|
if type(descriptor) is not int or not stat.S_ISSOCK(
|
||||||
|
os.fstat(descriptor).st_mode
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
with socket.fromfd(descriptor, socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||||
|
credentials = peer.getsockopt(
|
||||||
|
socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")
|
||||||
|
)
|
||||||
|
_, uid, _ = struct.unpack("3i", credentials)
|
||||||
|
try:
|
||||||
|
return pwd.getpwuid(uid).pw_name
|
||||||
|
except KeyError as error:
|
||||||
|
raise ValueError(
|
||||||
|
"The receiver could not identify the peer."
|
||||||
|
) from error
|
||||||
|
|
||||||
|
|
||||||
|
def manifest_domain(spec):
|
||||||
|
manifest = spec.manifest()
|
||||||
|
for field in ("mailbox", "resource"):
|
||||||
|
if field in manifest:
|
||||||
|
manifest = manifest[field]
|
||||||
|
break
|
||||||
|
return manifest.get("domain")
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def authorized_request(role, spec=None):
|
||||||
|
peer = socket_peer()
|
||||||
|
if peer in (None, "root", LOCAL_WORKERS[role]):
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
with locked_root_directory(NODE_KEYS, shared=True):
|
||||||
|
if peer == f"coulobre-{role}-request":
|
||||||
|
if scope_files(role):
|
||||||
|
raise ValueError(
|
||||||
|
"Use a domain-scoped panel key for this receiver."
|
||||||
|
)
|
||||||
|
elif peer.startswith(f"coulobre-{role}-p-"):
|
||||||
|
domains = scoped_domains(scope_path(peer))
|
||||||
|
if spec is not None and manifest_domain(spec) not in domains:
|
||||||
|
raise ValueError(
|
||||||
|
"The panel key is not assigned to this domain."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise ValueError("The peer is not authorized for this receiver.")
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def check_mail_service_peer():
|
||||||
|
if socket_peer() in MAIL_SERVICE_PEERS and (
|
||||||
|
scope_files("mail") or rollout_target("mail")
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"The remote mail service is unavailable on this receiver."
|
||||||
|
)
|
||||||
@@ -6,6 +6,7 @@ from .credential_rotation import valid_generation
|
|||||||
from .database_node import DEFAULT_SOCKET, DatabaseSpec
|
from .database_node import DEFAULT_SOCKET, DatabaseSpec
|
||||||
from .mail_node import MailboxSpec
|
from .mail_node import MailboxSpec
|
||||||
from .node_requests import serve_apply_request
|
from .node_requests import serve_apply_request
|
||||||
|
from .receiver_scope import check_mail_service_peer
|
||||||
|
|
||||||
REQUEST_VERSION = 1
|
REQUEST_VERSION = 1
|
||||||
CREDENTIAL_SOCKET = "/run/coulobre-service-credentials.sock"
|
CREDENTIAL_SOCKET = "/run/coulobre-service-credentials.sock"
|
||||||
@@ -98,6 +99,8 @@ def main(argv=None):
|
|||||||
|
|
||||||
def parse(payload):
|
def parse(payload):
|
||||||
request = ServiceCredentialRequest.from_manifest(payload)
|
request = ServiceCredentialRequest.from_manifest(payload)
|
||||||
|
if request.kind == "mailbox":
|
||||||
|
check_mail_service_peer()
|
||||||
if args.mailbox_only and request.kind != "mailbox":
|
if args.mailbox_only and request.kind != "mailbox":
|
||||||
raise ValueError("This node handles mailbox requests only.")
|
raise ValueError("This node handles mailbox requests only.")
|
||||||
return request
|
return request
|
||||||
|
|||||||
@@ -85,10 +85,13 @@ MIDDLEWARE = [
|
|||||||
"django.middleware.common.CommonMiddleware",
|
"django.middleware.common.CommonMiddleware",
|
||||||
"django.middleware.csrf.CsrfViewMiddleware",
|
"django.middleware.csrf.CsrfViewMiddleware",
|
||||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||||
|
"coulobre.hosting.panel_sessions.PanelSessionMiddleware",
|
||||||
"django_otp.middleware.OTPMiddleware",
|
"django_otp.middleware.OTPMiddleware",
|
||||||
"coulobre.hosting.sign_in.PrivilegedFactorMiddleware",
|
"coulobre.hosting.sign_in.PrivilegedFactorMiddleware",
|
||||||
"django.contrib.messages.middleware.MessageMiddleware",
|
"django.contrib.messages.middleware.MessageMiddleware",
|
||||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||||
|
"coulobre.hosting.panel_roles.PanelRoleMiddleware",
|
||||||
|
"coulobre.hosting.installation_features.FeaturePolicyMiddleware",
|
||||||
"coulobre.hosting.impersonation.CustomerImpersonationMiddleware",
|
"coulobre.hosting.impersonation.CustomerImpersonationMiddleware",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest import TestCase
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from . import linked_updates, local_update, node_maintenance
|
||||||
|
from .node_probe import PROBE, STATUS_PROBE, parse_status_probe
|
||||||
|
from .node_requests import serve_apply_request
|
||||||
|
from .release_updates import UpdateError
|
||||||
|
|
||||||
|
ORIGINAL = "0.11.0rc1"
|
||||||
|
TARGET = "0.11.1rc1"
|
||||||
|
|
||||||
|
|
||||||
|
def receiver(role, release, *, protocol=2, state="maintenance", target=TARGET):
|
||||||
|
return {
|
||||||
|
"version": protocol,
|
||||||
|
"operation": "probe",
|
||||||
|
"role": role,
|
||||||
|
"release": release,
|
||||||
|
"state": state,
|
||||||
|
"upgrade_target": target,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class LinkedUpdateTests(TestCase):
|
||||||
|
def test_only_target_version_in_maintenance_enables_update(self):
|
||||||
|
def staged(body):
|
||||||
|
return linked_updates.staged_for_release(
|
||||||
|
parse_status_probe(json.dumps(body).encode(), "dns"), TARGET
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(staged(receiver("dns", TARGET)))
|
||||||
|
self.assertFalse(staged(receiver("dns", ORIGINAL)))
|
||||||
|
self.assertFalse(staged(receiver("dns", TARGET, state="configured")))
|
||||||
|
self.assertFalse(staged(receiver("dns", TARGET, target="0.11.2rc1")))
|
||||||
|
self.assertFalse(
|
||||||
|
staged(receiver("dns", TARGET, protocol=1, state="configured"))
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_roster_requires_every_shared_panel_before_leaving_maintenance(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
with TemporaryDirectory() as root:
|
||||||
|
inventory = Path(root) / "inventory.json"
|
||||||
|
state = Path(root) / "keys"
|
||||||
|
state.mkdir()
|
||||||
|
keys = {"SHA256:panel-one", "SHA256:panel-two"}
|
||||||
|
|
||||||
|
def write_plan(panels):
|
||||||
|
inventory.write_text(
|
||||||
|
json.dumps({"target": TARGET, "panels": panels})
|
||||||
|
)
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch.object(node_maintenance, "NODE_KEYS", state),
|
||||||
|
patch.object(node_maintenance, "locked_root_directory"),
|
||||||
|
patch.object(node_maintenance, "require_root_directory"),
|
||||||
|
patch.object(
|
||||||
|
node_maintenance,
|
||||||
|
"read_root_file",
|
||||||
|
side_effect=Path.read_text,
|
||||||
|
) as read,
|
||||||
|
patch.object(
|
||||||
|
node_maintenance, "receiver_panel_keys", return_value=keys
|
||||||
|
),
|
||||||
|
patch.object(
|
||||||
|
node_maintenance, "version", return_value=ORIGINAL
|
||||||
|
) as release,
|
||||||
|
):
|
||||||
|
read.side_effect = lambda path, mode: path.read_text()
|
||||||
|
write_plan({key: ORIGINAL for key in keys})
|
||||||
|
node_maintenance.begin_maintenance("dns", inventory)
|
||||||
|
self.assertEqual(
|
||||||
|
node_maintenance.rollout_target("dns"), TARGET
|
||||||
|
)
|
||||||
|
release.return_value = TARGET
|
||||||
|
|
||||||
|
write_plan({"SHA256:panel-one": TARGET})
|
||||||
|
with self.assertRaisesRegex(
|
||||||
|
ValueError, "every authorized panel"
|
||||||
|
):
|
||||||
|
node_maintenance.finish_maintenance("dns", inventory)
|
||||||
|
|
||||||
|
write_plan(
|
||||||
|
{"SHA256:panel-one": TARGET, "SHA256:panel-two": ORIGINAL}
|
||||||
|
)
|
||||||
|
with self.assertRaisesRegex(ValueError, "agree"):
|
||||||
|
node_maintenance.finish_maintenance("dns", inventory)
|
||||||
|
self.assertEqual(
|
||||||
|
node_maintenance.rollout_target("dns"), TARGET
|
||||||
|
)
|
||||||
|
|
||||||
|
write_plan({key: TARGET for key in keys})
|
||||||
|
node_maintenance.finish_maintenance("dns", inventory)
|
||||||
|
self.assertIsNone(node_maintenance.rollout_target("dns"))
|
||||||
|
|
||||||
|
def test_unknown_receiver_blocks_root_update_until_it_reports_target(self):
|
||||||
|
nodes = [
|
||||||
|
{
|
||||||
|
"protocol": 2,
|
||||||
|
"state": "maintenance",
|
||||||
|
"release": TARGET,
|
||||||
|
"upgrade_target": TARGET,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"protocol": None,
|
||||||
|
"state": "unavailable",
|
||||||
|
"release": None,
|
||||||
|
"upgrade_target": None,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
local_update,
|
||||||
|
"installation_plan",
|
||||||
|
return_value={"hostname": "panel.example.test"},
|
||||||
|
),
|
||||||
|
patch.object(local_update, "linked_status", return_value=nodes),
|
||||||
|
):
|
||||||
|
with self.assertRaisesRegex(UpdateError, "every linked receiver"):
|
||||||
|
local_update.check_installation(TARGET)
|
||||||
|
nodes[1].update(nodes[0])
|
||||||
|
self.assertEqual(
|
||||||
|
local_update.check_installation(TARGET), "panel.example.test"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_receiver_preserves_probe_and_blocks_provisioning_in_maintenance(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
parse = Mock()
|
||||||
|
apply = Mock()
|
||||||
|
inputs = [
|
||||||
|
STATUS_PROBE,
|
||||||
|
PROBE,
|
||||||
|
{"kind": "bind9_zone", "domain": "example.test", "version": 1},
|
||||||
|
]
|
||||||
|
expected = ["maintenance", "failed", "failed"]
|
||||||
|
for payload, outcome in zip(inputs, expected, strict=True):
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
"coulobre.node_requests.sys.stdin",
|
||||||
|
buffer=io.BytesIO(json.dumps(payload).encode()),
|
||||||
|
),
|
||||||
|
patch("sys.stdout", new_callable=io.StringIO) as output,
|
||||||
|
patch("coulobre.node_probe.check_receiver"),
|
||||||
|
patch("coulobre.node_probe.version", return_value=TARGET),
|
||||||
|
patch(
|
||||||
|
"coulobre.node_maintenance.rollout_target",
|
||||||
|
return_value=TARGET,
|
||||||
|
),
|
||||||
|
):
|
||||||
|
result = serve_apply_request(1, parse, apply, probe_role="dns")
|
||||||
|
self.assertEqual(result, int(outcome == "failed"))
|
||||||
|
self.assertEqual(
|
||||||
|
json.loads(output.getvalue())["state"], outcome
|
||||||
|
)
|
||||||
|
parse.assert_not_called()
|
||||||
|
apply.assert_not_called()
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import pwd
|
||||||
|
import socket
|
||||||
|
from contextlib import nullcontext
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest import TestCase
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from . import node_maintenance, node_setup, receiver_scope
|
||||||
|
from .dns_node import DnsZone
|
||||||
|
from .mail_node import MailboxQuotaUpdate, MailboxSpec
|
||||||
|
from .mail_policy import MailRouting
|
||||||
|
from .mail_queue import MailQueueRequest
|
||||||
|
from .node_requests import serve_apply_request
|
||||||
|
from .node_retirement import RetirementRequest
|
||||||
|
from .service_access import ServiceAccessRequest
|
||||||
|
|
||||||
|
|
||||||
|
def check_request(role, spec=None):
|
||||||
|
with receiver_scope.authorized_request(role, spec):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ReceiverScopeTests(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
lock = patch.object(
|
||||||
|
receiver_scope, "locked_root_directory", return_value=nullcontext()
|
||||||
|
)
|
||||||
|
lock.start()
|
||||||
|
self.addCleanup(lock.stop)
|
||||||
|
|
||||||
|
def test_unix_peer_identity_comes_from_the_kernel(self):
|
||||||
|
left, right = socket.socketpair()
|
||||||
|
with (
|
||||||
|
left,
|
||||||
|
right,
|
||||||
|
patch(
|
||||||
|
"coulobre.receiver_scope.sys.stdin.fileno",
|
||||||
|
return_value=left.fileno(),
|
||||||
|
),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
peer = receiver_scope.socket_peer()
|
||||||
|
except PermissionError:
|
||||||
|
self.skipTest("SO_PEERCRED is unavailable in this sandbox")
|
||||||
|
self.assertEqual(peer, pwd.getpwuid(os.getuid()).pw_name)
|
||||||
|
|
||||||
|
def test_exact_domain_applies_to_all_managed_mail_operations(self):
|
||||||
|
mailbox = MailboxSpec("alpha.example.test", "sales")
|
||||||
|
requests = (
|
||||||
|
mailbox,
|
||||||
|
MailboxQuotaUpdate(mailbox),
|
||||||
|
MailQueueRequest(mailbox.domain),
|
||||||
|
MailRouting(mailbox.domain, {}),
|
||||||
|
ServiceAccessRequest(mailbox, True),
|
||||||
|
RetirementRequest(mailbox, str(uuid4())),
|
||||||
|
)
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
receiver_scope,
|
||||||
|
"socket_peer",
|
||||||
|
return_value="coulobre-mail-p-alpha",
|
||||||
|
),
|
||||||
|
patch.object(
|
||||||
|
receiver_scope, "scoped_domains", return_value={mailbox.domain}
|
||||||
|
),
|
||||||
|
):
|
||||||
|
for request in requests:
|
||||||
|
check_request("mail", request)
|
||||||
|
for domain in ("beta.example.test", "sub.alpha.example.test"):
|
||||||
|
with self.assertRaisesRegex(ValueError, "not assigned"):
|
||||||
|
check_request("mail", MailQueueRequest(domain))
|
||||||
|
|
||||||
|
def test_scope_is_enforced_before_dispatching_dns_operations(self):
|
||||||
|
zone = DnsZone(
|
||||||
|
"beta.example.test",
|
||||||
|
1,
|
||||||
|
("ns.example.test",),
|
||||||
|
"hostmaster.example.test",
|
||||||
|
)
|
||||||
|
apply = Mock()
|
||||||
|
request = RetirementRequest(zone, str(uuid4()))
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
receiver_scope,
|
||||||
|
"socket_peer",
|
||||||
|
return_value="coulobre-dns-p-alpha",
|
||||||
|
),
|
||||||
|
patch.object(
|
||||||
|
receiver_scope,
|
||||||
|
"scoped_domains",
|
||||||
|
return_value={"alpha.example.test"},
|
||||||
|
),
|
||||||
|
patch(
|
||||||
|
"coulobre.node_requests.sys.stdin",
|
||||||
|
buffer=io.BytesIO(json.dumps(request.manifest()).encode()),
|
||||||
|
),
|
||||||
|
patch("sys.stdout", new_callable=io.StringIO) as output,
|
||||||
|
):
|
||||||
|
result = serve_apply_request(
|
||||||
|
1, lambda data: request, apply, probe_role="dns"
|
||||||
|
)
|
||||||
|
self.assertEqual(result, 1)
|
||||||
|
self.assertIn(
|
||||||
|
"not assigned", json.loads(output.getvalue())["problem"]
|
||||||
|
)
|
||||||
|
apply.assert_not_called()
|
||||||
|
|
||||||
|
def test_legacy_and_service_ssh_accounts_cannot_bypass_scoped_mail(self):
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
receiver_scope,
|
||||||
|
"socket_peer",
|
||||||
|
return_value="coulobre-mail-request",
|
||||||
|
) as peer,
|
||||||
|
patch.object(
|
||||||
|
receiver_scope, "scope_files", return_value=[Path("/scope")]
|
||||||
|
),
|
||||||
|
):
|
||||||
|
with self.assertRaisesRegex(ValueError, "domain-scoped"):
|
||||||
|
check_request("mail")
|
||||||
|
peer.return_value = "coulobre-dns-p-alpha"
|
||||||
|
with self.assertRaisesRegex(ValueError, "not authorized"):
|
||||||
|
check_request("mail")
|
||||||
|
for name in receiver_scope.MAIL_SERVICE_PEERS:
|
||||||
|
peer.return_value = name
|
||||||
|
with self.assertRaisesRegex(ValueError, "unavailable"):
|
||||||
|
receiver_scope.check_mail_service_peer()
|
||||||
|
peer.return_value = "root"
|
||||||
|
check_request("mail")
|
||||||
|
receiver_scope.check_mail_service_peer()
|
||||||
|
|
||||||
|
def test_scopes_reject_overlap_and_record_both_keys(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
role = node_setup.ROLES["dns"]
|
||||||
|
key = Path("public-key")
|
||||||
|
with (
|
||||||
|
TemporaryDirectory() as scratch,
|
||||||
|
patch.object(
|
||||||
|
node_setup, "locked_root_directory", return_value=nullcontext()
|
||||||
|
),
|
||||||
|
patch.object(
|
||||||
|
node_setup,
|
||||||
|
"one_public_key",
|
||||||
|
side_effect=(
|
||||||
|
"ssh-ed25519 YWJj",
|
||||||
|
"ssh-ed25519 ZGVm",
|
||||||
|
"ssh-ed25519 ZGVm",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
patch.object(node_setup, "check_ssh_receiver"),
|
||||||
|
patch.object(node_setup, "ensure_identity"),
|
||||||
|
patch.object(node_setup, "rollout_target", return_value=None),
|
||||||
|
):
|
||||||
|
root = Path(scratch)
|
||||||
|
|
||||||
|
def read(path, *, mode=None):
|
||||||
|
return path.read_text()
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch.object(node_setup, "NODE_KEYS", root),
|
||||||
|
patch("coulobre.node_files.os.fchown"),
|
||||||
|
patch.object(receiver_scope, "NODE_KEYS", root),
|
||||||
|
patch.object(node_maintenance, "NODE_KEYS", root),
|
||||||
|
patch.object(receiver_scope, "require_root_directory"),
|
||||||
|
patch.object(node_maintenance, "require_root_directory"),
|
||||||
|
patch.object(
|
||||||
|
receiver_scope, "read_root_file", side_effect=read
|
||||||
|
),
|
||||||
|
patch.object(node_setup, "read_root_file", side_effect=read),
|
||||||
|
patch.object(
|
||||||
|
node_maintenance, "read_root_file", side_effect=read
|
||||||
|
),
|
||||||
|
):
|
||||||
|
node_setup.authorize_scoped_panel(
|
||||||
|
role, "one", key, ["alpha.example.test"]
|
||||||
|
)
|
||||||
|
with self.assertRaisesRegex(ValueError, "overlaps"):
|
||||||
|
node_setup.authorize_scoped_panel(
|
||||||
|
role, "two", key, ["sub.alpha.example.test"]
|
||||||
|
)
|
||||||
|
node_setup.authorize_scoped_panel(
|
||||||
|
role, "two", key, ["beta.example.test"]
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
len(node_maintenance.receiver_panel_keys(role.name)), 2
|
||||||
|
)
|
||||||
Reference in new issue
Block a user