Compare commits

...
24 Commits
Author SHA1 Message Date
parkel 0b93754e4c Configure and monitor off-site copies in the hosting panel
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 16:14:55 +01:00
parkel ab16c9db62 Queue off-site transfers and protect their local sources 2026-11-22 16:14:55 +01:00
parkel 6b78db3684 Transfer and verify encrypted account archives through restic 2026-11-22 16:14:55 +01:00
parkel af58151ee2 Merge pull request 'Schedule jobs for hosted websites' (#104) from feature/website-scheduled-jobs into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #104
2026-11-22 16:04:27 +01:00
parkel 8e17527ab0 Allow the receiver to terminate overdue website jobs
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 15:42:39 +01:00
parkel a01f318330 Use the existing node protocol for job requests 2026-11-22 15:39:49 +01:00
parkel 30f19727c5 Expose scheduled website jobs in the hosting panel 2026-11-22 15:38:27 +01:00
parkel 92fea45f84 Schedule website jobs with hosting plan limits and run tracking 2026-11-22 15:38:27 +01:00
parkel c944f9cb23 Run scheduled jobs under the provisioned website identity 2026-11-22 15:38:27 +01:00
parkel 539569ccb7 Merge pull request 'Add a browser file manager for websites' (#103) from feature/website-file-manager into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #103
2026-11-22 15:27:37 +01:00
parkel 4fdb4d29c5 Keep file actions readable on smaller screens
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 12:39:52 +01:00
parkel 9d97d4993b Keep the site identity switch available under systemd 2026-11-22 12:36:19 +01:00
parkel 19ed42083a Add the website file manager to the panel 2026-11-22 12:30:53 +01:00
parkel d54e3924ac Add a scoped web-node service for website files 2026-11-22 12:30:53 +01:00
parkel 651ee0fbe1 Merge pull request 'Host independent websites within a hosting account' (#102) from feature/independent-websites into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #102
2026-11-22 12:17:44 +01:00
parkel db62940063 Document and verify independent website workflows
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 12:10:07 +01:00
parkel 86d91303d4 Manage independent websites and their account lifecycle 2026-11-22 12:06:10 +01:00
parkel bd88b64ca6 Give independent websites separate node and archive identities 2026-11-22 12:06:10 +01:00
parkel 526106b7a0 Merge pull request 'Let resellers onboard customers and provision hosting resources' (#101) from feature/reseller-customer-onboarding into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #101
2026-11-22 11:53:09 +01:00
parkel 98bf8e127b Document and verify reseller account boundaries
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 11:43:42 +01:00
parkel 2846e83644 Delegate customer onboarding and provisioning to resellers 2026-11-22 11:43:42 +01:00
parkel 957979c00e Merge pull request 'Protect panel sign-in and customer password recovery' (#99) from feature/protect-panel-sign-in into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #99
2026-11-22 11:36:02 +01:00
parkel 58f589343d Document and verify panel authentication workflows
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-22 11:30:58 +01:00
parkel 2e9caf5498 Protect privileged sign-in and customer password recovery 2026-11-22 11:30:58 +01:00
102 changed files with 7754 additions and 168 deletions

No files matched your search

+5
View File
@@ -5,6 +5,7 @@ RequestHeader unset X-Forwarded-Protocol
RequestHeader unset X-Forwarded-Ssl
RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-For "expr=%{REMOTE_ADDR}"
RequestHeader set X-Coulobre-Client-IP "expr=%{REMOTE_ADDR}"
ProxyPass /static/ !
Alias /static/ /var/www/coulobre-panel-static/
@@ -14,5 +15,9 @@ Alias /static/ /var/www/coulobre-panel-static/
Require all granted
</Directory>
<LocationMatch "^/accounts/[0-9]+/(websites/[0-9]+/)?files/$">
LimitRequestBody 68157440
</LocationMatch>
ProxyPass / "unix:/run/coulobre-panel/panel.sock|http://localhost/"
ProxyPassReverse / http://localhost/
+13
View File
@@ -1,6 +1,16 @@
DJANGO_SETTINGS_MODULE=coulobre.settings
COULOBRE_ALLOWED_HOSTS=panel.example.net
COULOBRE_HTTPS_PROXY=1
COULOBRE_REQUIRE_PRIVILEGED_MFA=1
COULOBRE_TRUST_APACHE_CLIENT_IP=1
# Set an SMTP relay for email verification and customer password resets.
# COULOBRE_SMTP_HOST=smtp.example.net
# COULOBRE_SMTP_PORT=587
# COULOBRE_SMTP_USER=
# COULOBRE_SMTP_PASSWORD=
# COULOBRE_SMTP_STARTTLS=1
# COULOBRE_EMAIL_FROM=panel@example.net
# COULOBRE_PASSWORD_RESET_ORIGIN=https://panel.example.net
COULOBRE_STATIC_ROOT=/var/www/coulobre-panel-static
COULOBRE_SECRET_KEY=
COULOBRE_DB_NAME=coulobre_panel
@@ -12,6 +22,8 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_WEB_ACTIVATION=1
# COULOBRE_LOCAL_WEB_HTTPS=1
# COULOBRE_LOCAL_WEB_SFTP=1
# COULOBRE_WEB_FILE_MANAGER=1
# COULOBRE_WEBSITE_JOBS=1
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1
# These two switches also enable provisioners using the SSH service drop-ins.
# COULOBRE_LOCAL_DNS_PUBLISHING=1
@@ -38,6 +50,7 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1
# COULOBRE_REMOTE_ACCOUNT_BACKUP_MAIL=1
# COULOBRE_LOCAL_BACKUP_RETENTION=1
# COULOBRE_OFFSITE_BACKUP_DESTINATIONS='{"vault":"Off-site vault"}'
# COULOBRE_LOCAL_WEBSITE_RESTORE=1
# COULOBRE_LOCAL_DATABASE_RESTORE=1
# COULOBRE_LOCAL_MAILBOX_RESTORE=1
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre off-site backup transfer socket
[Socket]
ListenStream=/run/coulobre-account-offsite.sock
SocketUser=root
SocketGroup=coulobre-offsite-requests
SocketMode=0660
Accept=yes
MaxConnections=2
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,23 @@
[Unit]
Description=Coulobre off-site backup transfer
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
StateDirectory=coulobre/offsite
StateDirectoryMode=0700
UMask=0077
ExecStart=/opt/coulobre/bin/coulobre-account-backup offsite-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=30min
TimeoutStopSec=10s
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectHome=true
ProtectSystem=strict
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
@@ -0,0 +1,26 @@
[Unit]
Description=Coulobre Panel off-site backup worker
Requires=coulobre-account-offsite.socket
Wants=network-online.target
After=network-online.target coulobre-account-offsite.socket mariadb.service rabbitmq-server.service
[Service]
Type=exec
User=coulobre-offsite-worker
Group=coulobre-offsite-worker
SupplementaryGroups=coulobre-offsite-requests
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
UMask=0077
ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-offsite-backups --hostname=offsite-worker@%H --concurrency=1 --prefetch-multiplier=1
KillMode=mixed
TimeoutStopSec=31min
Restart=on-failure
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,6 @@
[Unit]
Requires=coulobre-website-files.socket
After=coulobre-website-files.socket
[Service]
SupplementaryGroups=coulobre-file-requests
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre website file operation socket
[Socket]
ListenStream=/run/coulobre-website-files.sock
SocketUser=root
SocketGroup=coulobre-file-requests
SocketMode=0660
Accept=yes
MaxConnections=16
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,23 @@
[Unit]
Description=Coulobre website file operation
CollectMode=inactive-or-failed
[Service]
Type=exec
# The system manager starts this as root. An explicit User= can drop
# CAP_SETUID during setup, before the receiver changes to the website user.
WorkingDirectory=/opt/coulobre
UMask=0027
ExecStart=/opt/coulobre/bin/coulobre-web-node files-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
NoNewPrivileges=true
CapabilityBoundingSet=CAP_SYS_CHROOT CAP_SETUID CAP_SETGID CAP_DAC_READ_SEARCH
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/srv/coulobre/web
RestrictAddressFamilies=AF_UNIX
RuntimeMaxSec=2min
@@ -0,0 +1,26 @@
[Unit]
Description=Coulobre Panel website job worker
Requires=coulobre-website-jobs.socket
Wants=network-online.target
After=network-online.target coulobre-website-jobs.socket mariadb.service rabbitmq-server.service
[Service]
Type=exec
User=coulobre-website-job-worker
Group=coulobre-website-job-worker
SupplementaryGroups=coulobre-website-job-requests
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
UMask=0077
ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-website-jobs --hostname=website-jobs@%H --concurrency=2 --prefetch-multiplier=1
KillMode=mixed
TimeoutStopSec=2min
Restart=on-failure
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre website job socket
[Socket]
ListenStream=/run/coulobre-website-jobs.sock
SocketUser=root
SocketGroup=coulobre-website-job-requests
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,31 @@
[Unit]
Description=Coulobre scheduled website job
CollectMode=inactive-or-failed
[Service]
Type=exec
# The system service starts as root and switches to the website user.
WorkingDirectory=/opt/coulobre
ExecStart=/opt/coulobre/bin/coulobre-web-node job-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
# The receiver also terminates the website user's process on timeout.
CapabilityBoundingSet=CAP_SETUID CAP_SETGID CAP_DAC_READ_SEARCH CAP_KILL
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ProtectProc=invisible
ProtectControlGroups=true
ReadWritePaths=/srv/coulobre/web
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=true
RestrictSUIDSGID=true
MemoryMax=256M
TasksMax=32
CPUQuota=100%
RuntimeMaxSec=75s
TimeoutStopSec=5s
KillMode=control-group
+296
View File
@@ -162,6 +162,70 @@ The addresses for hosted sites, mail, and authoritative DNS can differ from
the panel hostname. Configure the corresponding public DNS records for each
service using its reachable address.
## Protect panel sign-in
The HTTPS deployment requires a second factor for administrators, staff,
resellers, and other operator logins. Existing unverified privileged sessions
return to sign-in after the upgrade. Apply the database migrations before
restarting the panel, worker, and scheduler.
A privileged user signs in with a password to start first-time setup. The
setup session can only enroll a second factor or sign out. Choose an
authenticator app, enter the displayed time-based key, and confirm a code
from the app. Use the authenticator's code at future sign-ins. Keep the
panel host and authenticator device clocks synchronized.
If an SMTP relay is configured and the account already has a valid email
address, the user can instead register one-time email codes. The panel uses
the address assigned to the account at enrollment. These codes expire in
five minutes and can be requested once a minute. An authenticator is the
preferred option for privileged accounts.
Save the recovery codes shown after enrollment. Each code works once and
can be entered after the account password. If the user loses the factor
and all recovery codes, verify their identity and issue a replacement
enrollment code on the panel host.
```sh
panel_manage issue_panel_enrollment operator
```
This revokes the previous factor, recovery codes, and sessions verified
with that factor. Deliver the one-time enrollment code to the account
owner through a trusted channel. It expires in 20 minutes. The user signs
in with their password and enters the code to set up a replacement.
### Configure email delivery and customer password recovery
Set `COULOBRE_SMTP_HOST`, `COULOBRE_SMTP_PORT`, and
`COULOBRE_EMAIL_FROM` in the panel environment. Add the relay's username
and password if it requires authentication. The default uses STARTTLS on
port 587. Keep the environment file restricted to the service operators.
Set `COULOBRE_PASSWORD_RESET_ORIGIN` to the panel's public HTTPS origin
to enable **Forgot your password?**. Make sure the default Celery worker
is running. The worker sends 30-minute, single-use links only to active
customer accounts. Keep customer email addresses up to date. Privileged
accounts use administrator-assisted password recovery, followed by their
existing second factor or the enrollment recovery flow.
### Verify client identification
Coulobre limits sign-in, verification, and reset attempts using counters
in the panel database. The scheduler expires old counters. A limit returns
HTTP 429 and a `Retry-After` header. The default allows eight password
attempts per username and client and forty per client in a five-minute
window. IPv6 clients share a counter within a /64.
For Apache deployments, install the current `panel-proxy.inc` and set
`COULOBRE_TRUST_APACHE_CLIENT_IP=1` when Gunicorn listens on the
restricted Unix socket. Apache overwrites the client IP header using its
resolved peer address. With a separate reverse proxy, use the trusted
peer configuration above so Apache supplies the visitor address. Keep
the Gunicorn socket private to the panel service and the front-end server.
A direct TCP connection uses its network peer address for rate limiting.
## Protect a host with nftables and Fail2ban
Enable protection independently on a panel, web, mail, or DNS host. Use the
@@ -573,6 +637,123 @@ serves no tenant content when unknown hosts should be rejected.
[Apache default virtual host](https://httpd.apache.org/docs/current/en/vhosts/name-based.html#defaultvhost) ·
[Deleting a Certbot certificate](https://eff-certbot.readthedocs.io/en/stable/using.html#deleting-certificates)
## Host independent websites
Set a hosting plan's **Website limit** above one to allow additional
websites under an account. The limit includes the primary website. Existing
plans start with one website. In **Independent websites**, choose **Add
website** to provision a domain or subdomain with its own document root,
operating-system user, PHP-FPM pool, and Apache virtual host.
Leave the PHP series blank to select the newest installed stable series
allowed by the plan. Changing the series on one website keeps the other
websites on their configured versions. If the plan sets a website storage
limit, the web node applies that quota to the new site's user.
Point the domain's DNS at the web server and select **Enable HTTPS** after
setting up the existing Certbot worker. Each website has its own Certbot
lineage. An alias under **Website aliases** shares the primary document
root and runtime.
Use **Suspend website** to disable access to a single site. Account-wide
suspension applies to all its active websites. Resuming the account preserves
any independent website suspension. To retire a site, suspend it and
confirm its domain using **Retire website**. The web node archives its data
and disables its Apache and PHP configuration. Retiring a failed provisioning request also frees its place in the plan.
Its domain remains reserved until released with the account's names.
Operators can download the website's version 2 manifest. Use the existing
[website SFTP setup](development.md#install-sftp-keys-on-a-web-node) on the web node
with that manifest to authorize a key for the site's own user. The web
node suspends new SFTP logins for a suspended independent website when
keys have been installed.
New account archives include the primary website and activated independent
websites. Select the website when restoring a file or document root from
an archive containing several sites. The archive identifies each website
by domain and site ID. Upgrade the panel and its web and backup workers
together before enabling additional sites.
## Enable the website file manager
The file manager connects to the web node on the same server as the panel.
It supports the document root of the primary site and each active
independent site. Customers and their assigned resellers can open **Files**.
Operators need both **Can view hosting account** and **Can manage website
files**. File operations are unavailable through impersonation.
```sh
sudo groupadd --system coulobre-file-requests
sudo install -m 0644 deploy/systemd/coulobre-website-files.socket \
deploy/systemd/coulobre-website-files@.service /etc/systemd/system/
sudo install -D -m 0644 deploy/systemd/coulobre-panel.service.d/website-files.conf \
/etc/systemd/system/coulobre-panel.service.d/website-files.conf
sudo install -m 0644 deploy/apache/panel-proxy.inc /etc/coulobre/panel-proxy.inc
```
Set `COULOBRE_WEB_FILE_MANAGER=1` in `/etc/coulobre/panel.env`. For an
Apache deployment, reload Apache to apply the updated request body limit.
```sh
panel_manage migrate --noinput
panel_manage collectstatic --noinput
sudo systemctl daemon-reload
sudo systemctl enable --now coulobre-website-files.socket
sudo systemctl restart coulobre-panel
sudo apache2ctl configtest
sudo systemctl reload apache2
```
The manager shows site-owned folders and regular files. It skips symbolic
links and files with multiple hard links. Uploads accept one file of up to
64 MiB at a time and count toward the site's configured filesystem quota.
Uploads and renames require an unused name in the current folder. A
separate confirmation is required to delete a file or an empty folder.
## Enable scheduled website jobs
The scheduled job worker runs on the same server as the panel and web
node. Install the local socket and Celery worker on that server.
```sh
sudo groupadd --system coulobre-website-job-requests
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin coulobre-website-job-worker
sudo install -m 0644 deploy/systemd/coulobre-website-jobs.socket \
deploy/systemd/coulobre-website-jobs@.service \
deploy/systemd/coulobre-website-job-worker.service /etc/systemd/system/
```
Set `COULOBRE_WEBSITE_JOBS=1` in `/etc/coulobre/panel.env`.
```sh
panel_manage migrate --noinput
sudo systemctl daemon-reload
sudo systemctl enable --now coulobre-website-job-worker.service
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
```
Set **Website job limit** to the number of saved jobs allowed per hosting
account. Paused jobs count toward the saved limit. The default is zero.
If you lower a limit, the oldest enabled jobs retain their places until
the account removes or pauses jobs. Add `website-jobs` to the local service
health list if you monitor this worker from the panel.
Customers and their assigned resellers can open **Scheduled jobs** from the
account page. Operators need both **Can view hosting account** and **Can
manage scheduled website jobs**. Pick the primary or an active independent
website. Use five cron fields in UTC. For example, `*/15 * * * *` runs every
15 minutes. Runs must be at least five minutes apart. When both day fields
are restricted, the date must match both.
The job runs as the website's Unix user in its document root with a
60-second deadline. To use the site's selected PHP series, install its PHP
CLI package and enter a command such as `"$PHP_CLI" tasks/refresh.php`.
The panel shows the last result, including the exit code if the node
reported one. Command output is discarded. A run missed by over 90 seconds
is skipped, and a run with an unconfirmed result is never replayed.
Suspended and retired sites are ineligible for new runs.
## Enable HTTPS for hosted websites
Once a site is active, obtain the website certificate with Certbot on the
@@ -810,6 +991,96 @@ Expired entries stay in the history and lose their restore actions. Keep
the corresponding `.expired` records beside the ZIPs to prevent a late
worker delivery from recreating an expired archive.
#### Copy scheduled account backups off-site
Coulobre can send scheduled archives to an encrypted restic repository over
SFTP. On the backup node, install restic and OpenSSH and create a directory
for each destination. This example uses the destination ID `vault`.
[Restic SFTP repository setup](https://restic.readthedocs.io/en/stable/030_preparing_a_new_repo.html#sftp)
```sh
sudo apt install restic openssh-client
sudo install -d -m 0700 /etc/coulobre/offsite/vault
sudo ssh-keygen -t ed25519 -N '' -f /etc/coulobre/offsite/vault/identity
```
Authorize the public key for a dedicated SFTP login that has access to the
repository. Place the destination files in the directory with root
ownership and mode `0600`.
| File | Contents |
| --- | --- |
| `repository` | A line such as `sftp:coulobre-offsite:repository`. Here `repository` is relative to the SFTP user's directory. |
| `password` | The restic repository password. Store a recovery copy separately from the backup node. |
| `ssh_config` | A `Host coulobre-offsite` block with the storage server's `HostName`, `User`, and optional `Port`. Set `ConnectTimeout 10`, `ServerAliveInterval 30`, and `ServerAliveCountMax 3`. |
| `identity` | The dedicated private key generated above. |
| `known_hosts` | The independently verified SSH host key for the storage server. |
Create a new repository if needed, then verify access from the backup node.
```sh
profile=/etc/coulobre/offsite/vault
ssh_options="-F $profile/ssh_config -i $profile/identity"
ssh_options="$ssh_options -o UserKnownHostsFile=$profile/known_hosts"
ssh_options="$ssh_options -o GlobalKnownHostsFile=/dev/null"
ssh_options="$ssh_options -o StrictHostKeyChecking=yes -o BatchMode=yes -o IdentitiesOnly=yes"
sudo restic --repository-file "$profile/repository" \
--password-file "$profile/password" -o "sftp.args=$ssh_options" init
sudo /opt/coulobre/bin/coulobre-account-backup verify-offsite vault
```
Set `COULOBRE_OFFSITE_BACKUP_DESTINATIONS='{"vault":"Off-site vault"}'` in
`/etc/coulobre/panel.env`. This setting contains IDs and labels. Each ID
maps to a directory under `/etc/coulobre/offsite` on the backup node.
```sh
sudo groupadd --system coulobre-offsite-requests
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin coulobre-offsite-worker
sudo install -m 0644 deploy/systemd/coulobre-account-offsite.socket \
deploy/systemd/coulobre-account-offsite@.service \
deploy/systemd/coulobre-offsite-worker.service /etc/systemd/system/
panel_manage migrate --noinput
sudo systemctl daemon-reload
sudo systemctl enable --now coulobre-offsite-worker.service
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
```
Choose the destination in **Backup schedule**. The choice applies to future
scheduled backups. The archive history shows transfer status. A copy becomes
**Verified** after the worker reads it back from restic and verifies its
size and SHA-256 checksum. Allow time and bandwidth for both the upload
and verification within the 30-minute transfer deadline. An interrupted
transfer reuses an existing snapshot with the same backup ID and verifies
it again. The worker makes up to five attempts before requiring a manual
retry. Operators with **Can change offsite backup transfer** can retry a
failed copy from the archive history. Add `offsite-backups` to the local
service health list to monitor the worker.
Archives awaiting verification stay on the backup node and do not count
toward the eligible local retention set. Once verified, they follow the
existing local schedule and protection rules. Manage remote snapshot
retention in restic on the storage side. Assign a new destination ID when
switching repositories. Keep the original profile and recovery credentials
for as long as you retain copies in that repository.
To recover a copy, take its destination ID, account ID, and backup ID from
the archive history. Run the recovery command on a node with the
destination profile. It looks up the snapshot by backup ID and verifies
the checksum in its authenticated metadata before creating the output file.
```sh
sudo install -d -m 0700 /srv/coulobre-recovery
sudo /opt/coulobre/bin/coulobre-account-backup recover-offsite vault 42 \
123e4567-e89b-12d3-a456-426614174000 /srv/coulobre-recovery/account.zip
sudo /opt/coulobre/bin/coulobre-account-backup unpack \
/srv/coulobre-recovery/account.zip /srv/coulobre-recovery/resources
```
The remote snapshot stores the archive filename and backup ID tag. With
the repository credentials, use `restic snapshots --json` to find them
when recovering without the original panel database.
#### Restore from local account backups in the panel
Enable local account backups first. Install the restore socket and give the
@@ -1908,6 +2179,31 @@ limit and retain their assigned plans. Operators can assign and move
accounts from the hosting account form. Use the audit history to review
changes to reseller policy and account assignments made through the panel.
### Onboard customers and delegate provisioning
A reseller can open an unassigned hosting account in their own portfolio and
select **Add customer login**. Enter a new username and password, and add an
email address to support customer password recovery. Share the initial
credentials with the customer through a trusted channel. An existing
customer created by the same reseller can be added with **Link existing
customer**. The operator controls changes to existing assignments and to
customer sign-in status. The reseller's **Customers** page lists their own
logins.
Enable **Manage databases and mailboxes** on the reseller policy to let that
reseller request and provision both resources for their hosting accounts.
New requests use the account's existing database and mailbox limits and
mailbox storage quota. A deployment must enable the relevant provisioner
before the reseller can queue work. The panel shows provisioning status,
while service credentials and deployment manifests follow their existing
permissions. Both local and separate mail receivers use the same panel
permission.
The operator's reseller detail page records customer creation and linking,
resource requests, provisioning attempts queued or retried, and changes to
the reseller policy. Customer sign-in and operator support access use the
same workflows as operator-created accounts.
## Suspend and resume hosting services
Open the hosting account and use **Hosting service access**. This requires
+6 -2
View File
@@ -1215,12 +1215,14 @@ time.
Use the [website backup command](#back-up-and-restore-hosted-website-files)
on the web node and the [database backup command](#back-up-and-restore-a-managed-database)
on each database node. Transfer the resulting files to a root-controlled
directory with mode `0600` on every archive. Name the website archive
directory with mode `0600` on every archive. Name the primary website archive
`website.tar.gz` and each SQL dump `database-<suffix>.sql.gz`, for example
`database-cms.sql.gz`. When the manifest includes mail, use the
[mailbox backup command](#back-up-and-restore-a-mailbox) on the mail node and
place each archive under `mailboxes/<domain>/<local-part>.tar.gz` within the
component directory. Assemble the ZIP with the same account manifest.
component directory. For a version 3 account manifest, use
`websites/s<site_id>.tar.gz` for each entry in `additional_websites`.
Assemble the ZIP with the same account manifest.
```sh
sudo /opt/coulobre/bin/coulobre-account-backup pack \
@@ -1244,6 +1246,8 @@ sudo /opt/coulobre/bin/coulobre-account-backup unpack \
```
Use the recovered `website.json` and `website.tar.gz` with `restore-site`.
For an independent website, use its `websites/s<site_id>.json` and
`websites/s<site_id>.tar.gz` pair with the same command.
Use each `database-<suffix>.json` and `database-<suffix>.sql.gz` pair with
`restore-database`. For mail, use the original manifest and archive recovered
as `mailboxes/<domain>/<local-part>.json` and
+2
View File
@@ -11,6 +11,7 @@ requires-python = ">=3.12"
license = "Apache-2.0"
dependencies = [
"Django>=5.2.8,<5.3",
"django-otp>=1.7.5,<2",
"celery>=5.6,<6",
"cryptography>=45",
"dnspython>=2.7,<3",
@@ -42,6 +43,7 @@ server = ["gunicorn>=27.0.1,<28"]
"templates/hosting/*.conf",
"templates/hosting/*.html",
"templates/hosting/*.php",
"templates/hosting/*.txt",
]
[tool.ruff]
+77 -2
View File
@@ -9,6 +9,7 @@ from dataclasses import dataclass
from pathlib import Path
from shutil import copyfileobj
from tempfile import NamedTemporaryFile, TemporaryDirectory
from uuid import UUID
from zipfile import ZIP_STORED, BadZipFile, ZipFile
from .database_node import DEFAULT_SOCKET, DatabaseSpec
@@ -18,6 +19,7 @@ from .web_node import WebSite
BASE_MANIFEST_VERSION = 1
MAIL_MANIFEST_VERSION = 2
MULTI_SITE_MANIFEST_VERSION = 3
MANIFEST_KIND = "coulobre_account_backup"
MANIFEST_NAME = "manifest.json"
MAX_MANIFEST_BYTES = 1024 * 1024
@@ -29,8 +31,27 @@ class AccountBackup:
website: WebSite
databases: tuple[DatabaseSpec, ...]
mailboxes: tuple[MailboxSpec, ...] | None = None
additional_websites: tuple[WebSite, ...] = ()
def __post_init__(self):
if self.website.site_id is not None:
raise ValueError(
"The primary website must use its account identity."
)
sites = {self.website.domain}
site_ids = set()
for site in self.additional_websites:
if (
site.account_id != self.website.account_id
or site.site_id is None
):
raise ValueError(
"All websites must belong to the backup account."
)
if site.domain in sites or site.site_id in site_ids:
raise ValueError("The account backup lists a website twice.")
sites.add(site.domain)
site_ids.add(site.site_id)
names = set()
for database in self.databases:
if database.account_id != self.website.account_id:
@@ -57,6 +78,11 @@ class AccountBackup:
manifest["mailboxes"] = [
mailbox.manifest() for mailbox in self.mailboxes
]
if self.additional_websites:
manifest["version"] = MULTI_SITE_MANIFEST_VERSION
manifest["additional_websites"] = [
site.manifest() for site in self.additional_websites
]
return manifest
@classmethod
@@ -67,30 +93,44 @@ class AccountBackup:
if type(version) is not int or version not in (
BASE_MANIFEST_VERSION,
MAIL_MANIFEST_VERSION,
MULTI_SITE_MANIFEST_VERSION,
):
raise ValueError("Unsupported account backup manifest version.")
fields = {"version", "kind", "website", "databases"}
if version == MAIL_MANIFEST_VERSION:
if version == MULTI_SITE_MANIFEST_VERSION:
fields.add("additional_websites")
if version == MAIL_MANIFEST_VERSION or (
version == MULTI_SITE_MANIFEST_VERSION and "mailboxes" in data
):
fields.add("mailboxes")
if data.keys() != fields or not isinstance(data["databases"], list):
raise ValueError("Expected a Coulobre account backup manifest.")
mailboxes = None
if version == MAIL_MANIFEST_VERSION:
if "mailboxes" in fields:
if not isinstance(data["mailboxes"], list):
raise ValueError("Expected a list of mailbox manifests.")
mailboxes = tuple(
MailboxSpec.from_manifest(item) for item in data["mailboxes"]
)
sites = data.get("additional_websites", [])
if not isinstance(sites, list):
raise ValueError(
"Expected a list of additional website manifests."
)
return cls(
WebSite.from_manifest(data["website"]),
tuple(
DatabaseSpec.from_manifest(item) for item in data["databases"]
),
mailboxes,
tuple(WebSite.from_manifest(site) for site in sites),
)
def components(self):
yield self.website, "website.json", "website.tar.gz"
for site in self.additional_websites:
name = f"websites/{site.node_key}"
yield site, f"{name}.json", f"{name}.tar.gz"
for database in self.databases:
name = f"database-{database.suffix}"
yield database, f"{name}.json", f"{name}.sql.gz"
@@ -129,6 +169,20 @@ def main(argv=None):
commands.add_parser(
"restore-request", help="Restore a component for the panel worker."
)
commands.add_parser(
"offsite-request", help="Transfer a scheduled backup for the worker."
)
verify = commands.add_parser(
"verify-offsite", help="Check access to an off-site destination."
)
verify.add_argument("destination")
recover = commands.add_parser(
"recover-offsite", help="Retrieve and verify an off-site archive."
)
recover.add_argument("destination")
recover.add_argument("account_id", type=int)
recover.add_argument("backup_id", type=UUID)
recover.add_argument("output", type=Path)
args = parser.parse_args(argv)
if args.command == "restore-request":
@@ -146,7 +200,28 @@ def main(argv=None):
return serve_backup_request()
if args.command == "offsite-request":
from .offsite_node import serve_offsite_request
return serve_offsite_request()
try:
if args.command == "verify-offsite":
from .offsite_node import verify_destination
verify_destination(args.destination)
print("Off-site repository access verified.")
return 0
if args.command == "recover-offsite":
from .offsite_backup import OffsiteBackupRequest
from .offsite_node import recover_offsite_backup
request = OffsiteBackupRequest(
args.account_id, args.backup_id, args.destination
)
snapshot = recover_offsite_backup(request, args.output)
print(f"Verified archive recovered from snapshot {snapshot}.")
return 0
if args.command == "unpack":
backup = unpack_backup(args.archive, args.directory)
else:
+20
View File
@@ -8,6 +8,26 @@ class CoulobreAdminSite(AdminSite):
def has_permission(self, request):
return super().has_permission(request) and not is_tenant(request.user)
def login(self, request, extra_context=None):
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
destination = request.GET.get("next")
if not url_has_allowed_host_and_scheme(
destination,
{request.get_host()},
require_https=request.is_secure(),
):
destination = reverse("admin:index")
if request.user.is_authenticated:
if not self.has_permission(request):
raise PermissionDenied
return redirect(destination)
return redirect_to_login(destination, login_url="panel:login")
class CoulobreAdminConfig(AdminConfig):
default_site = "coulobre.admin.CoulobreAdminSite"
@@ -1,6 +1,7 @@
from uuid import uuid4
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
@@ -18,6 +19,7 @@ SCHEDULE_FIELDS = (
"weekday",
"time",
"include_mailboxes",
"offsite_destination",
)
@@ -47,6 +49,15 @@ class AccountBackupScheduleForm(forms.Form):
self.allow_mail = allow_mail
if not allow_mail and not self.initial.get("include_mailboxes"):
del self.fields["include_mailboxes"]
destinations = settings.OFFSITE_BACKUP_DESTINATIONS
current = self.initial.get("offsite_destination")
if destinations or current:
choices = [("", "Local archive only"), *destinations.items()]
if current and current not in destinations:
choices.append((current, f"{current} (unavailable)"))
self.fields["offsite_destination"] = forms.ChoiceField(
choices=choices, required=False, label="Off-site destination"
)
def clean(self):
cleaned = super().clean()
@@ -91,6 +102,18 @@ class WebsiteRestoreForm(BackupRestoreForm):
label="Replace the existing file at this path", required=False
)
def __init__(self, *args, targets=None, **kwargs):
super().__init__(*args, **kwargs)
self.targets = targets or {}
if len(self.targets) > 1:
self.fields["site_key"] = forms.ChoiceField(
label="Website",
choices=[
(key, site.domain) for key, site in self.targets.items()
],
)
self.order_fields(["site_key", "scope", "filename", "replace"])
def clean_filename(self):
filename = self.cleaned_data["filename"]
if filename:
@@ -102,6 +125,8 @@ class WebsiteRestoreForm(BackupRestoreForm):
def clean(self):
cleaned = super().clean()
if len(self.targets) == 1:
cleaned["site_key"] = next(iter(self.targets))
if cleaned.get("scope") == "file" and cleaned.get("filename") == "":
self.add_error(
"filename", "Enter the path of the file to restore."
+22 -3
View File
@@ -1,17 +1,19 @@
from datetime import UTC, datetime, timedelta
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.web_node import WebSite
from .independent_websites import active_websites
from .models import (
AccountBackupSchedule,
HostingAccount,
HostingMailbox,
OffsiteBackupTransfer,
)
from .resource_requests import lock_hosting_account, require_open_account
@@ -34,6 +36,7 @@ def account_backup_manifest(account, *, include_mailboxes=False):
WebSite(account.pk, account.primary_domain),
tuple(database.spec for database in account.databases.all()),
mailboxes,
tuple(site.spec for site in active_websites(account)),
).manifest()
@@ -44,9 +47,11 @@ def queue_account_backup(account_id, *, include_mailboxes=False):
_enqueue_backup(account, include_mailboxes=include_mailboxes)
def _enqueue_backup(account, *, include_mailboxes, scheduled_for=None):
def _enqueue_backup(
account, *, include_mailboxes, scheduled_for=None, offsite_destination=""
):
if not account.backup_jobs.filter(finished_at__isnull=True).exists():
account.backup_jobs.create(
job = account.backup_jobs.create(
manifest=account_backup_manifest(
account, include_mailboxes=include_mailboxes
),
@@ -54,6 +59,10 @@ def _enqueue_backup(account, *, include_mailboxes, scheduled_for=None):
and settings.REMOTE_ACCOUNT_BACKUP_MAIL,
scheduled_for=scheduled_for,
)
if scheduled_for is not None and offsite_destination:
OffsiteBackupTransfer.objects.create(
backup=job, destination=offsite_destination
)
def _next_backup_run(schedule, now):
@@ -78,6 +87,15 @@ def save_backup_schedule(account_id, *, can_manage_mail, schedule_fields):
schedule.include_mailboxes or schedule_fields["include_mailboxes"]
):
raise PermissionDenied
destination = schedule_fields.get(
"offsite_destination", schedule.offsite_destination
)
if (
schedule_fields["enabled"]
and destination
and destination not in settings.OFFSITE_BACKUP_DESTINATIONS
):
raise ValidationError("Choose an available off-site destination.")
timing_changed = any(
getattr(schedule, field) != schedule_fields[field]
@@ -124,6 +142,7 @@ def _queue_scheduled_backup(account_id, now):
account,
include_mailboxes=schedule.include_mailboxes,
scheduled_for=schedule.next_run_at,
offsite_destination=schedule.offsite_destination,
)
schedule.next_run_at = _next_backup_run(schedule, now)
schedule.save(update_fields=["next_run_at"])
+11 -1
View File
@@ -13,6 +13,7 @@ from coulobre.node_retirement import RetirementRequest
from coulobre.sftp_keys import public_key_fingerprint
from coulobre.web_node import WebAlias, WebSite
from .independent_websites import active_websites
from .models import (
AccountBackupExpiration,
AccountRetirement,
@@ -83,6 +84,10 @@ def account_inventory(account):
.distinct()
)
certificates.extend(tls_domains)
additional = list(active_websites(account))
certificates.extend(
site.spec.domain for site in additional if site.https_enabled
)
sftp = getattr(account, "sftp", None)
site_domains = WebActivation.objects.filter(
plan__account=account, finished_at__isnull=False, problem=""
@@ -101,7 +106,9 @@ def account_inventory(account):
"site": website.manifest(),
"aliases": [domain for domain, _ in aliases],
"certificates": sorted(set(certificates)),
"website_domains": sorted(set(site_domains)),
"website_domains": sorted(
set(site_domains) | {site.spec.domain for site in additional}
),
"sftp_keys": sorted(
public_key_fingerprint(key)
for key in sftp.public_keys.splitlines()
@@ -246,6 +253,9 @@ def request_retirement(account_id, policy, confirmation, digest, actor):
account.retired_at = retirement.requested_at
account.customer = account.reseller = None
account.save(update_fields=["retired_at", "customer", "reseller"])
account.website_jobs.update(
enabled=False, next_run_at=None, dispatched_at=None
)
schedule = getattr(account, "backup_schedule", None)
if schedule is not None:
schedule.enabled = False
+16 -3
View File
@@ -59,6 +59,8 @@ class HostingPlanAdmin(admin.ModelAdmin):
list_display = (
"name",
"description",
"website_limit",
"website_job_limit",
"database_limit",
"mailbox_limit",
"mailbox_quota_mib",
@@ -77,7 +79,7 @@ class HostingPlanAdmin(admin.ModelAdmin):
@admin.register(Reseller)
class ResellerAdmin(admin.ModelAdmin):
list_display = ("user", "account_limit")
list_display = ("user", "account_limit", "manage_resources")
list_select_related = ("user",)
search_fields = ("user__username",)
filter_horizontal = ("hosting_plans",)
@@ -91,10 +93,21 @@ class ResellerAdmin(admin.ModelAdmin):
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ("user",)
list_select_related = ("user",)
list_display = ("user", "reseller")
list_select_related = ("user", "reseller__user")
search_fields = ("user__username",)
def get_list_display(self, request):
if not request.user.has_perm("hosting.view_reseller"):
return ("user",)
return super().get_list_display(request)
def get_exclude(self, request, obj=None):
excluded = list(super().get_exclude(request, obj) or ())
if not request.user.has_perm("hosting.view_reseller"):
excluded.append("reseller")
return excluded
@admin.register(CustomerImpersonation)
class CustomerImpersonationAdmin(admin.ModelAdmin):
+36 -5
View File
@@ -5,6 +5,7 @@ from django.db import transaction
from coulobre.account_backup import AccountBackup
from coulobre.web_node import WebSite
from .independent_websites import Operation, active_websites
from .models import ComponentRestoreJob, HostingMailbox, WebsiteRestoreJob
from .resource_requests import lock_hosting_account, require_active_services
@@ -50,16 +51,40 @@ def available_restore_resources(backup, kind, current):
return {key: spec for key, spec in current.items() if key in keys}
def current_website_restore_targets(account):
if account.retired_at is not None:
return {}
sites = [WebSite(account.pk, account.primary_domain)]
sites.extend(
website.spec
for website in active_websites(account).exclude(
operation=Operation.RETIRE, finished_at__isnull=True
)
)
return {site.node_key: site for site in sites}
def available_website_restore_targets(backup, current=None):
if current is None:
current = current_website_restore_targets(backup.account)
return {
key: site
for key, site in current.items()
if backup.can_restore_website(site)
}
@transaction.atomic
def queue_website_restore(
backup, *, restore_id, filename, replace, operator_username
backup, *, restore_id, filename, replace, operator_username, site_key=None
):
account = lock_hosting_account(backup.account_id, customer_id=None)
require_active_services(account)
backup.refresh_from_db()
if not backup.can_restore_website(
WebSite(account.pk, account.primary_domain)
):
backup.account = account
targets = available_website_restore_targets(backup)
site = targets.get(site_key or str(account.pk))
if site is None:
raise ValidationError(
"Choose a completed backup of the current website."
)
@@ -69,7 +94,13 @@ def queue_website_restore(
backup,
restore_id,
operator_username,
{"filename": filename, "replace": replace},
{
"filename": filename,
"replace": replace,
"site_manifest": site.manifest()
if site.site_id is not None
else None,
},
WebsiteRestoreJob.objects.filter(
backup__account=account, finished_at__isnull=True
),
+8 -2
View File
@@ -21,10 +21,16 @@ SCHEDULED_ARCHIVES = {
"retention_protected": False,
"expired_at__isnull": True,
}
OFFSITE_READY = Q(offsite_transfer__isnull=True) | Q(
offsite_transfer__verified_at__isnull=False
)
def plan_backup_expirations(now):
scheduled_archives = Q(
scheduled_archives = (
Q(backup_jobs__offsite_transfer__isnull=True)
| Q(backup_jobs__offsite_transfer__verified_at__isnull=False)
) & Q(
**{
f"backup_jobs__{field}": value
for field, value in SCHEDULED_ARCHIVES.items()
@@ -60,7 +66,7 @@ def plan_backup_expiration(account_id, now):
):
return
archives = account.backup_jobs.filter(**SCHEDULED_ARCHIVES)
archives = account.backup_jobs.filter(OFFSITE_READY, **SCHEDULED_ARCHIVES)
retained = list(
archives.order_by("-requested_at", "-pk").values_list(
"pk", "backup_id"
@@ -0,0 +1,202 @@
from django import forms
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.http import Http404, JsonResponse
from django.shortcuts import get_object_or_404, redirect
from django.utils.functional import cached_property
from django.views import View
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin
from coulobre.domain_names import canonical_domain
from .access import OperatorOnlyMixin, TenantScopeMixin
from .independent_websites import (
Operation,
account_websites,
allowed_versions,
create_website,
queue_website_operation,
)
from .models import HostingAccount, IndependentWebsite, WebsiteDomain
class WebsiteCreateForm(forms.Form):
domain = forms.CharField(max_length=253)
php_version = forms.CharField(
label="PHP series",
required=False,
max_length=5,
help_text="Leave blank to use the newest allowed stable series.",
)
def clean_domain(self):
try:
return canonical_domain(self.cleaned_data["domain"])
except ValueError as error:
raise forms.ValidationError(str(error)) from error
class WebsiteOperationForm(forms.Form):
def __init__(self, *args, operation, domain, **kwargs):
super().__init__(*args, **kwargs)
self.operation = operation
self.domain = domain
if operation in (Operation.ACTIVATE, Operation.PHP):
self.fields["php_version"] = forms.CharField(
label="PHP series",
max_length=5,
required=operation == Operation.PHP,
)
if operation == Operation.RETIRE:
self.fields["confirmation"] = forms.CharField(
label="Confirm the website domain",
max_length=253,
help_text=f"Enter {domain} to retire this website.",
)
def clean_confirmation(self):
value = self.cleaned_data["confirmation"]
if value != self.domain:
raise forms.ValidationError("Enter the website domain exactly.")
return value
class IndependentWebsiteEditor(
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, FormView
):
queryset = HostingAccount.objects.filter(
retired_at__isnull=True
).select_related("hosting_plan")
object = None
customer_relation = "customer"
permission_required = (
"hosting.view_hostingaccount",
"hosting.change_hostingaccount",
)
template_name = "hosting/independent_website_form.html"
def dispatch(self, request, *args, **kwargs):
if not settings.LOCAL_WEB_ACTIVATION:
raise Http404
return super().dispatch(request, *args, **kwargs)
@cached_property
def account(self):
return self.get_object()
def get_context_data(self, **kwargs):
return super().get_context_data(
account=self.account,
allowed_php_versions=allowed_versions(self.account),
**kwargs,
)
class IndependentWebsiteCreate(IndependentWebsiteEditor):
form_class = WebsiteCreateForm
extra_context = {"title": "Add independent website", "add": True}
def form_valid(self, form):
domain = form.cleaned_data["domain"]
try:
create_website(
self.account.pk,
domain,
form.cleaned_data["php_version"],
self.request.user,
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
except IntegrityError:
if not WebsiteDomain.objects.filter(domain=domain).exists():
raise
form.add_error("domain", "This domain is unavailable.")
return self.form_invalid(form)
return redirect(self.account)
class IndependentWebsiteOperation(IndependentWebsiteEditor):
form_class = WebsiteOperationForm
@cached_property
def operation(self):
try:
operation = Operation(self.kwargs["operation"])
except ValueError:
raise Http404 from None
if operation == Operation.HTTPS and not settings.LOCAL_WEB_HTTPS:
raise Http404
return operation
@cached_property
def website(self):
return get_object_or_404(
account_websites(self.account),
pk=self.kwargs["site_pk"],
retired_at__isnull=True,
)
def get_initial(self):
return {"php_version": self.website.requested_php_version}
def get_form_kwargs(self):
return super().get_form_kwargs() | {
"operation": self.operation,
"domain": self.website.reservation.domain,
}
def get_context_data(self, **kwargs):
return super().get_context_data(
title=self.operation.label,
website=self.website,
retiring=self.operation == Operation.RETIRE,
**kwargs,
)
def form_valid(self, form):
try:
queue_website_operation(
self.account.pk,
self.website.pk,
self.operation,
form.cleaned_data.get("php_version", ""),
self.request.user,
)
except (HostingAccount.DoesNotExist, IndependentWebsite.DoesNotExist):
raise Http404 from None
except ValidationError as error:
if self.operation == Operation.ACTIVATE:
form.add_error(None, " ".join(error.messages))
else:
form.add_error(None, error)
return self.form_invalid(form)
return redirect(self.account)
class IndependentWebsiteManifest(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
permission_required = "hosting.view_hostingaccount"
def get(self, request, pk, site_pk):
website = get_object_or_404(
IndependentWebsite.objects.select_related("reservation"),
pk=site_pk,
reservation__account_id=pk,
)
return JsonResponse(
website.spec.manifest(),
headers={
"Cache-Control": "private, no-store",
"Content-Disposition": (
"attachment; "
f'filename="coulobre-website-{website.pk}.json"'
),
},
)
@@ -0,0 +1,198 @@
from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.utils import timezone
from coulobre.node_retirement import RetirementRequest
from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.php_runtime import validate_php_version
from coulobre.service_access import ServiceAccessRequest
from .access import is_tenant, manages_account
from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob
from .node_client import (
activate_local_site,
apply_on_local_node,
enable_local_https,
set_local_site_storage_limit,
update_local_php_version,
)
from .resource_requests import lock_hosting_account, require_active_services
Operation = IndependentWebsite.Operation
def account_websites(account):
return (
IndependentWebsite.objects.filter(reservation__account=account)
.select_related("reservation")
.order_by("reservation__domain")
)
def active_websites(account):
return account_websites(account).filter(
activated=True, retired_at__isnull=True
)
def website_limit(account):
plan = account.hosting_plan
return plan.website_limit if plan is not None else 1
def allowed_versions(account):
plan = account.hosting_plan
return plan.allowed_php_versions() if plan is not None else ()
def website_actions(website):
if website.finished_at is None or website.retired_at is not None:
return ()
if not website.activated:
return (Operation.ACTIVATE, Operation.RETIRE)
if website.suspended:
return (Operation.RESUME, Operation.RETIRE)
actions = (Operation.PHP, Operation.SUSPEND)
if settings.LOCAL_WEB_HTTPS and not website.https_enabled:
actions += (Operation.HTTPS,)
return actions
def check_actor(account, actor):
if is_tenant(actor) and not manages_account(actor, account):
raise PermissionDenied
def check_version(account, version):
try:
validate_php_version(version)
except ValueError as error:
raise ValidationError({"php_version": str(error)}) from error
allowed = allowed_versions(account)
if allowed and version not in allowed:
raise ValidationError(
{"php_version": "This PHP series is outside the hosting plan."}
)
@transaction.atomic
def create_website(account_id, domain, version, actor):
account = lock_hosting_account(account_id, customer_id=None)
check_actor(account, actor)
require_active_services(account)
if account_websites(account).filter(
retired_at__isnull=True
).count() + 1 >= website_limit(account):
raise ValidationError(
"This hosting account has reached its website limit."
)
if version:
check_version(account, version)
if WebsiteDomain.objects.filter(domain=domain).exists():
raise ValidationError({"domain": "This domain is unavailable."})
reservation = WebsiteDomain.objects.create(account=account, domain=domain)
return IndependentWebsite.objects.create(
reservation=reservation, requested_php_version=version
)
@transaction.atomic
def queue_website_operation(account_id, site_id, operation, version, actor):
account = lock_hosting_account(account_id, customer_id=None)
check_actor(account, actor)
require_active_services(account)
website = (
account_websites(account)
.select_for_update()
.get(pk=site_id, retired_at__isnull=True)
)
if operation not in Operation.values:
raise ValidationError("Choose a website operation.")
if website.finished_at is None:
raise ValidationError("Wait for the current website operation.")
if operation not in website_actions(website):
raise ValidationError(
"This operation is unavailable for this website."
)
if operation == Operation.PHP or version:
check_version(account, version)
if operation == Operation.RETIRE and (
account.backup_jobs.filter(finished_at__isnull=True).exists()
or WebsiteRestoreJob.objects.filter(
backup__account=account, finished_at__isnull=True
).exists()
):
raise ValidationError("Wait for the backup or restore to finish.")
IndependentWebsite.objects.requeue(
IndependentWebsite.objects.filter(pk=website.pk),
operation=operation,
requested_php_version=(
version
if operation in (Operation.ACTIVATE, Operation.PHP)
else website.requested_php_version
),
)
return website
def apply_website_operation(website):
site = website.spec
operation = website.operation
account = website.reservation.account
try:
require_active_services(account)
except ValidationError as error:
raise ValueError(" ".join(error.messages)) from None
if operation in (Operation.ACTIVATE, Operation.PHP):
requested = website.requested_php_version
if requested:
try:
check_version(account, requested)
except ValidationError as error:
raise ValueError(" ".join(error.messages)) from None
if operation == Operation.ACTIVATE:
plan = account.hosting_plan
_, version = activate_local_site(
site,
plan.get_php_settings() if plan else PhpPoolSettings(),
(requested,) if requested else allowed_versions(account),
)
limit = plan.website_storage_limit_mib if plan else None
if limit is not None:
set_local_site_storage_limit(site, limit)
return {
"activated": True,
"php_version": version,
"storage_limit_mib": limit,
}
if operation == Operation.PHP:
return {"php_version": update_local_php_version(site, requested)}
if operation == Operation.HTTPS:
if not settings.LOCAL_WEB_HTTPS:
raise ValueError("Enable the website HTTPS worker first.")
enable_local_https(site)
return {"https_enabled": True}
if operation in (Operation.SUSPEND, Operation.RESUME):
suspended = operation == Operation.SUSPEND
apply_on_local_node(
ServiceAccessRequest(site, suspended),
"/run/coulobre-web-apply.sock",
"web node",
"website access",
)
return {"suspended": suspended}
if operation == Operation.RETIRE:
request = RetirementRequest(site, str(website.retirement_id))
apply_on_local_node(
request,
"/run/coulobre-web-apply.sock",
"web node",
"website retirement",
identity=request.identity(),
)
website.websitescheduledjob_set.update(
enabled=False, next_run_at=None, dispatched_at=None
)
return {"retired_at": timezone.now()}
raise ValueError("Unknown website operation.")
@@ -0,0 +1,28 @@
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from ...panel_factors import ENROLLMENT_MINUTES, issue_recovery_enrollment
class Command(BaseCommand):
help = "Revoke a panel factor and issue a recovery enrollment code."
def add_arguments(self, parser):
parser.add_argument("username")
def handle(self, *, username, **options):
users = get_user_model()._default_manager
try:
user = users.get_by_natural_key(username)
except users.model.DoesNotExist:
raise CommandError("No panel user has that username.") from None
if not user.is_active:
raise CommandError("The panel user is inactive.")
try:
code = issue_recovery_enrollment(user)
except ValueError as error:
raise CommandError(str(error)) from error
self.stdout.write(
f"Enrollment code (valid for {ENROLLMENT_MINUTES} minutes)"
)
self.stdout.write(code)
@@ -0,0 +1,93 @@
# Generated by Django 5.2.19 on 2026-11-22 10:23
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0044_mail_parity"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="PanelFactorEnrollment",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("digest", models.CharField(max_length=64)),
("expires_at", models.DateTimeField(db_index=True)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="SignInWindow",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("digest", models.CharField(max_length=64)),
("slot", models.PositiveBigIntegerField(db_index=True)),
("attempts", models.PositiveSmallIntegerField(default=0)),
],
options={
"constraints": [
models.UniqueConstraint(
fields=("digest", "slot"),
name="hosting_unique_sign_in_window",
)
],
},
),
migrations.CreateModel(
name="PanelRecoveryCode",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("digest", models.CharField(max_length=64)),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"constraints": [
models.UniqueConstraint(
fields=("user", "digest"),
name="hosting_unique_panel_recovery_code",
)
],
},
),
]
@@ -0,0 +1,52 @@
# Generated by Django 5.2.19 on 2026-11-22 10:39
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0045_panel_authentication"),
]
operations = [
migrations.AddField(
model_name="customer",
name="reseller",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="managed_customers",
to="hosting.reseller",
),
),
migrations.AddField(
model_name="reseller",
name="manage_resources",
field=models.BooleanField(
default=False,
help_text=(
"Allow database and mailbox requests and provisioning."
),
),
),
migrations.AlterField(
model_name="resellerauditevent",
name="action",
field=models.CharField(
choices=[
("create", "Created reseller"),
("update", "Updated reseller"),
("assign", "Assigned hosting account"),
("unassign", "Unassigned hosting account"),
("plan", "Changed hosting account plan"),
("cust_add", "Created customer login"),
("cust_lnk", "Linked customer login"),
("request", "Requested hosting resource"),
("deploy", "Queued resource provisioning"),
],
max_length=8,
),
),
]
@@ -0,0 +1,106 @@
# Generated by Django 5.2.19 on 2026-11-22 10:56
import uuid
import django.core.validators
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0046_reseller_onboarding"),
]
operations = [
migrations.AddField(
model_name="hostingplan",
name="website_limit",
field=models.PositiveSmallIntegerField(
default=1,
help_text=(
"Maximum independent websites, including the primary site."
),
validators=[django.core.validators.MinValueValidator(1)],
),
),
migrations.AddField(
model_name="websiterestorejob",
name="site_manifest",
field=models.JSONField(blank=True, null=True),
),
migrations.CreateModel(
name="IndependentWebsite",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
(
"operation",
models.CharField(
choices=[
("activate", "Provision website"),
("php", "Change PHP series"),
("https", "Enable HTTPS"),
("suspend", "Suspend website"),
("resume", "Resume website"),
("retire", "Retire website"),
],
default="activate",
max_length=8,
),
),
("activated", models.BooleanField(default=False)),
("https_enabled", models.BooleanField(default=False)),
("suspended", models.BooleanField(default=False)),
("retired_at", models.DateTimeField(blank=True, null=True)),
(
"requested_php_version",
models.CharField(blank=True, max_length=5),
),
("php_version", models.CharField(blank=True, max_length=5)),
(
"storage_limit_mib",
models.PositiveIntegerField(blank=True, null=True),
),
(
"retirement_id",
models.UUIDField(default=uuid.uuid4, editable=False),
),
(
"reservation",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="website",
to="hosting.websitedomain",
),
),
],
options={
"indexes": [
models.Index(
fields=["operation", "finished_at", "requested_at"],
name="hosting_ind_operati_bc432b_idx",
)
],
},
),
]
@@ -0,0 +1,20 @@
# Generated by Django 5.2.19 on 2026-11-22 11:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("hosting", "0047_independent_websites"),
]
operations = [
migrations.AlterModelOptions(
name="hostingaccount",
options={
"permissions": [
("manage_website_files", "Can manage hosted website files")
]
},
),
]
@@ -0,0 +1,114 @@
# Generated by Django 5.2.19 on 2026-11-22 14:34
import django.core.validators
import django.db.models.deletion
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0048_website_file_permission"),
]
operations = [
migrations.AlterModelOptions(
name="hostingaccount",
options={
"permissions": [
(
"manage_website_files",
"Can manage hosted website files",
),
(
"manage_website_jobs",
"Can manage scheduled website jobs",
),
]
},
),
migrations.AddField(
model_name="hostingplan",
name="website_job_limit",
field=models.PositiveSmallIntegerField(
default=0,
help_text=(
"Maximum saved jobs per account. "
"Enter 0 to disable scheduling."
),
validators=[django.core.validators.MaxValueValidator(50)],
),
),
migrations.CreateModel(
name="WebsiteScheduledJob",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("name", models.CharField(max_length=120)),
("expression", models.CharField(max_length=120)),
("command", models.CharField(max_length=1000)),
("enabled", models.BooleanField(default=True)),
("next_run_at", models.DateTimeField(blank=True, null=True)),
("dispatched_at", models.DateTimeField(blank=True, null=True)),
("last_run_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
(
"last_result",
models.CharField(
blank=True,
choices=[
("running", "Running"),
("succeeded", "Succeeded"),
("failed", "Failed"),
("timed_out", "Timed out"),
("unconfirmed", "Result unavailable"),
],
max_length=11,
),
),
(
"last_exit_code",
models.SmallIntegerField(blank=True, null=True),
),
("run_token", models.UUIDField(blank=True, null=True)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="website_jobs",
to="hosting.hostingaccount",
),
),
(
"website",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="hosting.independentwebsite",
),
),
],
options={
"ordering": ("pk",),
"indexes": [
models.Index(
fields=["enabled", "next_run_at"],
name="hosting_web_enabled_552c55_idx",
)
],
},
),
]
@@ -0,0 +1,69 @@
# Generated by Django 5.2.19 on 2026-11-22 15:10
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0049_scheduled_website_jobs"),
]
operations = [
migrations.AddField(
model_name="accountbackupschedule",
name="offsite_destination",
field=models.CharField(blank=True, max_length=48),
),
migrations.CreateModel(
name="OffsiteBackupTransfer",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
("destination", models.CharField(max_length=48)),
(
"next_attempt_at",
models.DateTimeField(default=django.utils.timezone.now),
),
("attempts", models.PositiveSmallIntegerField(default=0)),
("verified_at", models.DateTimeField(blank=True, null=True)),
("snapshot", models.CharField(blank=True, max_length=64)),
("sha256", models.CharField(blank=True, max_length=64)),
(
"backup",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="offsite_transfer",
to="hosting.accountbackupjob",
),
),
],
options={
"indexes": [
models.Index(
fields=["finished_at", "next_attempt_at"],
name="hosting_off_finishe_3de46c_idx",
)
],
},
),
]
+194 -6
View File
@@ -33,13 +33,15 @@ from coulobre.mail_node import (
MAX_MAILBOX_QUOTA_MIB,
MailboxSpec,
)
from coulobre.offsite_backup import MAX_DESTINATION_LENGTH
from coulobre.php_pool_settings import (
PHP_SETTING_BOUNDS,
PhpPoolSettings,
PhpPoolSettingsError,
)
from coulobre.php_runtime import validate_php_versions
from coulobre.web_node import MAX_STORAGE_LIMIT_MIB
from coulobre.web_node import MAX_STORAGE_LIMIT_MIB, WebSite
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH
from .fields import DomainNameField
@@ -55,6 +57,10 @@ class Reseller(models.Model):
},
)
account_limit = models.PositiveIntegerField(default=0)
manage_resources = models.BooleanField(
default=False,
help_text="Allow database and mailbox requests and provisioning.",
)
hosting_plans = models.ManyToManyField("HostingPlan", blank=True)
def __str__(self):
@@ -74,6 +80,10 @@ class ResellerAuditEvent(models.Model):
ASSIGN = "assign", "Assigned hosting account"
UNASSIGN = "unassign", "Unassigned hosting account"
PLAN = "plan", "Changed hosting account plan"
CUSTOMER_CREATE = "cust_add", "Created customer login"
CUSTOMER_LINK = "cust_lnk", "Linked customer login"
RESOURCE_REQUEST = "request", "Requested hosting resource"
RESOURCE_PROVISION = "deploy", "Queued resource provisioning"
reseller = models.ForeignKey(
Reseller,
@@ -104,6 +114,14 @@ class Customer(models.Model):
},
)
reseller = models.ForeignKey(
Reseller,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="managed_customers",
)
def __str__(self):
return self.user.get_username()
@@ -246,6 +264,18 @@ def php_plan_field(option, label):
class HostingPlan(models.Model):
name = models.CharField(max_length=120, unique=True)
description = models.CharField(max_length=240, blank=True)
website_limit = models.PositiveSmallIntegerField(
default=1,
validators=[MinValueValidator(1)],
help_text="Maximum independent websites, including the primary site.",
)
website_job_limit = models.PositiveSmallIntegerField(
default=0,
validators=[MaxValueValidator(50)],
help_text=(
"Maximum saved jobs per account. Enter 0 to disable scheduling."
),
)
database_limit = models.PositiveIntegerField(
blank=True,
null=True,
@@ -374,6 +404,10 @@ class HostingAccount(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
permissions = [
("manage_website_files", "Can manage hosted website files"),
("manage_website_jobs", "Can manage scheduled website jobs"),
]
constraints = [
models.CheckConstraint(
condition=models.Q(scheduled_backups_to_keep__isnull=True)
@@ -663,11 +697,12 @@ class WebProvisioningPlan(models.Model):
class ProvisioningJobManager(models.Manager):
def queue(self, **target):
job, created = self.get_or_create(**target)
if not created:
return created or bool(
self.requeue(self.filter(pk=job.pk).exclude(problem=""))
)
def requeue(self, jobs, **updates):
jobs.filter(finished_at__isnull=False).update(
return jobs.filter(finished_at__isnull=False).update(
requested_at=timezone.now(),
last_dispatched_at=None,
started_at=None,
@@ -876,6 +911,77 @@ class WebsiteAlias(ProvisioningJob):
]
class IndependentWebsite(ProvisioningJob):
class Operation(models.TextChoices):
ACTIVATE = "activate", "Provision website"
PHP = "php", "Change PHP series"
HTTPS = "https", "Enable HTTPS"
SUSPEND = "suspend", "Suspend website"
RESUME = "resume", "Resume website"
RETIRE = "retire", "Retire website"
reservation = models.OneToOneField(
WebsiteDomain, on_delete=models.CASCADE, related_name="website"
)
operation = models.CharField(
max_length=8, choices=Operation, default=Operation.ACTIVATE
)
activated = models.BooleanField(default=False)
https_enabled = models.BooleanField(default=False)
suspended = models.BooleanField(default=False)
retired_at = models.DateTimeField(null=True, blank=True)
requested_php_version = models.CharField(max_length=5, blank=True)
php_version = models.CharField(max_length=5, blank=True)
storage_limit_mib = models.PositiveIntegerField(null=True, blank=True)
retirement_id = models.UUIDField(default=uuid.uuid4, editable=False)
class Meta:
indexes = [
models.Index(fields=("operation", "finished_at", "requested_at"))
]
def __str__(self):
return self.reservation.domain
@property
def spec(self):
return WebSite(
self.reservation.account_id, self.reservation.domain, self.pk
)
class WebsiteScheduledJob(models.Model):
class Result(models.TextChoices):
RUNNING = "running", "Running"
SUCCEEDED = "succeeded", "Succeeded"
FAILED = "failed", "Failed"
TIMED_OUT = "timed_out", "Timed out"
UNCONFIRMED = "unconfirmed", "Result unavailable"
account = models.ForeignKey(
HostingAccount, on_delete=models.CASCADE, related_name="website_jobs"
)
website = models.ForeignKey(
IndependentWebsite, on_delete=models.CASCADE, null=True, blank=True
)
domain = DomainNameField(max_length=253)
name = models.CharField(max_length=120)
expression = models.CharField(max_length=120)
command = models.CharField(max_length=MAX_JOB_COMMAND_LENGTH)
enabled = models.BooleanField(default=True)
next_run_at = models.DateTimeField(null=True, blank=True)
dispatched_at = models.DateTimeField(null=True, blank=True)
last_run_at = models.DateTimeField(null=True, blank=True)
finished_at = models.DateTimeField(null=True, blank=True)
last_result = models.CharField(choices=Result, max_length=11, blank=True)
last_exit_code = models.SmallIntegerField(null=True, blank=True)
run_token = models.UUIDField(null=True, blank=True)
class Meta:
ordering = ("pk",)
indexes = [models.Index(fields=("enabled", "next_run_at"))]
class SiteSFTP(ProvisioningJob):
account = models.OneToOneField(
HostingAccount, on_delete=models.CASCADE, related_name="sftp"
@@ -930,9 +1036,50 @@ class AccountBackupJob(ProvisioningJob):
return expiration is None or expiration.finished_at is not None
def can_restore_website(self, site):
return (
self.archive_is_restorable
and self.manifest.get("website") == site.manifest()
return self.archive_is_restorable and (
self.manifest.get("website") == site.manifest()
or site.manifest() in self.manifest.get("additional_websites", [])
)
class OffsiteBackupTransfer(ProvisioningJob):
backup = models.OneToOneField(
AccountBackupJob,
on_delete=models.CASCADE,
related_name="offsite_transfer",
)
destination = models.CharField(max_length=MAX_DESTINATION_LENGTH)
next_attempt_at = models.DateTimeField(default=timezone.now)
attempts = models.PositiveSmallIntegerField(default=0)
verified_at = models.DateTimeField(null=True, blank=True)
snapshot = models.CharField(max_length=64, blank=True)
sha256 = models.CharField(max_length=64, blank=True)
class Meta:
indexes = [models.Index(fields=("finished_at", "next_attempt_at"))]
@property
def status(self):
if self.verified_at is not None:
return "Verified"
if self.backup.finished_at is None:
return "Waiting for local archive"
if self.backup.problem:
return "Local backup failed"
if self.destination not in settings.OFFSITE_BACKUP_DESTINATIONS:
return "Destination unavailable"
if self.finished_at is not None:
return "Failed"
if self.started_at is not None:
return "Transferring"
if self.attempts:
return "Retry scheduled"
return "Queued"
@property
def label(self):
return settings.OFFSITE_BACKUP_DESTINATIONS.get(
self.destination, self.destination
)
@@ -956,6 +1103,7 @@ class WebsiteRestoreJob(ProvisioningJob):
related_name="website_restores",
)
restore_id = models.UUIDField(unique=True, editable=False)
site_manifest = models.JSONField(null=True, blank=True)
filename = models.CharField(max_length=MAX_RESTORE_PATH_BYTES, blank=True)
replace = models.BooleanField(default=False)
operator_username = models.CharField(max_length=150)
@@ -1032,6 +1180,9 @@ class AccountBackupSchedule(models.Model):
)
time = models.TimeField("time (UTC)")
include_mailboxes = models.BooleanField(default=False)
offsite_destination = models.CharField(
max_length=MAX_DESTINATION_LENGTH, blank=True
)
next_run_at = models.DateTimeField(null=True, blank=True)
class Meta:
@@ -1088,3 +1239,40 @@ class ServiceHealth(models.Model):
name="hosting_service_health_identity",
)
]
class SignInWindow(models.Model):
digest = models.CharField(max_length=64)
slot = models.PositiveBigIntegerField(db_index=True)
attempts = models.PositiveSmallIntegerField(default=0)
class Meta:
constraints = [
models.UniqueConstraint(
fields=("digest", "slot"),
name="hosting_unique_sign_in_window",
)
]
class PanelFactorEnrollment(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
digest = models.CharField(max_length=64)
expires_at = models.DateTimeField(db_index=True)
class PanelRecoveryCode(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
digest = models.CharField(max_length=64)
class Meta:
constraints = [
models.UniqueConstraint(
fields=("user", "digest"),
name="hosting_unique_panel_recovery_code",
)
]
+127
View File
@@ -0,0 +1,127 @@
from datetime import timedelta
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import F, Q
from django.utils import timezone
from coulobre.offsite_backup import (
HEX_DIGEST,
OFFSITE_SOCKET,
TRANSFER_TIMEOUT_SECONDS,
OffsiteBackupRequest,
)
from .models import OffsiteBackupTransfer
from .node_client import apply_on_local_node
OFFSITE_BACKUP_QUEUE = "coulobre-offsite-backups"
OFFSITE_BACKUP_LEASE = timedelta(seconds=TRANSFER_TIMEOUT_SECONDS + 60)
MAX_ATTEMPTS = 5
TRANSFER_PROBLEM = (
"The node could not verify the off-site copy. Check its destination."
)
def transfer_scope(now):
return {
"next_attempt_at__lte": now,
"destination__in": settings.OFFSITE_BACKUP_DESTINATIONS,
"backup__finished_at__isnull": False,
"backup__problem": "",
"backup__expired_at__isnull": True,
}
def finish_interrupted_transfers(now):
OffsiteBackupTransfer.objects.filter(
finished_at__isnull=True,
started_at__lte=now - OFFSITE_BACKUP_LEASE,
attempts__gte=MAX_ATTEMPTS,
).update(finished_at=now, problem=TRANSFER_PROBLEM)
def apply_offsite_transfer(job):
request = OffsiteBackupRequest(
job.backup.account_id, job.backup.backup_id, job.destination
)
reply = apply_on_local_node(
request,
OFFSITE_SOCKET,
"off-site backup node",
"archive transfer",
timeout=TRANSFER_TIMEOUT_SECONDS + 20,
)
snapshot, digest = reply.get("snapshot"), reply.get("sha256")
if not all(
isinstance(value, str) and HEX_DIGEST.fullmatch(value)
for value in (snapshot, digest)
):
raise ValueError(
"The off-site node returned an invalid verification result."
)
return snapshot, digest
def run_offsite_transfer(job_id):
now = timezone.now()
if not OffsiteBackupTransfer.objects.filter(
pk=job_id, finished_at__isnull=True, **transfer_scope(now)
).exists():
return
jobs = OffsiteBackupTransfer.objects.filter(
pk=job_id, finished_at__isnull=True, next_attempt_at__lte=now
)
claim = jobs.filter(
Q(started_at__isnull=True)
| Q(started_at__lte=now - OFFSITE_BACKUP_LEASE),
attempts__lt=MAX_ATTEMPTS,
)
if not claim.update(started_at=now, attempts=F("attempts") + 1):
return
running = jobs.filter(started_at=now)
job = running.select_related("backup").first()
if job is None:
return
try:
snapshot, digest = apply_offsite_transfer(job)
except (OSError, ValueError):
finished = timezone.now()
if job.attempts >= MAX_ATTEMPTS:
running.update(finished_at=finished, problem=TRANSFER_PROBLEM)
else:
delay = timedelta(minutes=5 * 2 ** (job.attempts - 1))
running.update(
next_attempt_at=finished + delay,
started_at=None,
last_dispatched_at=None,
problem=TRANSFER_PROBLEM,
)
else:
finished = timezone.now()
running.update(
finished_at=finished,
verified_at=finished,
snapshot=snapshot,
sha256=digest,
problem="",
)
@transaction.atomic
def retry_offsite_transfer(transfer):
if transfer.destination not in settings.OFFSITE_BACKUP_DESTINATIONS:
raise ValidationError(
"Configure the original off-site destination before retrying."
)
if not OffsiteBackupTransfer.objects.requeue(
OffsiteBackupTransfer.objects.filter(
pk=transfer.pk,
verified_at__isnull=True,
backup__expired_at__isnull=True,
).exclude(problem=""),
attempts=0,
next_attempt_at=timezone.now(),
):
raise ValidationError("Only failed off-site transfers can be retried.")
+270
View File
@@ -0,0 +1,270 @@
import secrets
from datetime import timedelta
from smtplib import SMTPException
import django_otp
from django.conf import settings
from django.contrib.auth import get_user_model, login
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.db import connection, transaction
from django.db.models import F
from django.middleware.csrf import rotate_token
from django.utils import timezone
from django.utils.crypto import constant_time_compare, salted_hmac
from django.views.decorators.debug import sensitive_variables
from django_otp.models import Device
from django_otp.plugins.otp_email.models import EmailDevice
from django_otp.plugins.otp_totp.models import TOTPDevice
from .models import PanelFactorEnrollment, PanelRecoveryCode
DEVICE_NAME = "Coulobre Panel"
DEVICE_TYPES = {"authenticator": TOTPDevice, "email": EmailDevice}
CHALLENGE_SESSION = "coulobre_panel_challenge"
SETUP_SESSION = "coulobre_panel_factor_device"
SETUP_EXPIRES = "coulobre_panel_factor_expiry"
SETUP_DESTINATION = "coulobre_panel_factor_destination"
CHALLENGE_SECONDS = 300
ENROLLMENT_MINUTES = 20
def privileged_user(user):
return user.is_authenticated and (
user.is_staff
or user.is_superuser
or hasattr(user, "hosting_reseller")
or not hasattr(user, "hosting_customer")
)
def requires_panel_factor(user):
return settings.REQUIRE_PRIVILEGED_MFA and privileged_user(user)
def lock_user(user_id):
users = get_user_model()._default_manager.filter(pk=user_id)
if connection.vendor == "sqlite":
users.update(last_login=F("last_login"))
return users.select_for_update().get()
def user_devices(user, device_type):
return device_type.objects.filter(user=user, name=DEVICE_NAME)
def confirmed_device(user):
for device_type in DEVICE_TYPES.values():
device = user_devices(user, device_type).filter(confirmed=True).first()
if device:
return device
return None
def device_for_user(user, device_id, *, confirmed):
device = Device.from_persistent_id(device_id) if device_id else None
if (
isinstance(device, (EmailDevice, TOTPDevice))
and device.user_id == user.pk
and device.name == DEVICE_NAME
and device.confirmed == confirmed
):
return device
return None
def email_factor_available(user):
if not settings.EMAIL_HOST or not user.email:
return False
try:
validate_email(user.email)
except ValidationError:
return False
return True
def recovery_required(user):
return PanelFactorEnrollment.objects.filter(user=user).exists()
def secret_digest(kind, token):
return salted_hmac(
f"coulobre.panel-factor.{kind}", token, algorithm="sha256"
).hexdigest()
@sensitive_variables("code")
@transaction.atomic
def issue_recovery_enrollment(user):
user = lock_user(user.pk)
if not (confirmed_device(user) or recovery_required(user)):
raise ValueError("This user can enroll a factor after signing in.")
for device_type in DEVICE_TYPES.values():
user_devices(user, device_type).delete()
PanelRecoveryCode.objects.filter(user=user).delete()
code = secrets.token_urlsafe(24)
PanelFactorEnrollment.objects.update_or_create(
user=user,
defaults={
"digest": secret_digest("enrollment", code),
"expires_at": timezone.now()
+ timedelta(minutes=ENROLLMENT_MINUTES),
},
)
return code
@sensitive_variables("recovery_code")
@transaction.atomic
def begin_enrollment(user, method, *, recovery_code=None):
user = lock_user(user.pk)
if confirmed_device(user):
return None
enrollment = PanelFactorEnrollment.objects.filter(user=user).first()
if enrollment is not None and (
not recovery_code
or enrollment.expires_at <= timezone.now()
or not constant_time_compare(
enrollment.digest, secret_digest("enrollment", recovery_code)
)
):
return None
if enrollment is None and recovery_code is not None:
return None
fields = {}
if method == "email":
if not email_factor_available(user):
return None
fields["email"] = user.email
for device_type in DEVICE_TYPES.values():
user_devices(user, device_type).filter(confirmed=False).delete()
device = user_devices(user, DEVICE_TYPES[method]).create(
user=user, name=DEVICE_NAME, confirmed=False, **fields
)
if enrollment:
enrollment.digest = ""
enrollment.save(update_fields=["digest"])
return device
def start_initial_setup(request, destination):
request.session[SETUP_DESTINATION] = destination
request.session[SETUP_EXPIRES] = int(timezone.now().timestamp()) + 900
def initial_setup_active(request):
return request.session.get(SETUP_EXPIRES, 0) > int(
timezone.now().timestamp()
)
def start_challenge(request, user, destination):
request.session.cycle_key()
rotate_token(request)
request.session.pop(SETUP_SESSION, None)
request.session[CHALLENGE_SESSION] = {
"user": user.pk,
"backend": user.backend,
"auth_hash": user.get_session_auth_hash(),
"expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS,
"next": destination,
}
def pending_user(request):
data = request.session.get(CHALLENGE_SESSION)
if request.user.is_authenticated or not data:
return None
user = (
get_user_model()
._default_manager.filter(pk=data["user"], is_active=True)
.first()
)
if (
data["expires"] > int(timezone.now().timestamp())
and user is not None
and requires_panel_factor(user)
and constant_time_compare(
data["auth_hash"], user.get_session_auth_hash()
)
):
return user
request.session.pop(CHALLENGE_SESSION, None)
request.session.pop(SETUP_SESSION, None)
return None
def complete_challenge(request, user, device):
request.session.pop(SETUP_SESSION, None)
if request.user.is_authenticated:
request.session.pop(SETUP_EXPIRES, None)
destination = request.session.pop(SETUP_DESTINATION)
request.session.cycle_key()
rotate_token(request)
else:
data = request.session.pop(CHALLENGE_SESSION)
login(request, user, backend=data["backend"])
destination = data["next"]
django_otp.login(request, device)
return destination
@sensitive_variables("token", "codes")
@transaction.atomic
def confirm_enrollment(user, device_id, token):
user = lock_user(user.pk)
device = device_for_user(user, device_id, confirmed=False)
if (
device is None
or confirmed_device(user)
or not device.verify_token(token)
):
return None, []
device.confirmed = True
device.save(update_fields=["confirmed"])
PanelFactorEnrollment.objects.filter(user=user).delete()
codes = [secrets.token_hex(10) for _ in range(10)]
PanelRecoveryCode.objects.bulk_create(
[
PanelRecoveryCode(
user=user, digest=secret_digest("recovery", code)
)
for code in codes
]
)
return device, codes
@sensitive_variables("code")
@transaction.atomic
def verify_factor(user, code):
user = lock_user(user.pk)
device = confirmed_device(user)
if device is None:
return None
if len(code) == 20:
deleted, _ = PanelRecoveryCode.objects.filter(
user=user, digest=secret_digest("recovery", code)
).delete()
return device if deleted else None
return device if device.verify_token(code) else None
def send_factor_code(user, device_id, *, confirmed):
try:
with transaction.atomic():
user = lock_user(user.pk)
device = device_for_user(user, device_id, confirmed=confirmed)
if (
not isinstance(device, EmailDevice)
or not device.email
or not settings.EMAIL_HOST
):
return "Email codes are unavailable for this account."
allowed, _ = device.generate_is_allowed()
if not allowed:
return "Wait a minute before requesting another email code."
device.generate_challenge()
except (OSError, SMTPException):
return "The email code could not be sent. Try again later."
return "A code was sent to the account email address."
+130
View File
@@ -0,0 +1,130 @@
from urllib.parse import urlsplit
from django.conf import settings
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.views import (
INTERNAL_RESET_SESSION_TOKEN,
PasswordResetConfirmView,
PasswordResetDoneView,
PasswordResetView,
)
from django.db import transaction
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from kombu.exceptions import OperationalError
from .panel_factors import lock_user, privileged_user
from .sign_in_limits import limit_attempt
def reset_enabled():
return bool(settings.PASSWORD_RESET_ORIGIN and settings.EMAIL_HOST)
def can_reset_password(user):
return (
user.is_active
and user.has_usable_password()
and not privileged_user(user)
)
class CustomerPasswordResetForm(PasswordResetForm):
def get_users(self, email):
return (
user
for user in super().get_users(email)
if can_reset_password(user)
)
def send_customer_reset_email(email):
if reset_enabled():
form = CustomerPasswordResetForm({"email": email})
if form.is_valid():
form.save(
domain_override=urlsplit(
settings.PASSWORD_RESET_ORIGIN
).netloc,
use_https=True,
email_template_name="hosting/password_reset_email.txt",
subject_template_name="hosting/password_reset_subject.txt",
)
class PasswordResetAvailable:
def get_context_data(self, **kwargs):
return super().get_context_data(auth_screen=True, **kwargs)
def dispatch(self, request, *args, **kwargs):
if not reset_enabled():
raise Http404
return super().dispatch(request, *args, **kwargs)
@method_decorator(never_cache, name="dispatch")
class CustomerPasswordResetView(PasswordResetAvailable, PasswordResetView):
template_name = "hosting/password_reset_request.html"
form_class = CustomerPasswordResetForm
success_url = reverse_lazy("panel:password_reset_done")
def post(self, request, *args, **kwargs):
limited = limit_attempt(
request,
"reset",
request.POST.get("email", "")[:254],
address_limit=20,
identity_limit=4,
)
return limited or super().post(request, *args, **kwargs)
def form_valid(self, form):
from .tasks import send_customer_password_reset
try:
send_customer_password_reset.apply_async(
args=[form.cleaned_data["email"]], retry=False, expires=300
)
except OperationalError:
return HttpResponse(
"Password reset is temporarily unavailable. Try again later.",
content_type="text/plain",
status=503,
)
# Use the same queue and response for all addresses.
return HttpResponseRedirect(self.get_success_url())
class CustomerResetDoneView(PasswordResetAvailable, PasswordResetDoneView):
template_name = "hosting/password_reset_done.html"
class CustomerResetConfirmView(
PasswordResetAvailable, PasswordResetConfirmView
):
template_name = "hosting/password_reset_confirm.html"
success_url = reverse_lazy("panel:password_reset_complete")
def get_user(self, uidb64):
user = super().get_user(uidb64)
return user if user is not None and can_reset_password(user) else None
@transaction.atomic
def form_valid(self, form):
user = lock_user(self.user.pk)
token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN)
if not can_reset_password(
user
) or not self.token_generator.check_token(user, token):
self.request.session.pop(INTERNAL_RESET_SESSION_TOKEN, None)
self.validlink = False
return self.render_to_response(self.get_context_data())
form.user = user
return super().form_valid(form)
class CustomerResetCompleteView(PasswordResetAvailable, PasswordResetDoneView):
template_name = "hosting/password_reset_complete.html"
title = "Password changed"
+7 -1
View File
@@ -29,6 +29,7 @@ def plan_reference(plan):
def policy_snapshot(reseller):
return {
"account_limit": reseller.account_limit,
"manage_resources": reseller.manage_resources,
"hosting_plans": [
plan_reference(plan)
for plan in reseller.hosting_plans.order_by("pk")
@@ -70,7 +71,9 @@ def create_reseller(login_form, policy, actor):
user.is_active = policy["is_active"]
user.save()
reseller = Reseller.objects.create(
user=user, account_limit=policy["account_limit"]
user=user,
account_limit=policy["account_limit"],
manage_resources=policy.get("manage_resources", False),
)
if "hosting_plans" in policy:
reseller.hosting_plans.set(policy["hosting_plans"])
@@ -102,6 +105,9 @@ def update_reseller(reseller_id, policy, actor):
if reseller.account_limit != policy["account_limit"]:
reseller.account_limit = policy["account_limit"]
reseller.save(update_fields=["account_limit"])
if "manage_resources" in policy:
reseller.manage_resources = policy["manage_resources"]
reseller.save(update_fields=["manage_resources"])
if "hosting_plans" in policy:
reseller.hosting_plans.set(policy["hosting_plans"])
changes = policy_changes(before, policy_snapshot(reseller))
+109
View File
@@ -0,0 +1,109 @@
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from .access import reseller_for_user
from .models import Customer, HostingAccount, Reseller, ResellerAuditEvent
from .reseller_accounts import lock_resellers, record_event
from .resource_requests import lock_hosting_account, require_open_account
Action = ResellerAuditEvent.Action
def scoped_customers(reseller):
return reseller.managed_customers.filter(
user__is_staff=False,
user__is_superuser=False,
user__hosting_reseller__isnull=True,
)
def lock_reseller_account(access, account_id, *, resources=False):
account = lock_hosting_account(account_id, customer_id=None)
if account.reseller_id != access.pk:
raise HostingAccount.DoesNotExist
reseller = lock_resellers(
Reseller.objects.filter(pk=access.pk, user_id=access.user_id)
).first()
if (
reseller is None
or not reseller.user.is_active
or reseller_for_user(reseller.user) is None
):
raise PermissionDenied
if resources and not reseller.manage_resources:
raise PermissionDenied
require_open_account(account)
return account, reseller
def require_unassigned_customer(account):
if account.customer_id is not None:
raise ValidationError("This hosting account already has a customer.")
@transaction.atomic
def create_reseller_customer(access, account_id, form):
account, reseller = lock_reseller_account(access, account_id)
require_unassigned_customer(account)
customer = Customer.objects.create(user=form.save(), reseller=reseller)
save_customer_link(account, reseller, customer, Action.CUSTOMER_CREATE)
return account
@transaction.atomic
def link_reseller_customer(access, account_id, customer_id):
account, reseller = lock_reseller_account(access, account_id)
require_unassigned_customer(account)
customer = (
scoped_customers(reseller)
.select_for_update()
.filter(pk=customer_id, user__is_active=True)
.first()
)
if customer is None:
raise ValidationError("This customer is no longer available.")
save_customer_link(account, reseller, customer, Action.CUSTOMER_LINK)
return account
def save_customer_link(account, reseller, customer, action):
account.customer = customer
account.save(update_fields=["customer"])
record_event(
reseller,
reseller.user.get_username(),
action,
{"customer": str(customer)},
account_domain=account.primary_domain,
)
@transaction.atomic
def request_reseller_resource(access, account_id, create, values):
account, reseller = lock_reseller_account(
access, account_id, resources=True
)
resource = create(account.pk, **values)
record_resource_event(reseller, account, Action.RESOURCE_REQUEST, resource)
return resource
@transaction.atomic
def provision_reseller_resource(access, account_id, provision, resource):
account, reseller = lock_reseller_account(
access, account_id, resources=True
)
if provision(resource):
record_resource_event(
reseller, account, Action.RESOURCE_PROVISION, resource
)
def record_resource_event(reseller, account, action, resource):
record_event(
reseller,
reseller.user.get_username(),
action,
{"resource": str(resource), "type": resource._meta.verbose_name},
account_domain=account.primary_domain,
)
@@ -0,0 +1,119 @@
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView
from .access import reseller_for_user
from .models import HostingAccount
from .reseller_onboarding import (
create_reseller_customer,
link_reseller_customer,
scoped_customers,
)
class ResellerCustomerLoginForm(UserCreationForm):
email = forms.EmailField(
required=False,
help_text="Used for customer password recovery when enabled.",
)
class Meta(UserCreationForm.Meta):
fields = ("username", "email")
class ResellerCustomerLinkForm(forms.Form):
customer = forms.ModelChoiceField(queryset=None)
def __init__(self, *args, customers, **kwargs):
super().__init__(*args, **kwargs)
self.fields["customer"].queryset = customers
class ResellerCustomerEditor(PermissionRequiredMixin, FormView):
template_name = "hosting/customer_form.html"
@cached_property
def reseller(self):
return reseller_for_user(self.request.user)
@cached_property
def account(self):
return get_object_or_404(
HostingAccount,
pk=self.kwargs["pk"],
reseller=self.reseller,
retired_at__isnull=True,
customer__isnull=True,
)
def has_permission(self):
return self.reseller is not None
def get_context_data(self, **kwargs):
return super().get_context_data(account=self.account, **kwargs)
@method_decorator(
sensitive_post_parameters("password1", "password2"), name="dispatch"
)
class ResellerCustomerCreate(ResellerCustomerEditor):
form_class = ResellerCustomerLoginForm
extra_context = {"title": "Add customer login"}
def form_valid(self, form):
account = self.account
try:
account = create_reseller_customer(self.reseller, account.pk, form)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
except IntegrityError:
user = form.instance
if (
not get_user_model()
.objects.filter(username__iexact=user.username)
.exists()
):
raise
form.add_error(
"username", user.unique_error_message(type(user), ["username"])
)
return self.form_invalid(form)
return redirect(account)
class ResellerCustomerLink(ResellerCustomerEditor):
form_class = ResellerCustomerLinkForm
extra_context = {"title": "Link existing customer"}
def get_form_kwargs(self):
return super().get_form_kwargs() | {
"customers": scoped_customers(self.reseller)
.filter(user__is_active=True)
.select_related("user")
.order_by("user__username")
}
def form_valid(self, form):
account = self.account
try:
account = link_reseller_customer(
self.reseller, account.pk, form.cleaned_data["customer"].pk
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
form.add_error(None, error)
return self.form_invalid(form)
return redirect(account)
+10 -2
View File
@@ -33,8 +33,16 @@ class ResellerPolicyForm(forms.ModelForm):
class Meta:
model = Reseller
fields = ("is_active", "account_limit", "hosting_plans")
labels = {"hosting_plans": "Allowed hosting plans"}
fields = (
"is_active",
"account_limit",
"hosting_plans",
"manage_resources",
)
labels = {
"hosting_plans": "Allowed hosting plans",
"manage_resources": "Manage databases and mailboxes",
}
help_texts = {
"account_limit": "Enter 0 to stop self-service account creation.",
"hosting_plans": (
+2 -2
View File
@@ -95,7 +95,7 @@ def queue_mailbox_provisioning(mailbox):
mailbox.mail_domain.account_id, customer_id=None
)
require_active_services(account)
MailboxProvisioning.objects.queue(mailbox=mailbox)
return MailboxProvisioning.objects.queue(mailbox=mailbox)
@transaction.atomic
@@ -200,7 +200,7 @@ def require_active_services(account):
def queue_database_provisioning(database):
account = lock_hosting_account(database.account_id, customer_id=None)
require_active_services(account)
DatabaseProvisioning.objects.queue(database=database)
return DatabaseProvisioning.objects.queue(database=database)
@transaction.atomic
+19 -3
View File
@@ -8,6 +8,7 @@ from coulobre.mail_node import MailboxSpec
from coulobre.service_access import ServiceAccessRequest
from coulobre.web_node import WebSite
from .independent_websites import account_websites, active_websites
from .models import (
AccountServiceJob,
ComponentRestoreJob,
@@ -62,6 +63,11 @@ def current_service_jobs(account):
"Resolve pending or failed website, database, and mailbox "
"provisioning before suspending services."
)
websites = account_websites(account).filter(retired_at__isnull=True)
if websites.filter(Q(finished_at__isnull=True) | ~Q(problem="")).exists():
raise ValidationError(
"Resolve pending or failed website operations first."
)
component_restores = ComponentRestoreJob.objects.filter(
backup__account=account
)
@@ -81,6 +87,9 @@ def current_service_jobs(account):
yield Kind.WEB, domain, site.manifest()
if settings.LOCAL_WEB_SFTP or hasattr(account, "sftp"):
yield Kind.SFTP, domain, site.manifest()
for website in active_websites(account):
site = website.spec
yield Kind.WEB, site.domain, site.manifest()
completed_restores = component_restores.filter(problem="")
restored_databases = completed_restores.filter(
kind=ComponentRestoreJob.Kind.DATABASE
@@ -176,9 +185,16 @@ def apply_service_change(job):
raise ValueError(
f"The provisioning worker for {job.target} is disabled."
)
request = ServiceAccessRequest(
resource.from_manifest(job.manifest), job.change.suspended
)
spec = resource.from_manifest(job.manifest)
suspended = job.change.suspended
if job.kind == Kind.WEB and spec.site_id is not None and not suspended:
website = (
active_websites(job.change.account).filter(pk=spec.site_id).first()
)
if website is None or website.spec != spec:
raise ValueError("The additional website has changed.")
suspended = website.suspended
request = ServiceAccessRequest(spec, suspended)
apply_on_local_node(
request, socket, job.get_kind_display(), "service access"
)
+322
View File
@@ -0,0 +1,322 @@
import base64
from django import forms
from django.contrib.auth import logout
from django.contrib.auth.views import LoginView, redirect_to_login
from django.shortcuts import redirect, render
from django.urls import reverse
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
from django_otp.plugins.otp_email.models import EmailDevice
from .panel_factors import (
SETUP_SESSION,
begin_enrollment,
complete_challenge,
confirm_enrollment,
confirmed_device,
device_for_user,
email_factor_available,
initial_setup_active,
pending_user,
recovery_required,
requires_panel_factor,
send_factor_code,
start_challenge,
start_initial_setup,
verify_factor,
)
from .password_reset import reset_enabled
from .sign_in_limits import limit_attempt
class PrivilegedFactorMiddleware:
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):
view = request.resolver_match.view_name
if (
not requires_panel_factor(request.user)
or request.user.is_verified()
or view == "panel:logout"
):
return None
if (
initial_setup_active(request)
and not confirmed_device(request.user)
and not recovery_required(request.user)
):
if view in ("panel:factor_enroll", "panel:factor_confirm"):
return None
return redirect("panel:factor_enroll")
destination = reverse("panel:accounts")
if request.method in ("GET", "HEAD") and view != "panel:login":
destination = request.get_full_path()
logout(request)
return redirect_to_login(destination)
class PanelLoginView(LoginView):
template_name = "hosting/login.html"
redirect_authenticated_user = True
def post(self, request, *args, **kwargs):
limited = limit_attempt(
request,
"password",
request.POST.get("username", "")[:150],
address_limit=40,
identity_limit=8,
)
return limited or super().post(request, *args, **kwargs)
def get_context_data(self, **kwargs):
return super().get_context_data(
password_reset_enabled=reset_enabled(), **kwargs
)
def form_valid(self, form):
user = form.get_user()
if not requires_panel_factor(user):
return super().form_valid(form)
destination = self.get_success_url()
if confirmed_device(user) or recovery_required(user):
start_challenge(self.request, user, destination)
return redirect("panel:factor_verify")
super().form_valid(form)
start_initial_setup(self.request, destination)
return redirect("panel:factor_enroll")
class FactorForm(forms.Form):
code = forms.CharField(
label="Verification or recovery code",
max_length=32,
widget=forms.TextInput(attrs={"autocomplete": "one-time-code"}),
)
def clean_code(self):
return self.cleaned_data["code"].lower().replace(" ", "")
class EnrollmentForm(forms.Form):
method = forms.ChoiceField(
label="Verification method", widget=forms.RadioSelect
)
code = forms.CharField(
label="Enrollment code",
max_length=32,
widget=forms.PasswordInput(attrs={"autocomplete": "off"}),
)
def __init__(self, *args, email_available, recovery, **kwargs):
super().__init__(*args, **kwargs)
choices = [("authenticator", "Authenticator app")]
if email_available:
choices.append(("email", "Email code"))
self.fields["method"].choices = choices
self.initial["method"] = "authenticator"
if not recovery:
del self.fields["code"]
class ConfirmFactorForm(FactorForm):
code = forms.RegexField(
r"^[0-9]{6}$",
label="Verification code",
widget=forms.TextInput(
attrs={"autocomplete": "one-time-code", "inputmode": "numeric"}
),
)
@method_decorator(never_cache, name="dispatch")
@method_decorator(sensitive_post_parameters("code"), name="dispatch")
class FactorView(FormView):
template_name = "hosting/authentication.html"
def get_context_data(self, **kwargs):
return super().get_context_data(
title=self.heading,
heading=self.heading,
instructions=self.instructions,
submit_label=self.submit_label,
back_to_login=not self.initial_setup,
auth_screen=True,
**kwargs,
)
def dispatch(self, request, *args, **kwargs):
self.initial_setup = (
requires_panel_factor(request.user)
and initial_setup_active(request)
and not request.user.is_verified()
)
self.user = (
request.user if self.initial_setup else pending_user(request)
)
if self.user is None:
return redirect("panel:login")
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
limited = limit_attempt(
request,
"factor",
str(self.user.pk),
address_limit=30,
identity_limit=10,
)
if limited:
return limited
if "send_code" in request.POST:
device = self.current_device()
if not isinstance(device, EmailDevice):
return redirect(request.path)
return self.render_to_response(
self.get_context_data(
form=self.form_class(),
code_notice=send_factor_code(
self.user,
device.persistent_id,
confirmed=device.confirmed,
),
)
)
return super().post(request, *args, **kwargs)
def current_device(self):
return None
def rejected(self, form, message):
form.add_error("code", message)
return self.form_invalid(form)
class VerifyFactorView(FactorView):
heading = "Verify your sign-in"
instructions = (
"Enter a verification code or one of your saved recovery codes."
)
submit_label = "Verify"
form_class = FactorForm
def current_device(self):
return confirmed_device(self.user)
def get(self, request, *args, **kwargs):
if self.current_device() is None:
return redirect("panel:factor_enroll")
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
return super().get_context_data(
email_factor=isinstance(self.current_device(), EmailDevice),
**kwargs,
)
def form_valid(self, form):
if self.current_device() is None:
return redirect("panel:factor_enroll")
verified = verify_factor(self.user, form.cleaned_data["code"])
if verified is None:
return self.rejected(
form, "Invalid or unavailable code. Try again."
)
return redirect(complete_challenge(self.request, self.user, verified))
class EnrollFactorView(FactorView):
heading = "Set up your second factor"
instructions = "Choose how you want to verify future sign-ins."
submit_label = "Continue"
form_class = EnrollmentForm
def get(self, request, *args, **kwargs):
if confirmed_device(self.user):
return redirect("panel:factor_verify")
return super().get(request, *args, **kwargs)
def get_form_kwargs(self):
return super().get_form_kwargs() | {
"email_available": email_factor_available(self.user),
"recovery": not self.initial_setup,
}
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if not self.initial_setup:
context["instructions"] = (
"Use the enrollment code provided by your hosting operator."
)
return context
def form_valid(self, form):
device = begin_enrollment(
self.user,
form.cleaned_data["method"],
recovery_code=form.cleaned_data.get("code"),
)
if device is None:
form.add_error(
None, "Could not start setup. Sign in and try again."
)
return self.form_invalid(form)
self.request.session[SETUP_SESSION] = device.persistent_id
return redirect("panel:factor_confirm")
class ConfirmFactorView(FactorView):
heading = "Confirm your second factor"
instructions = "Enter a code to complete setup."
submit_label = "Confirm"
form_class = ConfirmFactorForm
def current_device(self):
return device_for_user(
self.user, self.request.session.get(SETUP_SESSION), confirmed=False
)
def get(self, request, *args, **kwargs):
if self.current_device() is None:
return redirect("panel:factor_enroll")
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
device = self.current_device()
context = {}
if isinstance(device, EmailDevice):
context["email_factor"] = True
elif device:
context = {
"setup_key": base64.b32encode(device.bin_key).decode(),
"configuration_url": device.config_url,
}
return super().get_context_data(**context, **kwargs)
@sensitive_variables("codes")
def form_valid(self, form):
device, codes = confirm_enrollment(
self.user,
self.request.session.get(SETUP_SESSION),
form.cleaned_data["code"],
)
if device is None:
return self.rejected(
form, "Invalid or unavailable code. Try again."
)
destination = complete_challenge(self.request, self.user, device)
return render(
self.request,
"hosting/factor_recovery_codes.html",
{"codes": codes, "destination": destination},
)
+73
View File
@@ -0,0 +1,73 @@
from ipaddress import ip_address, ip_network
from unicodedata import normalize
from django.conf import settings
from django.db.models import F
from django.http import HttpResponse
from django.utils import timezone
from django.utils.crypto import salted_hmac
from .models import SignInWindow
WINDOW_SECONDS = 300
def client_address(request):
peer = request.META.get("REMOTE_ADDR") or ""
address = peer
if settings.TRUST_APACHE_CLIENT_IP and not peer:
address = request.META.get("HTTP_X_COULOBRE_CLIENT_IP", "")
try:
if "%" in address:
raise ValueError
parsed = ip_address(address)
except ValueError:
return "unknown"
if parsed.version == 6:
if parsed.ipv4_mapped:
return str(parsed.ipv4_mapped)
return str(ip_network((parsed, 64), strict=False))
return str(parsed)
def current_window():
return int(timezone.now().timestamp()) // WINDOW_SECONDS
def reserve_attempt(purpose, key, slot, limit):
digest = salted_hmac(
f"coulobre.sign-in.{purpose}", key, algorithm="sha256"
).hexdigest()
window, _ = SignInWindow.objects.get_or_create(digest=digest, slot=slot)
changed = SignInWindow.objects.filter(
pk=window.pk, attempts__lt=limit
).update(attempts=F("attempts") + 1)
return bool(changed)
def limit_attempt(
request, purpose, identity, *, address_limit, identity_limit
):
address = client_address(request)
slot = current_window()
identity = normalize("NFKC", identity).casefold()[:254]
if reserve_attempt(
f"{purpose}.address", address, slot, address_limit
) and (
reserve_attempt(
f"{purpose}.identity",
f"{address}|{identity}",
slot,
identity_limit,
)
):
return None
response = HttpResponse(
"Too many attempts. Try again in a few minutes.",
status=429,
content_type="text/plain",
)
retry_after = (slot + 1) * WINDOW_SECONDS - int(timezone.now().timestamp())
response["Retry-After"] = max(1, retry_after)
response["Cache-Control"] = "no-store"
return response
@@ -819,3 +819,52 @@ dd {
.dns-instructions input {
min-width: 12rem;
}
.file-breadcrumbs {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin: 0 0 1rem;
padding: 1rem 1.2rem 0;
list-style: none;
}
.file-breadcrumbs li {
overflow-wrap: anywhere;
}
.file-breadcrumbs li + li::before {
content: "/";
margin-right: 0.4rem;
color: var(--muted);
}
.file-forms {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(16rem, 100%), 1fr));
align-items: start;
gap: 1rem;
margin-block-end: 1.25rem;
padding-inline: 1.2rem;
}
.file-forms form,
.file-forms input[type="file"] {
min-width: 0;
max-width: 100%;
}
.file-table .file-name {
min-width: 7rem;
max-width: 28rem;
}
.file-table th:nth-child(2),
.file-table td:nth-child(2),
.file-table .table-actions {
white-space: nowrap;
}
.file-name {
overflow-wrap: anywhere;
}
+137 -3
View File
@@ -1,4 +1,4 @@
from datetime import timedelta
from datetime import datetime, timedelta
from uuid import UUID
from celery import shared_task
@@ -29,10 +29,12 @@ from .account_retirement import apply_retirement_job, finalize_retirement
from .backup_restores import (
RestoreKind,
available_restore_resources,
available_website_restore_targets,
current_restore_resources,
enabled_component_restores,
)
from .backup_retention import plan_backup_expirations
from .independent_websites import active_websites, apply_website_operation
from .mail_dns_setup import sync_mail_dns
from .mail_policies import apply_policy, mail_policy_available
from .models import (
@@ -45,9 +47,12 @@ from .models import (
DatabaseProvisioning,
DnsPublication,
HostingMailDomain,
IndependentWebsite,
MailboxProvisioning,
MailRoutingPublication,
MailVacationPublication,
OffsiteBackupTransfer,
SignInWindow,
SitePhpSettings,
SitePhpVersion,
SiteSFTP,
@@ -58,6 +63,7 @@ from .models import (
WebProvisioningPlan,
WebsiteAlias,
WebsiteRestoreJob,
WebsiteScheduledJob,
)
from .node_client import (
NodeReplyError,
@@ -79,9 +85,32 @@ from .node_client import (
update_local_sftp,
update_local_website_alias,
)
from .offsite_backups import (
MAX_ATTEMPTS as MAX_OFFSITE_ATTEMPTS,
)
from .offsite_backups import (
OFFSITE_BACKUP_LEASE,
OFFSITE_BACKUP_QUEUE,
finish_interrupted_transfers,
run_offsite_transfer,
transfer_scope,
)
from .password_reset import send_customer_reset_email
from .php_settings import plan_php_versions
from .service_changes import apply_service_change
from .sftp import site_is_active
from .sign_in_limits import current_window
from .website_jobs import (
JOB_QUEUE,
claim_website_job,
due_website_jobs,
recover_interrupted_runs,
run_website_job,
save_website_job_result,
)
from .website_jobs import (
Result as WebsiteJobResult,
)
REDISPATCH_AFTER = timedelta(minutes=5)
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
@@ -137,6 +166,12 @@ def render_web_plan(plan_id):
@shared_task
def dispatch_web_activations():
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
IndependentWebsite,
provision_independent_website,
WEB_ACTIVATION_QUEUE,
condition=~Q(operation=IndependentWebsite.Operation.HTTPS),
)
dispatch_provisioning_jobs(
WebActivation, activate_web_plan, WEB_ACTIVATION_QUEUE
)
@@ -177,6 +212,12 @@ def dispatch_site_storage_limits():
@shared_task
def dispatch_web_https():
if settings.LOCAL_WEB_HTTPS:
dispatch_provisioning_jobs(
IndependentWebsite,
provision_independent_website,
WEB_HTTPS_QUEUE,
operation=IndependentWebsite.Operation.HTTPS,
)
dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE)
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
@@ -362,6 +403,27 @@ def plan_account_backup_expirations():
plan_backup_expirations(timezone.now())
@shared_task
def dispatch_offsite_backups():
if settings.LOCAL_ACCOUNT_BACKUPS and settings.OFFSITE_BACKUP_DESTINATIONS:
now = timezone.now()
finish_interrupted_transfers(now)
dispatch_provisioning_jobs(
OffsiteBackupTransfer,
transfer_offsite_backup,
OFFSITE_BACKUP_QUEUE,
lease=OFFSITE_BACKUP_LEASE,
attempts__lt=MAX_OFFSITE_ATTEMPTS,
**transfer_scope(now),
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def transfer_offsite_backup(job_id):
if settings.LOCAL_ACCOUNT_BACKUPS and settings.OFFSITE_BACKUP_DESTINATIONS:
run_offsite_transfer(job_id)
def dispatch_provisioning_jobs(
model, task, queue, *, lease=REDISPATCH_AFTER, condition=None, **scope
):
@@ -736,6 +798,11 @@ def apply_account_backup(job):
backup = AccountBackup.from_manifest(job.manifest)
if backup.website.account_id != job.account_id:
raise ValueError("The backup manifest belongs to a different account.")
current_sites = {website.spec for website in active_websites(job.account)}
if set(backup.additional_websites) - current_sites:
raise ValueError(
"An additional website is no longer available for backup."
)
if backup.mailboxes is not None:
if job.remote_mail:
if not settings.REMOTE_ACCOUNT_BACKUP_MAIL:
@@ -820,8 +887,15 @@ def restore_website(job_id):
def apply_website_restore(job):
account = job.backup.account
site = WebSite(account.pk, account.primary_domain)
if not job.backup.can_restore_website(site):
site = (
WebSite.from_manifest(job.site_manifest)
if job.site_manifest is not None
else WebSite(account.pk, account.primary_domain)
)
if (
available_website_restore_targets(job.backup).get(site.node_key)
!= site
):
raise ValueError("The backup no longer matches the current website.")
restore_local_website(
WebsiteRestoreRequest(
@@ -909,3 +983,63 @@ def run_provisioning_job(
except ValueError as error:
problem = str(error)
running.update(finished_at=timezone.now(), problem=problem, **updates)
@shared_task
def expire_sign_in_windows():
SignInWindow.objects.filter(slot__lt=current_window() - 1).delete()
@shared_task
def send_customer_password_reset(email):
send_customer_reset_email(email)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_independent_website(job_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
IndependentWebsite.objects.select_related(
"reservation__account__hosting_plan"
),
job_id,
apply_website_operation,
"Could not complete the request to the web node. Try again.",
)
@shared_task
def dispatch_website_jobs():
if not settings.WEBSITE_JOBS:
return
now = timezone.now()
recover_interrupted_runs(now)
due = due_website_jobs(now).values_list("pk", "account_id", "next_run_at")
for job_id, account_id, next_run in list(due[:100]):
execute_website_job.apply_async(
args=[account_id, job_id, next_run.isoformat()],
queue=JOB_QUEUE,
expires=90,
retry=False,
)
WebsiteScheduledJob.objects.filter(
pk=job_id, next_run_at=next_run
).update(dispatched_at=now)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def execute_website_job(account_id, job_id, scheduled_for):
if not settings.WEBSITE_JOBS:
return
request = claim_website_job(
account_id, job_id, datetime.fromisoformat(scheduled_for)
)
if request is None:
return
try:
result, code = run_website_job(request)
except (OSError, NodeReplyError):
result, code = WebsiteJobResult.UNCONFIRMED, None
except ValueError:
result, code = WebsiteJobResult.FAILED, None
save_website_job_result(job_id, request.run_id, result, code)
@@ -15,7 +15,9 @@
Manual
{% endif %}
</td>
<td>{% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %}</td>
<td>
{% if job.manifest.additional_websites %}Websites{% else %}Website{% endif %}{% if job.includes_mailboxes %}, databases, and mail{% else %} and databases{% endif %}
</td>
<td>
{% if job.expired_at %}
Expired
@@ -26,6 +28,28 @@
{% else %}
{{ job.state|capfirst }}
{% endif %}
{% with transfer=job.offsite_transfer %}
{% if transfer %}
<div>Off-site · {{ transfer.label }} · {{ transfer.status }}</div>
{% if transfer.verified_at %}
<div>{{ transfer.verified_at|date:"j M Y, H:i" }} UTC</div>
<details>
<summary>Recovery details</summary>
<div>Backup ID <code>{{ job.backup_id }}</code></div>
<div>Account ID <code>{{ job.account_id }}</code></div>
<div>Destination ID <code>{{ transfer.destination }}</code></div>
</details>
{% elif transfer.problem %}
<div>{{ transfer.problem }}</div>
{% if can_retry_offsite and transfer.status == "Failed" %}
<form method="post" action="{% url 'panel:retry_offsite_backup' account.pk job.pk %}">
{% csrf_token %}
<button type="submit" class="button secondary">Retry off-site copy</button>
</form>
{% endif %}
{% endif %}
{% endif %}
{% endwith %}
</td>
<td>
{% if job.expired_at %}
@@ -10,11 +10,17 @@
{% include "hosting/account_status.html" %}
</div>
</div>
{% if manage_sftp or export_backup_manifest or is_operator and perms.hosting.change_hostingaccount or can_retire_account %}
{% if primary_file_access or manage_website_jobs or manage_sftp or export_backup_manifest or is_operator and perms.hosting.change_hostingaccount or can_retire_account %}
<div class="form-actions">
{% if can_retire_account %}
<a class="button secondary" href="{% url 'panel:account_retirement' account.pk %}">Retire account</a>
{% endif %}
{% if primary_file_access %}
<a class="button secondary" href="{% url 'panel:website_files' account.pk %}">Website files</a>
{% endif %}
{% if manage_website_jobs %}
<a class="button secondary" href="{% url 'panel:website_jobs' account.pk %}">Scheduled jobs</a>
{% endif %}
{% if manage_sftp %}
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">SFTP access</a>
{% endif %}
@@ -39,12 +45,28 @@
{% endif %}
{% if is_operator and perms.hosting.view_customer %}
<div><dt>Customer</dt><dd>{{ account.customer|default_if_none:"Unassigned" }}</dd></div>
{% elif is_reseller %}
<div><dt>Customer</dt>
<dd>
{% if account.customer_id %}
{% if account.customer.reseller_id == account.reseller_id %}
{{ account.customer }}
{% else %}Assigned{% endif %}
{% else %}
<a class="record-link" href="{% url 'panel:reseller_customer_create' account.pk %}">Add customer login</a>
{% if reseller_customer_link %}
<a class="record-link" href="{% url 'panel:reseller_customer_link' account.pk %}">Link existing customer</a>
{% endif %}
{% endif %}
</dd>
</div>
{% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl>
<nav class="account-navigation" aria-label="On this account">
{% if can_change_hosting_services or service_change %}<a href="#service-access-heading">Services</a>{% endif %}
{% if show_website %}<a href="#account-website">Website</a>{% endif %}
{% if independent_websites or add_independent_website %}<a href="#independent-websites">Independent websites</a>{% endif %}
{% if is_tenant or perms.hosting.view_hostingdatabase %}<a href="#databases-heading">Databases</a>{% endif %}
{% if is_tenant or perms.hosting.view_hostingdnszone %}<a href="#dns-zones-heading">DNS</a>{% endif %}
{% if is_tenant or perms.hosting.view_hostingmailbox %}<a href="#mailboxes-heading">Mailboxes</a>{% endif %}
@@ -81,6 +103,9 @@
{% endif %}
</div>
{% endif %}
{% if independent_websites or add_independent_website %}
{% include "hosting/independent_websites.html" %}
{% endif %}
{% if is_tenant or perms.hosting.view_hostingdatabase %}
<section class="surface" aria-labelledby="databases-heading">
<header class="section-heading">
@@ -92,14 +117,14 @@
{% endif %}
{% endif %}
</div>
{% if is_customer or is_operator and perms.hosting.add_hostingdatabase %}
{% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingdatabase %}
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">Request database</a>
{% endif %}
</header>
{% if databases %}
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Database</th>{% if is_operator %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
<thead><tr><th scope="col">Database</th>{% if is_operator or manage_database_provisioning %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
<tbody>
{% for database in databases %}
<tr>
@@ -115,16 +140,18 @@
</form>
{% endif %}
</td>
{% if is_operator %}
{% if is_operator or manage_database_provisioning %}
<td>
<div class="form-actions">
<a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a>
{% if is_operator %}
<a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a>
{% endif %}
{% if manage_database_provisioning %}
{% url 'panel:database_provision' database.pk as provision_url %}
{% include "hosting/resource_provisioning.html" with provisioning=database.provisioning enabled=local_database_enabled action=provision_url resource=database provision_label="Provision database" %}
{% endif %}
</div>
{% if manage_database_provisioning and database.provisioning.problem %}
{% if is_operator and manage_database_provisioning and database.provisioning.problem %}
<p class="heading-meta">{{ database.provisioning.problem }}</p>
{% endif %}
</td>
@@ -231,7 +258,7 @@
{% endif %}
{% endif %}
</div>
{% if is_customer or is_operator and perms.hosting.add_hostingmailbox %}
{% if is_customer or reseller_resource_management or is_operator and perms.hosting.add_hostingmailbox %}
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">Request mailbox</a>
{% endif %}
</header>
@@ -242,7 +269,7 @@
<tr>
<th scope="col">Email address</th>
<th scope="col">Storage limit</th>
{% if is_operator %}<th scope="col">Deployment</th>{% endif %}
{% if is_operator or manage_mailbox_provisioning %}<th scope="col">Deployment</th>{% endif %}
</tr>
</thead>
<tbody>
@@ -264,10 +291,12 @@
{% endif %}
</td>
<td>{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
{% if is_operator %}
{% if is_operator or manage_mailbox_provisioning %}
<td>
<div class="form-actions">
<a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a>
{% if is_operator %}
<a class="record-link" href="{% url 'panel:mailbox_manifest' mailbox.pk %}" aria-label="Download mailbox manifest for {{ mailbox }}">Download manifest</a>
{% endif %}
{% if change_mailbox_quota %}
<a class="record-link" href="{% url 'panel:mailbox_quota' mailbox.pk %}" aria-label="Change storage limit for {{ mailbox }}">Change storage limit</a>
{% endif %}
@@ -276,7 +305,7 @@
{% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=local_mailbox_enabled action=provision_url resource=mailbox provision_label="Provision mailbox" %}
{% endif %}
</div>
{% if manage_mailbox_provisioning and mailbox.provisioning.problem %}
{% if is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %}
<p class="heading-meta">{{ mailbox.provisioning.problem }}</p>
{% endif %}
</td>
@@ -0,0 +1,15 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block public_content %}
<main class="sign-in">
<div class="sign-in-inner">
<div class="brand sign-in-brand">
<span class="brand-mark" aria-hidden="true">C</span>
<span>Coulobre <span class="brand-product">Panel</span></span>
</div>
<section class="sign-in-card">
{% block authentication_content %}{% include "hosting/authentication_card.html" %}{% endblock %}
</section>
</div>
</main>
{% endblock %}
@@ -0,0 +1,25 @@
<h1>{{ heading }}</h1>
{% if instructions %}<p>{{ instructions }}</p>{% endif %}
{% if code_notice %}<p role="status">{{ code_notice }}</p>{% endif %}
{% if configuration_url %}
<p><a href="{{ configuration_url }}" rel="noreferrer">Open in an authenticator app</a> or add a time-based account using this key.</p>
<p><code>{{ setup_key }}</code></p>
{% endif %}
{% if form %}
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
<button class="button primary" type="submit">{{ submit_label }}</button>
{% if email_factor %}
<button class="button secondary" type="submit" name="send_code" value="1" formnovalidate>Send email code</button>
{% endif %}
</form>
{% endif %}
{% if back_to_login %}<p><a href="{% url 'panel:login' %}">Back to sign-in</a></p>{% endif %}
{% if request.user.is_authenticated %}
<form method="post" action="{% url 'panel:logout' %}">
{% csrf_token %}
<button class="button secondary" type="submit">Sign out</button>
</form>
{% endif %}
@@ -7,7 +7,7 @@
<link rel="stylesheet" href="{% static 'hosting/panel.css' %}">
</head>
<body>
{% if request.user.is_authenticated %}
{% if request.user.is_authenticated and not auth_screen %}
<a class="skip-link" href="#main-content">Skip to content</a>
<div class="panel">
<aside class="sidebar">
@@ -27,7 +27,7 @@
Hosting accounts
</a>
{% endif %}
{% if is_operator and perms.hosting.view_customer %}
{% if is_reseller or is_operator and perms.hosting.view_customer %}
<a href="{% url 'panel:customers' %}"{% if panel_section == 'customers' %} aria-current="{% if current == 'customers' %}page{% else %}location{% endif %}"{% endif %}>
<span class="nav-icon nav-icon-customers" aria-hidden="true"></span>
Customers
@@ -1,15 +1,23 @@
{% extends "hosting/base.html" %}
{% block title %}Add customer · Coulobre Panel{% endblock %}
{% block title %}{{ title|default:"Add customer" }} · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'panel:customers' %}">← Customers</a>
<header class="page-heading"><h1>Add customer</h1></header>
{% if account %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
{% else %}
<a class="back-link" href="{% url 'panel:customers' %}">← Customers</a>
{% endif %}
<header class="page-heading"><h1>{{ title|default:"Add customer" }}</h1></header>
<section class="surface editor-surface">
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Add customer</button>
<a class="button secondary" href="{% url 'panel:customers' %}">Cancel</a>
<button class="button primary" type="submit">{{ title|default:"Add customer" }}</button>
{% if account %}
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
{% else %}
<a class="button secondary" href="{% url 'panel:customers' %}">Cancel</a>
{% endif %}
</div>
</form>
</section>
@@ -3,7 +3,7 @@
{% block content %}
<header class="page-heading">
<h1>Customers</h1>
{% if perms.hosting.add_customer %}
{% if is_operator and perms.hosting.add_customer %}
<a class="button primary" href="{% url 'panel:customer_create' %}">Add customer</a>
{% endif %}
</header>
@@ -21,7 +21,7 @@
<tr>
<th scope="col">Username</th>
<th scope="col">Sign-in status</th>
{% if perms.hosting.change_customer or can_impersonate %}<th scope="col">Actions</th>{% endif %}
{% if is_operator and perms.hosting.change_customer or can_impersonate %}<th scope="col">Actions</th>{% endif %}
</tr>
</thead>
<tbody>
@@ -32,7 +32,7 @@
{% if customer.user.is_active %}<span class="status active">Active</span>
{% else %}<span class="status suspended">Suspended</span>{% endif %}
</td>
{% if perms.hosting.change_customer or can_impersonate %}
{% if is_operator and perms.hosting.change_customer or can_impersonate %}
<td>
<div class="table-actions">
{% if perms.hosting.change_customer and not customer.user.is_staff and not customer.user.is_superuser and not customer.user.hosting_reseller %}
@@ -67,6 +67,8 @@
</div>
{% elif search %}
<p class="empty">No customers match this search.</p>
{% elif is_reseller %}
<p class="empty">Open an unassigned hosting account to add a customer login.</p>
{% else %}
<p class="empty">No customers yet.</p>
{% endif %}
@@ -0,0 +1,12 @@
{% extends "hosting/base.html" %}
{% block title %}Save your recovery codes · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><h1>Save your recovery codes</h1></header>
<section class="surface editor-surface">
<p>Keep these codes somewhere safe. Each code lets you sign in once if you lose access to your second factor.</p>
<ul>
{% for code in codes %}<li><code>{{ code }}</code></li>{% endfor %}
</ul>
<a class="button primary" href="{{ destination }}">Continue to the panel</a>
</section>
{% endblock %}
@@ -19,6 +19,7 @@
<th scope="col">Mailbox limit</th>
<th scope="col">Storage per new mailbox</th>
<th scope="col">Default website limit</th>
<th scope="col">Scheduled jobs</th>
<th scope="col">PHP overrides</th>
</tr>
</thead>
@@ -37,6 +38,7 @@
<td>{{ hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}</td>
<td>{% if hosting_plan.mailbox_quota_mib is not None %}{{ hosting_plan.mailbox_quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
<td>{% if hosting_plan.website_storage_limit_mib is not None %}{{ hosting_plan.website_storage_limit_mib }} MiB{% else %}Unlimited{% endif %}</td>
<td>{{ hosting_plan.website_job_limit }}</td>
<td>{% if hosting_plan.get_php_settings.has_overrides %}Configured{% else %}Server defaults{% endif %}</td>
</tr>
{% endfor %}
@@ -0,0 +1,24 @@
{% extends "hosting/base.html" %}
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}#independent-websites">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>{{ title }}</h1>
{% if website %}<p class="heading-meta domain">{{ website }}</p>{% endif %}
</div>
</header>
<section class="surface editor-surface">
{% if add %}<p>This website has its own document root and PHP runtime. Point the domain at this web server before enabling HTTPS.</p>{% endif %}
{% if retiring %}<p>Retirement takes this website offline and archives its files on the web server. Its domain stays reserved.</p>{% endif %}
{% if allowed_php_versions %}<p>Allowed PHP series {{ allowed_php_versions|join:", " }}</p>{% endif %}
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">{{ title }}</button>
<a class="button secondary" href="{{ account.get_absolute_url }}#independent-websites">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,47 @@
<section class="surface" aria-labelledby="independent-websites">
<header class="section-heading">
<h2 id="independent-websites" tabindex="-1">Independent websites</h2>
{% if add_independent_website %}<a class="button primary" href="{% url 'panel:independent_website_create' account.pk %}">Add website</a>{% endif %}
</header>
{% if independent_websites %}
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Domain</th><th scope="col">Status</th><th scope="col">PHP</th><th scope="col">Storage limit</th><th scope="col">Actions</th></tr>
</thead>
<tbody>
{% for website, actions in independent_websites %}
<tr>
<th scope="row" class="domain">{{ website }}</th>
<td>
{% if website.retired_at %}<span class="status suspended">Retired</span>
{% elif website.suspended or account.services_suspended %}<span class="status suspended">Suspended</span>
{% elif website.activated %}<span class="status ready">Active</span>
{% endif %}
{% if website.https_enabled %}<span class="status ready">HTTPS</span>{% endif %}
{% if website.state == "failed" %}<p role="status">{{ website.get_operation_display }} failed{% if is_operator %}. {{ website.problem }}{% endif %}</p>
{% elif website.state == "queued" or website.state == "running" %}<p role="status">{{ website.get_operation_display }} · {{ website.state }}</p>
{% endif %}
</td>
<td>{{ website.php_version|default:"—" }}</td>
<td>{% if website.storage_limit_mib %}{{ website.storage_limit_mib }} MiB{% elif website.activated %}Unlimited{% else %}—{% endif %}</td>
<td><div class="table-actions">
{% if manage_website_files and website.activated and not website.suspended and not website.retired_at %}
<a class="record-link" href="{% url 'panel:independent_website_files' account.pk website.pk %}">Files</a>
{% endif %}
{% for action in actions %}
<a class="record-link" href="{% url 'panel:independent_website_operation' account.pk website.pk action.value %}">{{ action.label }}</a>
{% endfor %}
{% if is_operator and perms.hosting.view_hostingaccount %}
<a class="record-link" href="{% url 'panel:independent_website_manifest' account.pk website.pk %}">Download manifest</a>
{% endif %}
</div></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="empty">No independent websites have been added.</p>
{% endif %}
</section>
@@ -15,6 +15,9 @@
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
<button class="button primary" type="submit">Sign in</button>
</form>
{% if password_reset_enabled %}
<p><a href="{% url 'panel:password_reset' %}">Forgot your password?</a></p>
{% endif %}
</section>
</div>
</main>
@@ -0,0 +1,6 @@
{% extends "hosting/authentication.html" %}
{% block title %}Password changed · Coulobre Panel{% endblock %}
{% block authentication_content %}
<h1>Password changed</h1>
<a class="button primary" href="{% url 'panel:login' %}">Sign in</a>
{% endblock %}
@@ -0,0 +1,15 @@
{% extends "hosting/authentication.html" %}
{% block title %}Choose a new password · Coulobre Panel{% endblock %}
{% block authentication_content %}
{% if validlink %}
<h1>Choose a new password</h1>
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<button class="button primary" type="submit">Change password</button>
</form>
{% else %}
<h1>Reset link expired or already used</h1>
<p><a href="{% url 'panel:password_reset' %}">Request a new link</a></p>
{% endif %}
{% endblock %}
@@ -0,0 +1,7 @@
{% extends "hosting/authentication.html" %}
{% block title %}Check your email · Coulobre Panel{% endblock %}
{% block authentication_content %}
<h1>Check your email</h1>
<p>If the address belongs to an eligible customer account, we will send a reset link.</p>
<p><a href="{% url 'panel:login' %}">Back to sign-in</a></p>
{% endblock %}
@@ -0,0 +1,5 @@
Use this link within 30 minutes to choose a new password for your Coulobre Panel account.
{{ protocol }}://{{ domain }}{% url 'panel:password_reset_confirm' uidb64=uid token=token %}
You can ignore this message if you did not request a password reset.
@@ -0,0 +1,12 @@
{% extends "hosting/authentication.html" %}
{% block title %}Reset your password · Coulobre Panel{% endblock %}
{% block authentication_content %}
<h1>Reset your password</h1>
<p>Enter the email address associated with your customer account.</p>
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<button class="button primary" type="submit">Request reset link</button>
</form>
<p><a href="{% url 'panel:login' %}">Back to sign-in</a></p>
{% endblock %}
@@ -0,0 +1 @@
Reset your Coulobre Panel password
@@ -10,6 +10,7 @@
</header>
<dl class="details surface">
<div><dt>Panel sign-in</dt><dd>{{ reseller.user.is_active|yesno:"Active,Suspended" }}</dd></div>
<div><dt>Database and mailbox management</dt><dd>{{ reseller.manage_resources|yesno:"Allowed,Operator only" }}</dd></div>
<div><dt>Accounts allocated</dt><dd>{{ account_count }} of {{ reseller.account_limit }}</dd></div>
{% if perms.hosting.view_hostingplan %}
<div>
@@ -67,6 +68,11 @@
{% if event.changes.account_limit %}
<div>Account limit {{ event.changes.account_limit.before|default_if_none:"—" }} → {{ event.changes.account_limit.after }}</div>
{% endif %}
{% if event.changes.customer %}<div>{{ event.changes.customer }}</div>{% endif %}
{% if event.changes.resource %}<div>{{ event.changes.type|capfirst }} {{ event.changes.resource }}</div>{% endif %}
{% if event.changes.manage_resources %}
<div>Database and mailbox management {{ event.changes.manage_resources.before|yesno:"allowed,operator only,—" }} → {{ event.changes.manage_resources.after|yesno:"allowed,operator only" }}</div>
{% endif %}
{% if event.changes.is_active %}
<div>Panel sign-in {{ event.changes.is_active.before|yesno:"active,suspended,—" }} → {{ event.changes.is_active.after|yesno:"active,suspended" }}</div>
{% endif %}
@@ -0,0 +1,24 @@
{% extends "hosting/base.html" %}
{% block title %}{% if action == "rename" %}Rename{% else %}Remove{% endif %} website entry · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ folder_url }}">← Website files</a>
<header class="page-heading">
<div>
<h1>{% if action == "rename" %}Rename{% else %}Remove{% endif %} website entry</h1>
<p class="heading-meta domain">{{ site.domain }}</p>
</div>
</header>
<section class="surface editor-surface">
<p class="file-name"><strong>{{ name }}</strong></p>
{% if action == "delete" %}<p>This removes the selected file or empty folder from the website.</p>{% endif %}
<form method="post" class="editor">
{% csrf_token %}
<input type="hidden" name="operation" value="{{ action }}">
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">{% if action == "rename" %}Rename{% else %}Remove{% endif %}</button>
<a class="button secondary" href="{{ folder_url }}">Cancel</a>
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,67 @@
{% extends "hosting/base.html" %}
{% block title %}Website files · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Website files</h1>
<p class="heading-meta domain">{{ site.domain }}</p>
</div>
</header>
<section class="surface" aria-labelledby="website-folder">
<nav aria-label="Website folder path">
<ol class="file-breadcrumbs" id="website-folder">
{% for name, url in breadcrumbs %}
<li>{% if forloop.last %}<span aria-current="location">{{ name }}</span>{% else %}<a href="{{ url }}">{{ name }}</a>{% endif %}</li>
{% endfor %}
</ol>
</nav>
<div class="file-forms">
<form class="editor" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="operation" value="upload">
{{ upload_form.as_div }}
<button class="button primary" type="submit">Upload</button>
</form>
<form class="editor" method="post">
{% csrf_token %}
<input type="hidden" name="operation" value="mkdir">
{{ folder_form.as_div }}
<button class="button secondary" type="submit">Create folder</button>
</form>
</div>
{% if entries %}
<div class="table-scroll">
<table class="file-table">
<thead>
<tr><th scope="col">Name</th><th scope="col">Size</th><th scope="col">Actions</th></tr>
</thead>
<tbody>
{% for entry in entries %}
<tr>
<th scope="row" class="file-name">
<a class="record-link" href="{{ entry.open_url }}" aria-label="{% if entry.is_directory %}Open folder{% else %}Download{% endif %} {{ entry.name }}">{{ entry.name }}</a>
</th>
<td>{% if entry.is_directory %}Folder{% else %}{{ entry.size|filesizeformat }}{% endif %}</td>
<td>
<div class="table-actions">
<a class="record-link" href="{{ entry.rename_url }}" aria-label="Rename {{ entry.name }}">Rename</a>
<a class="record-link" href="{{ entry.delete_url }}" aria-label="Remove {{ entry.name }}">Remove</a>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="empty">No files or folders on this page.</p>
{% endif %}
{% if next_url or first_url %}
<nav class="pagination" aria-label="File pages">
{% if first_url %}<a class="button secondary" href="{{ first_url }}">First page</a>{% endif %}
{% if next_url %}<a class="button secondary" href="{{ next_url }}">Next page</a>{% endif %}
</nav>
{% endif %}
</section>
{% endblock %}
@@ -0,0 +1,10 @@
{% extends "hosting/base.html" %}
{% block title %}Website files · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading"><h1>Website files</h1></header>
<section class="surface editor-surface">
<p role="alert">{{ problem }}</p>
<a class="button secondary" href="{{ root_url }}">Back to document root</a>
</section>
{% endblock %}
@@ -0,0 +1,22 @@
{% extends "hosting/base.html" %}
{% block title %}{% if job %}Edit{% else %}Add{% endif %} website job · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ list_url }}">← Scheduled website jobs</a>
<header class="page-heading">
<div>
<h1>{% if job %}Edit{% else %}Add{% endif %} website job</h1>
{% if job %}<p class="heading-meta domain">{{ job.domain }}</p>{% endif %}
</div>
</header>
<section class="surface editor-surface">
<form method="post" class="editor">
{% csrf_token %}
{{ form.as_div }}
<div class="form-actions">
<button class="button primary" type="submit">Save job</button>
<a class="button secondary" href="{{ list_url }}">Cancel</a>
{% if job %}<button class="button secondary" name="action" value="remove" type="submit" formnovalidate>Remove job</button>{% endif %}
</div>
</form>
</section>
{% endblock %}
@@ -0,0 +1,45 @@
{% extends "hosting/base.html" %}
{% block title %}Scheduled website jobs · Coulobre Panel{% endblock %}
{% block content %}
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
<header class="page-heading">
<div>
<h1>Scheduled website jobs</h1>
<p class="heading-meta">{{ rows|length }} of {{ limit }} saved jobs</p>
</div>
{% if add_job %}
<a class="button primary" href="{% url 'panel:website_job_create' account.pk %}">Add job</a>
{% endif %}
</header>
<section class="surface" aria-label="Scheduled website jobs">
{% if rows %}
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Job</th><th scope="col">Website</th><th scope="col">Schedule (UTC)</th><th scope="col">Next run</th><th scope="col">Last result</th></tr>
</thead>
<tbody>
{% for job, available in rows %}
<tr>
<th scope="row"><a class="record-link" href="{% url 'panel:website_job_edit' account.pk job.pk %}">{{ job.name }}</a></th>
<td class="domain">{{ job.domain }}</td>
<td><code>{{ job.expression }}</code></td>
<td>
{% if available and job.next_run_at %}{{ job.next_run_at|date:"j M Y, H:i" }} UTC
{% elif job.enabled %}Unavailable{% else %}Paused{% endif %}
</td>
<td>
{{ job.get_last_result_display|default:"Never run" }}
{% if job.last_exit_code is not None %}(exit {{ job.last_exit_code }}){% endif %}
{% if job.last_run_at %}<br>{{ job.last_run_at|date:"j M Y, H:i" }} UTC{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="empty">No website jobs scheduled.</p>
{% endif %}
</section>
{% endblock %}
@@ -5,7 +5,7 @@
<header class="page-heading">
<div>
<h1>Restore website</h1>
<p class="heading-meta">{{ account.primary_domain }} · Backup requested {{ backup.requested_at|date:"j M Y, H:i" }} UTC</p>
<p class="heading-meta">{% if restore_site %}{{ restore_site.domain }} · {% endif %}Backup requested {{ backup.requested_at|date:"j M Y, H:i" }} UTC</p>
</div>
</header>
<section class="surface editor-surface">
+1
View File
@@ -160,6 +160,7 @@ class CustomerAccessTests(TestCase):
self.assertRedirects(
self.client.get(admin_url),
f"{reverse('admin:login')}?next={admin_url}",
target_status_code=403,
)
def test_customer_requests_respect_database_and_mailbox_plan_limits(
@@ -0,0 +1,293 @@
from unittest.mock import patch
from uuid import uuid4
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.account_restore_request import component_filename
from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.web_node import WebSite
from coulobre.web_node_apply import SitePaths
from coulobre.web_node_tls import certbot_lineage
from .account_backups import account_backup_manifest
from .models import (
AccountBackupJob,
Customer,
HostingAccount,
HostingPlan,
IndependentWebsite,
WebsiteDomain,
WebsiteRestoreJob,
)
from .service_changes import apply_service_change, request_service_change
from .tasks import apply_website_restore, provision_independent_website
Operation = IndependentWebsite.Operation
class WebsiteIdentityTests(SimpleTestCase):
def test_independent_site_keeps_account_id_and_separate_node_paths(self):
primary = WebSite(17, "example.test")
child = WebSite(17, "shop.example.test", 17)
self.assertEqual(primary.manifest()["version"], 1)
self.assertEqual(child.manifest()["version"], 2)
self.assertEqual(WebSite.from_manifest(child.manifest()), child)
self.assertEqual(primary.service_user, "coulobre-17")
self.assertEqual(child.service_user, "coulobre-s17")
self.assertEqual(SitePaths.for_site(child).account.name, "s17")
self.assertEqual(certbot_lineage(child).name, "coulobre-s17")
self.assertIn(
"/srv/coulobre/web/s17/public",
child.render("apache"),
)
self.assertNotEqual(
SitePaths.for_site(child), SitePaths.for_site(primary)
)
def test_multisite_bundle_identifies_children_and_rejects_foreign_sites(
self,
):
primary = WebSite(17, "example.test")
child = WebSite(17, "shop.example.test", 19)
spec = AccountBackup(primary, (), additional_websites=(child,))
self.assertEqual(spec.manifest()["version"], 3)
self.assertEqual(AccountBackup.from_manifest(spec.manifest()), spec)
self.assertEqual(
component_filename(spec, child), "websites/s19.tar.gz"
)
self.assertIsNone(
component_filename(spec, WebSite(17, child.domain, 20))
)
with self.assertRaisesMessage(
ValueError, "belong to the backup account"
):
AccountBackup(
primary,
(),
additional_websites=(WebSite(42, child.domain, 19),),
)
@override_settings(
LOCAL_WEB_ACTIVATION=True,
LOCAL_WEB_HTTPS=True,
LOCAL_ACCOUNT_BACKUPS=True,
LOCAL_WEBSITE_RESTORE=True,
)
class IndependentWebsiteTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.owner = users.create_user("owner")
cls.outsider = users.create_user("outsider")
Customer.objects.create(user=cls.outsider)
cls.plan = HostingPlan.objects.create(
name="Two websites",
website_limit=2,
php_versions="8.4,8.5",
website_storage_limit_mib=200,
)
cls.account = HostingAccount.objects.create(
name="Example",
primary_domain="example.test",
customer=Customer.objects.create(user=cls.owner),
hosting_plan=cls.plan,
)
cls.other = HostingAccount.objects.create(
name="Elsewhere",
primary_domain="foreign.test",
customer=cls.outsider.hosting_customer,
)
def setUp(self):
self.client.force_login(self.owner)
self.add = reverse(
"panel:independent_website_create", args=[self.account.pk]
)
def create_website(self):
response = self.client.post(
self.add, {"domain": "SHOP.Example.Test.", "php_version": "8.4"}
)
self.assertRedirects(response, self.account.get_absolute_url())
return IndependentWebsite.objects.get()
def active_website(self):
website = self.create_website()
IndependentWebsite.objects.filter(pk=website.pk).update(
activated=True, php_version="8.4", finished_at=timezone.now()
)
website.refresh_from_db()
return website
def operation(self, website, action, data=None):
return self.client.post(
reverse(
"panel:independent_website_operation",
args=[self.account.pk, website.pk, action],
),
data or {},
)
def test_scoped_creation_and_quota_inherit_plan(self):
response = self.client.post(self.add, {"domain": "foreign.test"})
self.assertContains(response, "This domain is unavailable.")
response = self.client.post(
self.add, {"domain": "shop.example.test", "php_version": "8.3"}
)
self.assertContains(response, "outside the hosting plan")
website = self.create_website()
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"shop.example.test",
)
self.assertContains(
self.client.post(self.add, {"domain": "overflow.example.test"}),
"has reached its website limit",
)
with (
patch(
"coulobre.hosting.independent_websites.activate_local_site",
return_value=(PhpPoolSettings(), "8.4"),
) as activate,
patch(
"coulobre.hosting.independent_websites.set_local_site_storage_limit"
) as quota,
):
provision_independent_website.run(website.pk)
activate.assert_called_once_with(
website.spec, self.plan.get_php_settings(), ("8.4",)
)
quota.assert_called_once_with(website.spec, 200)
website.refresh_from_db()
self.assertEqual(website.storage_limit_mib, 200)
self.assertEqual(website.php_version, "8.4")
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"Change PHP series",
)
self.assertRedirects(
self.operation(website, Operation.PHP, {"php_version": "8.5"}),
self.account.get_absolute_url(),
)
with patch(
"coulobre.hosting.independent_websites.update_local_php_version",
return_value="8.5",
) as switch:
provision_independent_website.run(website.pk)
switch.assert_called_once_with(website.spec, "8.5")
website.refresh_from_db()
self.assertEqual(website.php_version, "8.5")
self.client.force_login(self.outsider)
self.assertEqual(self.client.get(self.add).status_code, 404)
self.assertEqual(
self.operation(website, Operation.SUSPEND).status_code, 404
)
def test_tls_and_retirement_leave_primary_reservation_intact(self):
website = self.active_website()
self.assertRedirects(
self.operation(website, Operation.HTTPS),
self.account.get_absolute_url(),
)
with patch(
"coulobre.hosting.independent_websites.enable_local_https"
) as tls:
provision_independent_website.run(website.pk)
tls.assert_called_once_with(website.spec)
self.assertRedirects(
self.operation(website, Operation.SUSPEND),
self.account.get_absolute_url(),
)
with patch(
"coulobre.hosting.independent_websites.apply_on_local_node"
) as node:
provision_independent_website.run(website.pk)
request = node.call_args.args[0]
self.assertEqual(request.resource, website.spec)
self.assertTrue(request.suspended)
self.assertContains(
self.operation(
website, Operation.RETIRE, {"confirmation": "wrong"}
),
"Enter the website domain exactly.",
)
self.assertRedirects(
self.operation(
website, Operation.RETIRE, {"confirmation": str(website)}
),
self.account.get_absolute_url(),
)
with patch(
"coulobre.hosting.independent_websites.apply_on_local_node"
) as node:
provision_independent_website.run(website.pk)
self.assertEqual(node.call_args.args[0].resource, website.spec)
website.refresh_from_db()
self.assertTrue(website.https_enabled)
self.assertIsNotNone(website.retired_at)
self.assertTrue(
WebsiteDomain.objects.filter(
account=self.account, is_primary=True
).exists()
)
self.assertContains(
self.client.post(self.add, {"domain": "shop.example.test"}),
"This domain is unavailable.",
)
def test_account_resume_preserves_an_independently_suspended_site(self):
website = self.active_website()
IndependentWebsite.objects.filter(pk=website.pk).update(suspended=True)
request_service_change(self.account.pk, "suspend", "operator")
self.account.service_changes.first().jobs.update(
finished_at=timezone.now(), applied_suspended=True
)
request_service_change(self.account.pk, "resume", "operator")
job = self.account.service_changes.first().jobs.get()
with patch(
"coulobre.hosting.service_changes.apply_on_local_node"
) as node:
apply_service_change(job)
self.assertEqual(node.call_args.args[0].resource, website.spec)
self.assertTrue(node.call_args.args[0].suspended)
def test_restore_selects_exact_website_from_account_archive(self):
website = self.active_website()
backup = AccountBackupJob.objects.create(
account=self.account,
manifest=account_backup_manifest(self.account),
finished_at=timezone.now(),
)
self.assertEqual(
backup.manifest["additional_websites"], [website.spec.manifest()]
)
self.client.force_login(self.operator)
location = reverse(
"panel:website_restore", args=[self.account.pk, backup.pk]
)
page = self.client.get(location)
self.assertContains(page, "shop.example.test")
data = {
"scope": "file",
"filename": "index.php",
"restore_id": uuid4(),
}
response = self.client.post(location, data | {"site_key": "s999"})
self.assertIn("site_key", response.context["form"].errors)
self.assertRedirects(
self.client.post(
location, data | {"site_key": website.spec.node_key}
),
self.account.get_absolute_url(),
)
job = WebsiteRestoreJob.objects.get()
self.assertEqual(job.site_manifest, website.spec.manifest())
with patch("coulobre.hosting.tasks.restore_local_website") as restore:
apply_website_restore(job)
self.assertEqual(restore.call_args.args[0].site, website.spec)
@@ -0,0 +1,266 @@
import json
from datetime import timedelta
from pathlib import Path
from unittest.mock import patch
from uuid import uuid4
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.offsite_backup import OffsiteBackupRequest, destination_labels
from coulobre.offsite_node import OffsiteRepositoryError, Repository
from coulobre.web_node import WebSite
from .account_backups import queue_account_backup, queue_due_account_backups
from .backup_retention import plan_backup_expirations
from .models import (
AccountBackupExpiration,
HostingAccount,
OffsiteBackupTransfer,
)
from .offsite_backups import MAX_ATTEMPTS, OFFSITE_BACKUP_QUEUE
from .tasks import dispatch_offsite_backups, transfer_offsite_backup
class OffsiteRepositoryTests(SimpleTestCase):
def test_destination_profiles_and_requests_are_bounded(self):
request = OffsiteBackupRequest(42, uuid4(), "vault")
self.assertEqual(
OffsiteBackupRequest.from_manifest(request.manifest()), request
)
for destination in ("../vault", "elsewhere:repo", "A", "two words"):
with (
self.subTest(destination=destination),
self.assertRaises(ValueError),
):
destination_labels({destination: "Fixture"})
self.assertNotIn("password", request.manifest())
def test_snapshot_lookup_checks_archive_identity_and_checksum_metadata(
self,
):
request = OffsiteBackupRequest(42, uuid4(), "vault")
repository = Repository(Path("/etc/coulobre/offsite/vault"))
entry = {
"id": "a" * 64,
"paths": [f"/{request.archive_name}"],
"tags": [request.tag, "coulobre-sha256-" + "b" * 64],
}
with patch.object(
Repository, "run", return_value=json.dumps([entry])
) as restic:
self.assertEqual(
repository.snapshot(request), ("a" * 64, "b" * 64)
)
restic.assert_called_once_with(
"--json", "snapshots", "--tag", request.tag, capture=True
)
for entries in ([entry, entry], [entry | {"paths": ["/another.zip"]}]):
with (
patch.object(
Repository, "run", return_value=json.dumps(entries)
),
self.assertRaises(OffsiteRepositoryError),
):
repository.snapshot(request)
@override_settings(
LOCAL_ACCOUNT_BACKUPS=True,
LOCAL_BACKUP_RETENTION=True,
OFFSITE_BACKUP_DESTINATIONS={"vault": "Off-site vault"},
)
class OffsiteBackupWorkflowTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.operator = get_user_model().objects.create_superuser("operator")
cls.account = HostingAccount.objects.create(
name="Off-site fixture",
primary_domain="example.test",
scheduled_backups_to_keep=1,
)
def setUp(self):
self.client.force_login(self.operator)
self.now = timezone.now()
self.history = reverse(
"panel:account_backup_archives", args=[self.account.pk]
)
self.schedule = reverse(
"panel:account_backup_schedule", args=[self.account.pk]
)
def archive(self, *, age=0, **values):
requested = self.now - timedelta(days=age)
spec = AccountBackup(
WebSite(self.account.pk, self.account.primary_domain), ()
)
return self.account.backup_jobs.create(
**(
{
"manifest": spec.manifest(),
"finished_at": requested,
"requested_at": requested,
"scheduled_for": requested,
}
| values
)
)
def transfer(self, archive=None, **values):
return OffsiteBackupTransfer.objects.create(
backup=self.archive() if archive is None else archive,
destination="vault",
next_attempt_at=self.now,
**values,
)
def test_only_scheduled_backups_capture_the_configured_destination(self):
response = self.client.post(
self.schedule,
{
"enabled": "on",
"frequency": "daily",
"time": "10:00",
"offsite_destination": "vault",
},
)
self.assertRedirects(response, self.account.get_absolute_url())
schedule = self.account.backup_schedule
self.assertEqual(schedule.offsite_destination, "vault")
schedule.next_run_at = self.now
schedule.save(update_fields=["next_run_at"])
queue_due_account_backups(self.now)
offsite = OffsiteBackupTransfer.objects.get()
self.assertEqual(offsite.backup.scheduled_for, self.now)
self.assertEqual(offsite.destination, "vault")
offsite.backup.finished_at = self.now
offsite.backup.save(update_fields=["finished_at"])
queue_account_backup(self.account.pk)
self.assertEqual(OffsiteBackupTransfer.objects.count(), 1)
self.assertTrue(
self.account.backup_jobs.filter(
scheduled_for__isnull=True
).exists()
)
self.assertContains(
self.client.post(
self.schedule,
{
"enabled": "on",
"frequency": "daily",
"time": "10:00",
"offsite_destination": "../../elsewhere",
},
),
"Select a valid choice",
)
def test_only_finished_local_archives_are_dispatched(self):
ready = self.transfer()
self.transfer(self.archive(finished_at=None))
self.transfer(self.archive(problem="Local backup failed"))
self.transfer(self.archive(expired_at=self.now))
with patch.object(transfer_offsite_backup, "apply_async") as publish:
dispatch_offsite_backups.run()
publish.assert_called_once_with(
args=[ready.pk],
queue=OFFSITE_BACKUP_QUEUE,
retry=False,
)
def test_retry_is_bounded_and_duplicate_delivery_does_not_reupload(self):
transfer = self.transfer()
with patch(
"coulobre.hosting.offsite_backups.apply_offsite_transfer",
side_effect=OSError("secret fixture"),
) as send:
for attempt in range(MAX_ATTEMPTS):
OffsiteBackupTransfer.objects.filter(pk=transfer.pk).update(
next_attempt_at=self.now
)
transfer_offsite_backup.run(transfer.pk)
transfer_offsite_backup.run(transfer.pk)
self.assertEqual(send.call_count, attempt + 1)
transfer.refresh_from_db()
self.assertIsNotNone(transfer.finished_at)
self.assertNotIn("secret fixture", transfer.problem)
self.assertContains(
self.client.get(self.history), "Retry off-site copy"
)
retry = reverse(
"panel:retry_offsite_backup",
args=[self.account.pk, transfer.backup_id],
)
self.assertRedirects(self.client.post(retry), self.history)
transfer.refresh_from_db()
self.assertEqual(transfer.attempts, 0)
with patch(
"coulobre.hosting.offsite_backups.apply_offsite_transfer",
return_value=("a" * 64, "b" * 64),
) as send:
transfer_offsite_backup.run(transfer.pk)
transfer_offsite_backup.run(transfer.pk)
send.assert_called_once()
transfer.refresh_from_db()
self.assertEqual(transfer.snapshot, "a" * 64)
self.assertEqual(transfer.sha256, "b" * 64)
self.assertIsNotNone(transfer.verified_at)
self.assertContains(
self.client.get(self.history), "Off-site vault · Verified"
)
self.assertEqual(self.client.post(retry).status_code, 409)
def test_retention_keeps_the_source_and_waits_for_a_verified_successor(
self,
):
previous = self.archive(age=3)
waiting = self.transfer(
self.archive(age=2), problem="Unavailable", finished_at=self.now
)
newest = self.transfer(self.archive(age=1))
plan_backup_expirations(self.now)
self.assertFalse(AccountBackupExpiration.objects.exists())
newest.verified_at = newest.finished_at = self.now
newest.save(update_fields=["verified_at", "finished_at"])
plan_backup_expirations(self.now)
expiration = AccountBackupExpiration.objects.get()
self.assertEqual(expiration.backup, previous)
self.assertEqual(expiration.keeper_ids, [str(newest.backup.backup_id)])
self.assertFalse(
AccountBackupExpiration.objects.filter(
backup=waiting.backup
).exists()
)
def test_retry_permission_and_account_scope(self):
transfer = self.transfer(finished_at=self.now, problem="Failed")
user = get_user_model().objects.create_user("limited-operator")
user.user_permissions.add(
*Permission.objects.filter(
codename__in=[
"view_hostingaccount",
"view_webprovisioningplan",
"view_hostingdatabase",
"add_accountbackupjob",
]
)
)
self.client.force_login(user)
retry = reverse(
"panel:retry_offsite_backup",
args=[self.account.pk, transfer.backup_id],
)
self.assertEqual(self.client.post(retry).status_code, 403)
self.client.force_login(self.operator)
other = HostingAccount.objects.create(
name="Foreign", primary_domain="foreign.test"
)
scoped = reverse(
"panel:retry_offsite_backup", args=[other.pk, transfer.backup_id]
)
self.assertEqual(self.client.post(scoped).status_code, 404)
@@ -0,0 +1,323 @@
from datetime import datetime, timedelta
from io import StringIO
from types import SimpleNamespace
from unittest.mock import patch
from urllib.parse import urlsplit
from django.contrib.auth import SESSION_KEY, get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.core import mail
from django.core.management import call_command
from django.test import Client, RequestFactory, TestCase, override_settings
from django.urls import reverse
from django_otp.oath import TOTP, totp
from django_otp.plugins.otp_email.models import EmailDevice
from django_otp.plugins.otp_totp.models import TOTPDevice
from .models import Customer, HostingAccount, PanelRecoveryCode, Reseller
from .sign_in_limits import client_address
from .tasks import send_customer_password_reset
PASSWORD = "test-password-for-panel"
NEW_PASSWORD = "rotated-password-for-a-customer"
@override_settings(
REQUIRE_PRIVILEGED_MFA=True,
EMAIL_HOST="smtp.example.test",
EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
PASSWORD_RESET_ORIGIN="https://panel.example.test",
)
class PanelAuthenticationTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser(
"operator", password=PASSWORD, email="operator@example.test"
)
cls.reseller = users.create_user(
"reseller", password=PASSWORD, email="reseller@example.test"
)
reseller = Reseller.objects.create(user=cls.reseller)
cls.customer = users.create_user(
"customer", password=PASSWORD, email="customer@example.test"
)
customer = Customer.objects.create(user=cls.customer)
cls.account = HostingAccount.objects.create(
name="Customer website",
primary_domain="customer.example.test",
reseller=reseller,
customer=customer,
)
cls.other = HostingAccount.objects.create(
name="Separate website", primary_domain="other.example.test"
)
def login(self, user, client=None, **fields):
client = client or self.client
return client.post(
reverse("panel:login"),
{"username": user.username, "password": PASSWORD, **fields},
)
def enroll_authenticator(self, user):
enroll = reverse("panel:factor_enroll")
confirm = reverse("panel:factor_confirm")
self.assertRedirects(self.login(user), enroll)
self.assertIn(SESSION_KEY, self.client.session)
self.assertContains(self.client.get(enroll), "Authenticator app")
self.assertNotContains(self.client.get(enroll), "Enrollment code")
self.assertRedirects(self.client.get(reverse("admin:index")), enroll)
self.assertRedirects(
self.client.post(enroll, {"method": "authenticator"}), confirm
)
device = TOTPDevice.objects.get(user=user)
response = self.client.post(
confirm, {"code": f"{totp(device.bin_key):06d}"}
)
self.assertContains(response, "Save your recovery codes")
self.assertIn("no-store", response.headers["Cache-Control"])
return response.context["codes"]
def test_first_password_login_enrolls_and_later_logins_require_a_factor(
self,
):
codes = self.enroll_authenticator(self.operator)
account = self.account.get_absolute_url()
self.assertContains(self.client.get(account), "Customer website")
self.assertEqual(PanelRecoveryCode.objects.count(), 10)
other_browser = Client()
verify = reverse("panel:factor_verify")
self.assertRedirects(
self.login(self.operator, other_browser, next=account), verify
)
self.assertNotIn(SESSION_KEY, other_browser.session)
self.assertRedirects(
other_browser.post(verify, {"code": codes[0]}), account
)
self.assertEqual(PanelRecoveryCode.objects.count(), 9)
fresh_browser = Client()
self.assertRedirects(self.login(self.operator, fresh_browser), verify)
self.assertContains(
fresh_browser.post(verify, {"code": codes[0]}),
"Invalid or unavailable code",
)
self.assertNotIn(SESSION_KEY, fresh_browser.session)
def test_later_sign_in_accepts_a_fresh_authenticator_code(self):
self.enroll_authenticator(self.operator)
device = TOTPDevice.objects.get(user=self.operator)
code_generator = TOTP(device.bin_key)
code_generator.time = (device.last_t + 1) * device.step + 1
browser = Client()
verify = reverse("panel:factor_verify")
self.assertRedirects(self.login(self.operator, browser), verify)
data = {"code": f"{code_generator.token():06d}"}
with patch(
"django_otp.plugins.otp_totp.models.time",
SimpleNamespace(time=lambda: code_generator.time),
):
self.assertRedirects(
browser.post(verify, data), reverse("panel:accounts")
)
another_browser = Client()
self.assertRedirects(
self.login(self.operator, another_browser), verify
)
self.assertContains(
another_browser.post(verify, data),
"Invalid or unavailable code",
)
def test_operator_recovery_requires_a_one_time_enrollment_code(self):
self.enroll_authenticator(self.operator)
output = StringIO()
call_command("issue_panel_enrollment", "operator", stdout=output)
code = output.getvalue().splitlines()[-1]
account = self.account.get_absolute_url()
self.assertRedirects(
self.client.get(account),
f"{reverse('panel:login')}?next={account}",
)
verify = reverse("panel:factor_verify")
enroll = reverse("panel:factor_enroll")
confirm = reverse("panel:factor_confirm")
self.assertRedirects(
self.login(self.operator), verify, fetch_redirect_response=False
)
self.assertRedirects(self.client.get(verify), enroll)
self.assertContains(
self.client.post(
enroll, {"method": "authenticator", "code": "wrong"}
),
"Could not start setup",
)
data = {"method": "authenticator", "code": code}
self.assertRedirects(self.client.post(enroll, data), confirm)
self.assertContains(
self.client.post(enroll, data), "Could not start setup"
)
self.assertEqual(PanelRecoveryCode.objects.count(), 0)
device = TOTPDevice.objects.get(user=self.operator)
self.assertContains(
self.client.post(confirm, {"code": f"{totp(device.bin_key):06d}"}),
"Save your recovery codes",
)
self.assertContains(self.client.get(account), "Customer website")
def test_email_factor_sends_to_the_saved_address_and_is_single_use(self):
enroll = reverse("panel:factor_enroll")
confirm = reverse("panel:factor_confirm")
self.assertRedirects(self.login(self.reseller), enroll)
self.assertContains(self.client.get(enroll), "Email code")
self.assertRedirects(
self.client.post(enroll, {"method": "email"}), confirm
)
self.assertContains(
self.client.post(
confirm, {"send_code": "1", "email": "ignored@example.test"}
),
"sent to the account email address",
)
device = EmailDevice.objects.get(user=self.reseller)
self.assertEqual(mail.outbox[0].to, ["reseller@example.test"])
self.assertIn(device.token, mail.outbox[0].body)
self.assertContains(
self.client.post(confirm, {"send_code": "1"}),
"Wait a minute",
)
self.assertEqual(len(mail.outbox), 1)
self.assertContains(
self.client.post(confirm, {"code": device.token}),
"Save your recovery codes",
)
self.assertEqual(
self.client.get(self.other.get_absolute_url()).status_code, 404
)
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"Customer website",
)
verify = reverse("panel:factor_verify")
new_client = Client()
self.assertRedirects(self.login(self.reseller, new_client), verify)
self.assertContains(
new_client.post(verify, {"code": device.token}),
"Invalid or unavailable code",
)
def test_customer_has_password_only_login_and_scoped_single_use_reset(
self,
):
self.assertRedirects(
self.login(self.customer), reverse("panel:accounts")
)
self.client.post(reverse("panel:logout"))
with patch.object(
send_customer_password_reset, "apply_async"
) as enqueue:
for email in (self.customer.email, "unknown@example.test"):
self.assertRedirects(
self.client.post(
reverse("panel:password_reset"), {"email": email}
),
reverse("panel:password_reset_done"),
)
self.assertEqual(enqueue.call_count, 2)
for email in (
self.customer.email,
self.operator.email,
"unknown@example.test",
):
send_customer_password_reset.run(email)
self.assertEqual(len(mail.outbox), 1)
reset_url = next(
line
for line in mail.outbox[0].body.splitlines()
if line.startswith("https:")
)
self.assertEqual(urlsplit(reset_url).netloc, "panel.example.test")
path = urlsplit(reset_url).path
another_browser = Client()
form_path = self.client.get(path)["Location"]
self.assertEqual(another_browser.get(path)["Location"], form_path)
data = {"new_password1": NEW_PASSWORD, "new_password2": NEW_PASSWORD}
response = self.client.post(form_path, data)
self.assertRedirects(
response, reverse("panel:password_reset_complete")
)
self.assertNotIn(SESSION_KEY, self.client.session)
self.assertContains(
another_browser.post(form_path, data),
"Reset link expired or already used",
)
self.customer.refresh_from_db()
self.assertTrue(self.customer.check_password(NEW_PASSWORD))
def test_expired_reset_link_displays_generic_error(self):
past = datetime(2026, 1, 1, 0, 0)
with patch.object(default_token_generator, "_now", return_value=past):
send_customer_password_reset.run(self.customer.email)
reset_path = urlsplit(
next(
line
for line in mail.outbox[0].body.splitlines()
if line.startswith("https:")
)
).path
with patch.object(
default_token_generator,
"_now",
return_value=past + timedelta(minutes=31),
):
self.assertContains(
self.client.get(reset_path),
"Reset link expired or already used",
)
def test_django_admin_uses_the_panel_login(self):
self.assertRedirects(
self.client.get(reverse("admin:login")),
f"{reverse('panel:login')}?next=/admin/",
)
self.client.force_login(self.operator)
response = self.client.get(reverse("admin:index"))
self.assertEqual(
response["Location"], f"{reverse('panel:login')}?next=/admin/"
)
class SignInLimitsTests(TestCase):
@override_settings(TRUST_APACHE_CLIENT_IP=True)
def test_forwarded_address_requires_the_unix_socket(self):
factory = RequestFactory()
request = factory.get(
"/",
HTTP_X_COULOBRE_CLIENT_IP="192.0.2.1",
REMOTE_ADDR="192.0.2.20",
)
self.assertEqual(client_address(request), "192.0.2.20")
request.META["REMOTE_ADDR"] = ""
self.assertEqual(client_address(request), "192.0.2.1")
request.META["HTTP_X_COULOBRE_CLIENT_IP"] = "192.0.2.1, 192.0.2.2"
self.assertEqual(client_address(request), "unknown")
@override_settings(TRUST_APACHE_CLIENT_IP=False)
def test_sign_in_limit_cannot_be_reset_with_a_forwarded_header(self):
url = reverse("panel:login")
for attempt in range(9):
response = self.client.post(
url,
{"username": "missing", "password": "wrong"},
REMOTE_ADDR="203.0.113.10",
HTTP_X_FORWARDED_FOR=f"192.0.2.{attempt + 1}",
HTTP_X_COULOBRE_CLIENT_IP=f"192.0.2.{attempt + 1}",
)
self.assertEqual(response.status_code, 429)
self.assertTrue(response["Retry-After"].isdigit())
response = self.client.post(
url,
{"username": "missing", "password": "wrong"},
REMOTE_ADDR="203.0.113.20",
)
self.assertEqual(response.status_code, 200)
@@ -0,0 +1,278 @@
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from .models import (
Customer,
DatabaseProvisioning,
HostingAccount,
HostingDatabase,
HostingMailbox,
HostingMailDomain,
HostingPlan,
MailboxProvisioning,
Reseller,
ResellerAuditEvent,
)
from .reseller_onboarding import request_reseller_resource
PASSWORD = "fixture-password-for-customer"
Action = ResellerAuditEvent.Action
@override_settings(
LOCAL_DATABASE_PROVISIONING=True,
LOCAL_MAILBOX_PROVISIONING=True,
)
class ResellerOnboardingTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.alice = Reseller.objects.create(
user=users.create_user("alice"), manage_resources=True
)
cls.bob = Reseller.objects.create(
user=users.create_user("bob"), manage_resources=True
)
cls.plan = HostingPlan.objects.create(
name="Small",
database_limit=1,
mailbox_limit=1,
mailbox_quota_mib=50,
)
cls.account = HostingAccount.objects.create(
name="Alice account",
primary_domain="alice.test",
reseller=cls.alice,
hosting_plan=cls.plan,
)
cls.second = HostingAccount.objects.create(
name="Second Alice account",
primary_domain="second.test",
reseller=cls.alice,
hosting_plan=cls.plan,
)
cls.other = HostingAccount.objects.create(
name="Bob account",
primary_domain="bob.test",
reseller=cls.bob,
hosting_plan=cls.plan,
)
cls.other_customer = Customer.objects.create(
user=users.create_user("bob-customer"), reseller=cls.bob
)
cls.operator_customer = Customer.objects.create(
user=users.create_user("operator-customer")
)
def setUp(self):
self.client.force_login(self.alice.user)
def post_customer(self, account, **overrides):
return self.client.post(
reverse("panel:reseller_customer_create", args=[account.pk]),
{
"username": "new-customer",
"email": "customer@example.test",
"password1": PASSWORD,
"password2": PASSWORD,
**overrides,
},
)
def test_create_and_link_a_customer_to_owned_accounts(self):
self.assertContains(
self.client.get(self.account.get_absolute_url()),
"Add customer login",
)
self.assertRedirects(
self.post_customer(self.account, reseller=self.bob.pk),
self.account.get_absolute_url(),
)
customer = Customer.objects.get(user__username="new-customer")
self.assertEqual(customer.reseller_id, self.alice.pk)
self.assertTrue(customer.user.check_password(PASSWORD))
self.assertEqual(customer.user.email, "customer@example.test")
self.assertFalse(customer.user.is_staff)
self.account.refresh_from_db()
self.assertEqual(self.account.customer_id, customer.pk)
url = reverse("panel:reseller_customer_link", args=[self.second.pk])
form = self.client.get(url)
self.assertContains(form, "new-customer")
self.assertNotContains(form, "bob-customer")
self.assertNotContains(form, "operator-customer")
for outsider in (self.other_customer, self.operator_customer):
response = self.client.post(url, {"customer": outsider.pk})
self.assertIn("customer", response.context["form"].errors)
self.assertRedirects(
self.client.post(url, {"customer": customer.pk}),
self.second.get_absolute_url(),
)
self.assertEqual(
set(customer.hostingaccount_set.values_list("pk", flat=True)),
{self.account.pk, self.second.pk},
)
self.assertEqual(self.post_customer(self.account).status_code, 404)
events = self.alice.audit_events.order_by("pk")
self.assertEqual(
list(
events.values_list(
"action", "actor_username", "account_domain"
)
),
[
(Action.CUSTOMER_CREATE, "alice", "alice.test"),
(Action.CUSTOMER_LINK, "alice", "second.test"),
],
)
self.assertEqual(events.first().changes, {"customer": "new-customer"})
self.client.force_login(customer.user)
self.assertContains(
self.client.get(self.second.get_absolute_url()), self.second.name
)
self.assertEqual(
self.client.get(self.other.get_absolute_url()).status_code, 404
)
self.client.force_login(self.bob.user)
self.assertNotContains(
self.client.get(reverse("panel:customers")), "new-customer"
)
self.assertContains(
self.client.get(reverse("panel:customers")), "bob-customer"
)
def test_reseller_cannot_create_a_customer_for_another_reseller(self):
self.assertEqual(self.post_customer(self.other).status_code, 404)
self.assertFalse(
Customer.objects.filter(user__username="new-customer").exists()
)
self.alice.user.user_permissions.set(
Permission.objects.filter(content_type__app_label="hosting")
)
url = reverse("panel:customer_access", args=[self.other_customer.pk])
self.assertEqual(
self.client.post(url, {"access": "suspend"}).status_code, 403
)
self.client.force_login(self.operator)
self.assertContains(
self.client.get(reverse("panel:customers")), "bob-customer"
)
self.assertRedirects(
self.client.post(url, {"access": "suspend"}),
reverse("panel:customers"),
)
def test_delegated_resource_management_preserves_limits_and_audits_jobs(
self,
):
database_url = reverse("panel:database_create", args=[self.account.pk])
mailbox_url = reverse("panel:mailbox_create", args=[self.account.pk])
detail = self.account.get_absolute_url()
self.assertRedirects(
self.client.post(database_url, {"suffix": "shop"}), detail
)
self.assertRedirects(
self.client.post(mailbox_url, {"local_part": "info"}), detail
)
self.assertContains(
self.client.post(database_url, {"suffix": "over"}),
"has reached its database limit",
)
self.assertContains(
self.client.post(mailbox_url, {"local_part": "over"}),
"has reached its mailbox limit",
)
database = HostingDatabase.objects.get(account=self.account)
mailbox = HostingMailbox.objects.get(mail_domain__account=self.account)
self.assertEqual(mailbox.quota_mib, 50)
for model, resource in (("database", database), ("mailbox", mailbox)):
url = reverse(f"panel:{model}_provision", args=[resource.pk])
manifest = reverse(f"panel:{model}_manifest", args=[resource.pk])
self.assertContains(self.client.get(detail), f"Provision {model}")
self.assertEqual(self.client.get(manifest).status_code, 403)
for _ in range(2):
self.assertRedirects(self.client.post(url), detail)
self.assertEqual(DatabaseProvisioning.objects.get().database, database)
self.assertEqual(MailboxProvisioning.objects.get().mailbox, mailbox)
self.assertEqual(
list(
self.alice.audit_events.order_by("pk").values_list(
"action", flat=True
)
),
[Action.RESOURCE_REQUEST] * 2 + [Action.RESOURCE_PROVISION] * 2,
)
DatabaseProvisioning.objects.update(
finished_at=timezone.now(), problem="Failed"
)
retry = reverse("panel:database_provision", args=[database.pk])
self.assertRedirects(self.client.post(retry), detail)
self.assertEqual(DatabaseProvisioning.objects.get().state, "queued")
self.assertEqual(
self.alice.audit_events.filter(
action=Action.RESOURCE_PROVISION
).count(),
3,
)
def test_resource_scope_and_policy_are_checked_for_each_request(self):
database = HostingDatabase.objects.create(
account=self.other, suffix="shop"
)
domain = HostingMailDomain.objects.create(
account=self.other, domain="bob.test"
)
mailbox = HostingMailbox.objects.create(
mail_domain=domain, local_part="info"
)
for model, resource in (("database", database), ("mailbox", mailbox)):
location = reverse(f"panel:{model}_provision", args=[resource.pk])
self.assertEqual(self.client.post(location).status_code, 404)
for model, values in (
("database", {"suffix": "test"}),
("mailbox", {"local_part": "test"}),
):
path = reverse(f"panel:{model}_create", args=[self.other.pk])
self.assertEqual(self.client.post(path, values).status_code, 404)
self.assertFalse(DatabaseProvisioning.objects.exists())
self.assertFalse(MailboxProvisioning.objects.exists())
original = request_reseller_resource
def revoke_before_save(*args, **kwargs):
Reseller.objects.filter(pk=self.alice.pk).update(
manage_resources=False
)
return original(*args, **kwargs)
path = reverse("panel:database_create", args=[self.account.pk])
with patch(
"coulobre.hosting.views.request_reseller_resource",
side_effect=revoke_before_save,
):
self.assertEqual(
self.client.post(path, {"suffix": "test"}).status_code, 403
)
self.assertFalse(self.account.databases.exists())
self.assertFalse(self.alice.audit_events.exists())
@override_settings(LOCAL_DATABASE_PROVISIONING=False)
def test_deployment_can_disable_a_provisioner(self):
database = HostingDatabase.objects.create(
account=self.account, suffix="shop"
)
path = reverse("panel:database_provision", args=[database.pk])
self.assertNotContains(
self.client.get(self.account.get_absolute_url()),
"Provision database",
)
self.assertEqual(self.client.post(path).status_code, 404)
self.assertFalse(DatabaseProvisioning.objects.exists())
+1
View File
@@ -126,6 +126,7 @@ class ResellerAccessTests(TestCase):
reverse("admin:hosting_hostingaccount_changelist")
),
reverse("admin:login") + "?next=/admin/hosting/hostingaccount/",
target_status_code=403,
)
self.assertEqual(WebProvisioningPlan.objects.count(), 2)
+278
View File
@@ -0,0 +1,278 @@
import os
from io import BytesIO
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from urllib.parse import urlencode
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.web_node import WebSite
from coulobre.web_node_files import (
OPEN_DIRECTORY,
create_directory,
list_folder,
open_download,
rename_entry,
upload_file,
)
from coulobre.website_files import UPLOAD_LIMIT, WebsiteFileRequest
from .models import (
Customer,
HostingAccount,
IndependentWebsite,
WebActivation,
WebProvisioningPlan,
WebsiteDomain,
)
from .website_file_client import (
WebsiteDownload,
WebsiteFileError,
validate_reply,
)
class FileReceiverTests(SimpleTestCase):
def setUp(self):
self.root = Path(self.enterContext(TemporaryDirectory()))
self.folder = os.open(self.root, OPEN_DIRECTORY)
self.addCleanup(os.close, self.folder)
self.uid = os.getuid()
self.gid = os.getgid()
self.device = self.root.stat().st_dev
def test_upload_is_complete_and_has_web_permissions(self):
upload_file(self.folder, "site.txt", 3, BytesIO(b"abc"), self.gid)
target = self.root / "site.txt"
self.assertEqual(target.read_bytes(), b"abc")
self.assertEqual(target.stat().st_uid, self.uid)
self.assertEqual(target.stat().st_gid, self.gid)
self.assertEqual(target.stat().st_mode & 0o777, 0o640)
with self.assertRaises(FileExistsError):
upload_file(self.folder, "site.txt", 3, BytesIO(b"xyz"), self.gid)
with self.assertRaisesMessage(
ValueError, "before the file was complete"
):
upload_file(self.folder, "missing.txt", 3, BytesIO(b"a"), self.gid)
self.assertEqual(list(self.root.iterdir()), [target])
self.assertEqual(target.read_bytes(), b"abc")
def test_folder_listing_and_download_use_regular_owned_entries(self):
create_directory(self.folder, "assets", self.gid)
(self.root / "site.txt").write_text("example")
(self.root / "link").symlink_to("site.txt")
(self.root / ".coulobre-upload-pending").touch()
os.mkfifo(self.root / "fifo")
listing = list_folder(self.folder, "", self.uid, self.device)
self.assertEqual(
listing["entries"],
[
{"name": "assets", "is_directory": True, "size": 0},
{"name": "site.txt", "is_directory": False, "size": 7},
],
)
with self.assertRaisesMessage(ValueError, "unavailable"):
open_download(self.folder, "link", self.uid, self.device)
source, size = open_download(
self.folder, "site.txt", self.uid, self.device
)
with source:
self.assertEqual(source.read(), b"example")
self.assertEqual(size, 7)
with self.assertRaises(FileExistsError):
rename_entry(self.folder, "site.txt", "assets")
rename_entry(self.folder, "site.txt", "renamed.txt")
self.assertTrue((self.root / "renamed.txt").is_file())
def test_protocol_rejects_paths_outside_the_site_and_oversized_uploads(
self,
):
site = WebSite(4, "example.test")
for parent in ("..", "../assets", "/assets", "assets//images"):
with self.subTest(parent=parent), self.assertRaises(ValueError):
WebsiteFileRequest(site, "list", parent)
for name in (
"/file",
"one/two.txt",
".",
"folder\\file",
".coulobre-upload-x",
):
with self.subTest(name=name), self.assertRaises(ValueError):
WebsiteFileRequest(site, "delete", name=name)
with self.assertRaisesMessage(ValueError, "at most 64 MiB"):
WebsiteFileRequest(
site, "upload", name="big.txt", size=UPLOAD_LIMIT + 1
)
request = WebsiteFileRequest(
site, "download", "assets", "document.txt"
)
self.assertEqual(
WebsiteFileRequest.from_manifest(request.manifest()), request
)
with self.assertRaisesMessage(WebsiteFileError, "invalid file reply"):
validate_reply(
{"version": 1, "state": "ready", "identity": "other"}, request
)
@override_settings(WEB_FILE_MANAGER=True)
class WebsiteFilePanelTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.owner = users.create_user("owner")
cls.other_user = users.create_user("other")
cls.staff = users.create_user("operator")
customer = Customer.objects.create(user=cls.owner)
other_customer = Customer.objects.create(user=cls.other_user)
cls.account = HostingAccount.objects.create(
name="Owned account",
primary_domain="example.test",
customer=customer,
)
cls.other = HostingAccount.objects.create(
name="Other account",
primary_domain="other.test",
customer=other_customer,
)
for account in (cls.account, cls.other):
plan = WebProvisioningPlan.objects.create(
account=account,
primary_domain=account.primary_domain,
completed_at=timezone.now(),
apache_config="fixture",
)
WebActivation.objects.create(plan=plan, finished_at=timezone.now())
reservation = WebsiteDomain.objects.create(
account=cls.account, domain="shop.example.test"
)
cls.website = IndependentWebsite.objects.create(
reservation=reservation, activated=True, finished_at=timezone.now()
)
cls.primary_url = reverse("panel:website_files", args=[cls.account.pk])
cls.website_url = reverse(
"panel:independent_website_files",
args=[cls.account.pk, cls.website.pk],
)
def setUp(self):
self.client.force_login(self.owner)
def test_list_and_download_use_exact_independent_website(self):
with patch(
"coulobre.hosting.website_file_views.request_website_files",
return_value={
"entries": [
{"name": "note.txt", "size": 5, "is_directory": False}
],
"after": "",
},
) as node:
response = self.client.get(self.website_url, {"path": "content"})
self.assertContains(response, "shop.example.test")
self.assertContains(response, "Download note.txt")
self.assertEqual(node.call_args.args[0].site, self.website.spec)
connection = BytesIO()
with patch(
"coulobre.hosting.website_file_views.request_website_files",
return_value=WebsiteDownload(connection, BytesIO(b"hello"), 5),
):
response = self.client.get(
self.website_url,
{"path": "content", "name": "note.txt", "action": "download"},
)
self.assertEqual(
response["Content-Disposition"], 'attachment; filename="note.txt"'
)
self.assertEqual(response["X-Content-Type-Options"], "nosniff")
self.assertIn("no-store", response["Cache-Control"])
self.assertEqual(b"".join(response.streaming_content), b"hello")
self.assertTrue(connection.closed)
def test_upload_and_delete_confirmation(self):
upload = SimpleUploadedFile("site.txt", b"example")
with patch(
"coulobre.hosting.website_file_views.request_website_files"
) as node:
self.assertRedirects(
self.client.post(
self.primary_url, {"operation": "upload", "file": upload}
),
self.primary_url,
fetch_redirect_response=False,
)
self.assertEqual(node.call_args.args[0].size, 7)
self.assertEqual(
node.call_args.args[0].site,
WebSite(self.account.pk, "example.test"),
)
url = (
self.primary_url
+ "?"
+ urlencode({"action": "delete", "name": "site.txt"})
)
with patch(
"coulobre.hosting.website_file_views.request_website_files"
) as node:
self.assertContains(self.client.get(url), "Confirm removal")
response = self.client.post(url, {"operation": "delete"})
self.assertIn("confirm", response.context["form"].errors)
node.assert_not_called()
self.assertRedirects(
self.client.post(
url, {"operation": "delete", "confirm": "on"}
),
self.primary_url,
fetch_redirect_response=False,
)
self.assertEqual(node.call_args.args[0].operation, "delete")
def test_scope_and_suspension_are_checked_before_the_receiver(self):
other_url = reverse("panel:website_files", args=[self.other.pk])
with patch(
"coulobre.hosting.website_file_views.request_website_files"
) as node:
self.assertEqual(self.client.get(other_url).status_code, 404)
self.assertEqual(
self.client.get(self.primary_url, {"path": ".."}).status_code,
400,
)
IndependentWebsite.objects.filter(pk=self.website.pk).update(
suspended=True
)
self.assertEqual(
self.client.get(self.website_url).status_code, 409
)
HostingAccount.objects.filter(pk=self.account.pk).update(
services_suspended=True
)
self.assertEqual(
self.client.get(self.primary_url).status_code, 409
)
node.assert_not_called()
def test_operator_requires_website_file_permission(self):
self.client.force_login(self.staff)
self.staff.user_permissions.add(
Permission.objects.get(codename="view_hostingaccount")
)
self.assertEqual(self.client.get(self.primary_url).status_code, 403)
self.staff.user_permissions.add(
Permission.objects.get(codename="manage_website_files")
)
with patch(
"coulobre.hosting.website_file_views.request_website_files",
return_value={"entries": [], "after": ""},
):
self.assertContains(
self.client.get(self.primary_url), "Document root"
)
+327
View File
@@ -0,0 +1,327 @@
import json
from datetime import UTC, datetime, timedelta
from io import BytesIO, StringIO
from types import SimpleNamespace
from unittest.mock import patch
from uuid import uuid4
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre.web_node import WebSite
from coulobre.web_node_jobs import serve_website_job
from coulobre.website_job import WebsiteJobRequest
from .models import (
Customer,
HostingAccount,
HostingPlan,
IndependentWebsite,
WebActivation,
WebProvisioningPlan,
WebsiteDomain,
WebsiteScheduledJob,
)
from .node_client import encode_manifest
from .tasks import dispatch_website_jobs, execute_website_job
from .website_job_schedule import next_website_run
from .website_jobs import (
JOB_QUEUE,
Result,
claim_website_job,
recover_interrupted_runs,
)
NOW = datetime(2026, 11, 23, 10, 15, tzinfo=UTC)
CLOCK = "django.utils.timezone.now"
class WebsiteJobReceiverTests(SimpleTestCase):
def test_receiver_accepts_the_client_protocol_without_echoing_commands(
self,
):
request = WebsiteJobRequest(
WebSite(42, "example.test"), uuid4().hex, "exit 7"
)
request_body = BytesIO(encode_manifest(request.manifest()))
response = StringIO()
with (
patch("sys.stdin", SimpleNamespace(buffer=request_body)),
patch("sys.stdout", response),
patch(
"coulobre.web_node_jobs.execute_website_job",
return_value={"timed_out": False, "exit_code": 7},
) as execute,
):
self.assertEqual(serve_website_job(), 0)
execute.assert_called_once_with(request)
self.assertEqual(
json.loads(response.getvalue()),
{
"run_id": request.run_id,
"state": "configured",
"problem": None,
"timed_out": False,
"exit_code": 7,
},
)
class WebsiteJobScheduleTests(SimpleTestCase):
def test_utc_schedule_advances_to_the_next_matching_minute(self):
self.assertEqual(
next_website_run("*/15 * * * *", NOW),
NOW + timedelta(minutes=15),
)
self.assertEqual(
next_website_run("0 8 * * mon", NOW),
datetime(2026, 11, 30, 8, tzinfo=UTC),
)
self.assertEqual(
next_website_run("0 0 29 2 *", NOW),
datetime(2028, 2, 29, tzinfo=UTC),
)
self.assertEqual(
next_website_run("0 0 1 * mon", NOW),
datetime(2027, 2, 1, tzinfo=UTC),
)
def test_unsafe_or_impossible_schedules_are_rejected(self):
for value in (
"* * * * *",
"0,58 * * * *",
"*/0 * * * *",
"*/5/5 * * * *",
"0, * * * *",
"61 * * * *",
"0 0 31 2 *",
"@daily",
):
with self.subTest(value=value), self.assertRaises(ValueError):
next_website_run(value, NOW)
@override_settings(WEBSITE_JOBS=True)
class WebsiteJobWorkflowTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.user = users.create_user("site-owner")
cls.operator = users.create_user("operator")
cls.plan = HostingPlan.objects.create(name="Web", website_job_limit=2)
cls.account = HostingAccount.objects.create(
name="Site account",
primary_domain="example.test",
hosting_plan=cls.plan,
customer=Customer.objects.create(user=cls.user),
)
cls.foreign = HostingAccount.objects.create(
name="Another account",
primary_domain="foreign.test",
hosting_plan=cls.plan,
)
activation = WebProvisioningPlan.objects.create(
account=cls.account,
primary_domain=cls.account.primary_domain,
completed_at=timezone.now(),
)
WebActivation.objects.create(
plan=activation, finished_at=timezone.now()
)
for account, tag in ((cls.account, "shop"), (cls.foreign, "foreign")):
reservation = WebsiteDomain.objects.create(
account=account, domain=f"{tag}.example.test"
)
website = IndependentWebsite.objects.create(
reservation=reservation,
activated=True,
finished_at=timezone.now(),
)
if tag == "shop":
cls.site = website
else:
cls.foreign_site = website
cls.jobs_url = reverse("panel:website_jobs", args=[cls.account.pk])
cls.add_url = reverse(
"panel:website_job_create", args=[cls.account.pk]
)
def setUp(self):
self.client.force_login(self.user)
def form(self, **overrides):
return {
"site": "primary",
"name": "Refresh catalogue",
"expression": "*/15 * * * *",
"command": '"$PHP_CLI" refresh.php',
"enabled": "on",
**overrides,
}
def job(self, **overrides):
return self.account.website_jobs.create(
**(
{
"domain": self.account.primary_domain,
"name": "Due job",
"command": "true",
"expression": "*/15 * * * *",
"next_run_at": NOW,
}
| overrides
)
)
def test_customer_can_add_pause_and_remove_a_job_for_its_own_site(self):
self.assertContains(
self.client.get(self.account.get_absolute_url()), "Scheduled jobs"
)
with patch(CLOCK, return_value=NOW):
self.assertRedirects(
self.client.post(self.add_url, self.form(site=self.site.pk)),
self.jobs_url,
)
job = self.account.website_jobs.get()
self.assertEqual(job.website, self.site)
self.assertEqual(job.next_run_at, NOW + timedelta(minutes=15))
self.assertContains(
self.client.get(self.jobs_url), "shop.example.test"
)
edit = reverse(
"panel:website_job_edit", args=[self.account.pk, job.pk]
)
self.assertRedirects(
self.client.post(
edit, self.form(site=self.foreign_site.pk, enabled="")
),
self.jobs_url,
)
job.refresh_from_db()
self.assertEqual(job.website, self.site)
self.assertFalse(job.enabled)
self.assertIsNone(job.next_run_at)
self.assertRedirects(
self.client.post(edit, {"action": "remove"}), self.jobs_url
)
self.assertFalse(self.account.website_jobs.exists())
def test_customer_cannot_access_foreign_accounts_or_choose_foreign_sites(
self,
):
foreign_url = reverse("panel:website_jobs", args=[self.foreign.pk])
self.assertEqual(self.client.get(foreign_url).status_code, 404)
self.assertContains(
self.client.post(
self.add_url, self.form(site=self.foreign_site.pk)
),
"Select a valid choice",
)
self.assertFalse(WebsiteScheduledJob.objects.exists())
def test_holding_paused_jobs_counts_toward_the_plan_limit(self):
self.job()
self.job(enabled=False, next_run_at=None)
self.assertContains(
self.client.post(self.add_url, self.form()),
"has reached its scheduled job limit",
)
self.assertEqual(self.account.website_jobs.count(), 2)
def test_operator_needs_permission_and_feature_is_optional(self):
self.client.force_login(self.operator)
self.operator.user_permissions.add(
Permission.objects.get(codename="view_hostingaccount")
)
self.assertEqual(self.client.get(self.jobs_url).status_code, 403)
self.operator.user_permissions.add(
Permission.objects.get(codename="manage_website_jobs")
)
self.assertEqual(self.client.get(self.jobs_url).status_code, 200)
with self.settings(WEBSITE_JOBS=False):
self.assertEqual(self.client.get(self.jobs_url).status_code, 404)
def test_due_run_is_dispatched_and_only_claimed_once(self):
job = self.job()
with (
patch(CLOCK, return_value=NOW),
patch.object(execute_website_job, "apply_async") as publish,
patch(
"coulobre.hosting.tasks.run_website_job",
return_value=(Result.FAILED, 7),
) as run,
):
dispatch_website_jobs.run()
dispatch_website_jobs.run()
publish.assert_called_once_with(
args=[self.account.pk, job.pk, NOW.isoformat()],
queue=JOB_QUEUE,
expires=90,
retry=False,
)
for _ in range(2):
execute_website_job.run(*publish.call_args.kwargs["args"])
run.assert_called_once()
self.assertEqual(run.call_args.args[0].site.domain, "example.test")
job.refresh_from_db()
self.assertEqual(job.next_run_at, NOW + timedelta(minutes=15))
self.assertEqual(job.last_result, Result.FAILED)
self.assertEqual(job.last_exit_code, 7)
self.assertIsNone(job.run_token)
def test_missed_and_out_of_plan_runs_advance_without_running(self):
old_slot = NOW - timedelta(minutes=15)
missed = self.job(next_run_at=old_slot)
extra = self.job()
self.plan.website_job_limit = 1
self.plan.save(update_fields=["website_job_limit"])
with patch(CLOCK, return_value=NOW):
self.assertIsNone(
claim_website_job(self.account.pk, missed.pk, old_slot)
)
self.assertIsNone(
claim_website_job(self.account.pk, extra.pk, NOW)
)
for job in (missed, extra):
job.refresh_from_db()
self.assertEqual(job.next_run_at, NOW + timedelta(minutes=15))
self.assertIsNone(job.last_run_at)
def test_suspension_or_retirement_prevents_a_run(self):
job = self.job(website=self.site, domain=self.site.spec.domain)
for marker in (
{"suspended": True},
{"suspended": False, "operation": "retire", "finished_at": None},
{"retired_at": NOW, "finished_at": NOW},
):
IndependentWebsite.objects.filter(pk=self.site.pk).update(**marker)
WebsiteScheduledJob.objects.filter(pk=job.pk).update(
next_run_at=NOW
)
with patch(CLOCK, return_value=NOW):
self.assertIsNone(
claim_website_job(self.account.pk, job.pk, NOW)
)
HostingAccount.objects.filter(pk=self.account.pk).update(
services_suspended=True
)
primary = self.job()
with patch(CLOCK, return_value=NOW):
self.assertIsNone(
claim_website_job(self.account.pk, primary.pk, NOW)
)
def test_lost_worker_result_is_marked_unconfirmed_without_replay(self):
job = self.job()
with patch(CLOCK, return_value=NOW):
self.assertIsNotNone(
claim_website_job(self.account.pk, job.pk, NOW)
)
recover_interrupted_runs(NOW + timedelta(minutes=4))
job.refresh_from_db()
self.assertEqual(job.last_result, Result.UNCONFIRMED)
self.assertIsNone(job.run_token)
self.assertEqual(job.next_run_at, NOW + timedelta(minutes=15))
+103 -7
View File
@@ -1,13 +1,28 @@
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.views import LogoutView
from django.urls import path
from . import views
from .backup_restores import RestoreKind
from .credential_views import DatabaseCredentialView, MailboxCredentialView
from .health_views import ServiceHealthView
from .independent_website_views import (
IndependentWebsiteCreate,
IndependentWebsiteManifest,
IndependentWebsiteOperation,
)
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
from .mail_policy_views import MailRoutingEditor, MailVacationEditor
from .password_reset import (
CustomerPasswordResetView,
CustomerResetCompleteView,
CustomerResetConfirmView,
CustomerResetDoneView,
)
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
from .reseller_onboarding_views import (
ResellerCustomerCreate,
ResellerCustomerLink,
)
from .reseller_views import (
ResellerCreate,
ResellerDetail,
@@ -16,6 +31,14 @@ from .reseller_views import (
)
from .retirement_views import RetirementList, RetirementView
from .roundcube import RoundcubeLaunch, redeem_roundcube
from .sign_in import (
ConfirmFactorView,
EnrollFactorView,
PanelLoginView,
VerifyFactorView,
)
from .website_file_views import WebsiteFilesView
from .website_job_views import WebsiteJobEditor, WebsiteJobList
app_name = "panel"
@@ -24,13 +47,31 @@ urlpatterns = [
path(
"service-health/", ServiceHealthView.as_view(), name="service_health"
),
path("sign-in/", PanelLoginView.as_view(), name="login"),
path("sign-in/verify/", VerifyFactorView.as_view(), name="factor_verify"),
path("sign-in/enroll/", EnrollFactorView.as_view(), name="factor_enroll"),
path(
"sign-in/",
LoginView.as_view(
template_name="hosting/login.html",
redirect_authenticated_user=True,
),
name="login",
"sign-in/confirm/", ConfirmFactorView.as_view(), name="factor_confirm"
),
path(
"password-reset/",
CustomerPasswordResetView.as_view(),
name="password_reset",
),
path(
"password-reset/requested/",
CustomerResetDoneView.as_view(),
name="password_reset_done",
),
path(
"password-reset/<uidb64>/<token>/",
CustomerResetConfirmView.as_view(),
name="password_reset_confirm",
),
path(
"password-reset/complete/",
CustomerResetCompleteView.as_view(),
name="password_reset_complete",
),
path("sign-out/", LogoutView.as_view(), name="logout"),
path(
@@ -43,6 +84,56 @@ urlpatterns = [
name="account_retirement",
),
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
path(
"accounts/<int:pk>/files/",
WebsiteFilesView.as_view(),
name="website_files",
),
path(
"accounts/<int:pk>/website-jobs/",
WebsiteJobList.as_view(),
name="website_jobs",
),
path(
"accounts/<int:pk>/website-jobs/new/",
WebsiteJobEditor.as_view(),
name="website_job_create",
),
path(
"accounts/<int:pk>/website-jobs/<int:job_pk>/",
WebsiteJobEditor.as_view(),
name="website_job_edit",
),
path(
"accounts/<int:pk>/websites/<int:site_pk>/files/",
WebsiteFilesView.as_view(),
name="independent_website_files",
),
path(
"accounts/<int:pk>/websites/new/",
IndependentWebsiteCreate.as_view(),
name="independent_website_create",
),
path(
"accounts/<int:pk>/websites/<int:site_pk>/manifest/",
IndependentWebsiteManifest.as_view(),
name="independent_website_manifest",
),
path(
"accounts/<int:pk>/websites/<int:site_pk>/<str:operation>/",
IndependentWebsiteOperation.as_view(),
name="independent_website_operation",
),
path(
"accounts/<int:pk>/customers/new/",
ResellerCustomerCreate.as_view(),
name="reseller_customer_create",
),
path(
"accounts/<int:pk>/customers/link/",
ResellerCustomerLink.as_view(),
name="reseller_customer_link",
),
path(
"accounts/<int:pk>/service-access/",
views.ChangeHostingServices.as_view(),
@@ -93,6 +184,11 @@ urlpatterns = [
views.AccountBackupArchiveList.as_view(),
name="account_backup_archives",
),
path(
"accounts/<int:pk>/backups/<int:backup_pk>/offsite/retry/",
views.RetryOffsiteBackup.as_view(),
name="retry_offsite_backup",
),
path(
"accounts/<int:pk>/backups/retention/",
views.EditBackupRetention.as_view(),
+200 -49
View File
@@ -33,7 +33,6 @@ from coulobre.dns_node import MAX_SOA_SERIAL
from coulobre.mail_node import INVALID_LOCAL_PART
from coulobre.php_runtime import available_php_versions
from coulobre.sftp_keys import public_key_fingerprint
from coulobre.web_node import WebSite
from .access import (
OperatorOnlyMixin,
@@ -60,7 +59,9 @@ from .account_backups import (
from .backup_restores import (
RestoreKind,
available_restore_resources,
available_website_restore_targets,
current_restore_resources,
current_website_restore_targets,
enabled_component_restores,
queue_component_restore,
queue_website_restore,
@@ -79,6 +80,11 @@ from .impersonation import (
start_impersonation,
support_write_session,
)
from .independent_websites import (
account_websites,
website_actions,
website_limit,
)
from .mail_policy_views import mail_policy_enabled
from .models import (
AccountBackupJob,
@@ -97,6 +103,7 @@ from .models import (
WebsiteDomain,
WebsiteRestoreJob,
)
from .offsite_backups import retry_offsite_transfer
from .php_settings import (
SitePhpSettingsForm,
last_applied_php_settings,
@@ -114,6 +121,11 @@ from .php_versions import (
)
from .phpmyadmin import phpmyadmin_available
from .reseller_accounts import create_reseller_account, save_operator_account
from .reseller_onboarding import (
provision_reseller_resource,
request_reseller_resource,
scoped_customers,
)
from .resource_requests import (
change_mailbox_quota,
create_database_request,
@@ -150,6 +162,9 @@ from .website_aliases import (
queue_alias_operation,
queue_website_alias,
)
from .website_file_views import can_manage_website_files
from .website_job_views import can_manage_website_jobs
from .website_jobs import website_job_limit
VIEW_ACCOUNTS = "hosting.view_hostingaccount"
CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
@@ -174,6 +189,10 @@ MANAGE_BACKUP_SCHEDULE = (
*MANAGE_ACCOUNT_BACKUPS,
"hosting.change_accountbackupschedule",
)
RETRY_OFFSITE_BACKUP = (
*MANAGE_ACCOUNT_BACKUPS,
"hosting.change_offsitebackuptransfer",
)
MANAGE_BACKUP_RETENTION = (
*MANAGE_ACCOUNT_BACKUPS,
VIEW_MAILBOXES,
@@ -365,6 +384,44 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
reseller = reseller_for_user(user)
customer = customer_for_user(user)
tenant = reseller is not None or customer is not None
manage_resources = reseller is not None and reseller.manage_resources
context["reseller_resource_management"] = manage_resources
context["reseller_customer_link"] = reseller is not None and (
self.object.customer_id is None
and scoped_customers(reseller)
.filter(user__is_active=True)
.exists()
)
manage_files = (
not self.object.services_suspended
and can_manage_website_files(self.request)
)
context["manage_website_files"] = manage_files
context["manage_website_jobs"] = can_manage_website_jobs(
self.request
) and (
website_job_limit(self.object) > 0
or self.object.website_jobs.exists()
)
context["primary_file_access"] = manage_files and site_is_active(
self.object
)
if settings.LOCAL_WEB_ACTIVATION or manage_files:
websites = list(account_websites(self.object))
can_manage = (
settings.LOCAL_WEB_ACTIVATION
and not self.object.services_suspended
and (tenant or user.has_perm(CHANGE_ACCOUNTS))
and getattr(self.request, "impersonation", None) is None
)
context["independent_websites"] = [
(website, website_actions(website) if can_manage else ())
for website in websites
]
context["add_independent_website"] = can_manage and (
sum(website.retired_at is None for website in websites) + 1
< website_limit(self.object)
)
context["can_retire_account"] = not tenant and user.has_perms(
RETIRE_ACCOUNTS
)
@@ -470,6 +527,7 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
):
can_view_mailboxes = user.has_perm(VIEW_MAILBOXES)
context["show_account_backups"] = True
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP)
context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -532,7 +590,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
] and roundcube_available(self.request)
if tenant or user.has_perm(VIEW_DATABASES):
databases = self.object.databases.all()
if not tenant and user.has_perms(PROVISION_DATABASE):
if manage_resources or (
not tenant and user.has_perms(PROVISION_DATABASE)
):
databases = databases.select_related("provisioning")
context["manage_database_provisioning"] = True
context["local_database_enabled"] = (
@@ -573,14 +633,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
mailboxes = HostingMailbox.objects.filter(
mail_domain__account=self.object
).select_related("mail_domain")
if not tenant and user.has_perms(PROVISION_MAILBOX):
if manage_resources or (
not tenant and user.has_perms(PROVISION_MAILBOX)
):
mailboxes = mailboxes.select_related("provisioning")
context["manage_mailbox_provisioning"] = True
context["local_mailbox_enabled"] = (
settings.LOCAL_MAILBOX_PROVISIONING
)
context["change_mailbox_quota"] = user.has_perms(
CHANGE_MAILBOX_QUOTA
context["change_mailbox_quota"] = (
not tenant and user.has_perms(CHANGE_MAILBOX_QUOTA)
)
if context.get("show_webmail"):
mailboxes = list(
@@ -942,9 +1004,9 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
def visible_account_backups(account, user):
backups = account.backup_jobs.select_related("expiration").order_by(
"-requested_at", "-pk"
)
backups = account.backup_jobs.select_related(
"expiration", "offsite_transfer"
).order_by("-requested_at", "-pk")
if not user.has_perm(VIEW_MAILBOXES):
backups = backups.exclude(manifest__has_key="mailboxes")
return backups
@@ -973,6 +1035,7 @@ class AccountBackupArchiveList(
def get_context_data(self, **kwargs):
context = super().get_context_data(account=self.account, **kwargs)
user = self.request.user
context["can_retry_offsite"] = user.has_perms(RETRY_OFFSITE_BACKUP)
context["manage_backup_retention"] = (
settings.LOCAL_BACKUP_RETENTION
and user.has_perms(MANAGE_BACKUP_RETENTION)
@@ -992,6 +1055,25 @@ class AccountBackupArchiveList(
return context
class RetryOffsiteBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = RETRY_OFFSITE_BACKUP
def post(self, request, pk, backup_pk):
if not settings.LOCAL_ACCOUNT_BACKUPS:
raise Http404
account = get_object_or_404(HostingAccount, pk=pk)
backup = get_object_or_404(
visible_account_backups(account, request.user),
pk=backup_pk,
offsite_transfer__isnull=False,
)
try:
retry_offsite_transfer(backup.offsite_transfer)
except ValidationError as error:
return provisioning_conflict(error)
return redirect("panel:account_backup_archives", pk=pk)
class BackupRetentionView(
OperatorOnlyMixin, PermissionRequiredMixin, FormView
):
@@ -1097,11 +1179,11 @@ def backup_restore_context(account, user, backups, can_view_mailboxes):
]
)
if settings.LOCAL_WEBSITE_RESTORE:
site = WebSite(account.pk, account.primary_domain)
current = current_website_restore_targets(account)
context["website_restore_sources"] = {
backup.pk
for backup in backups
if backup.can_restore_website(site)
if available_website_restore_targets(backup, current)
}
if kinds:
history.extend(
@@ -1178,11 +1260,24 @@ class RequestWebsiteRestore(BackupRestoreView):
def get_backup(self):
backup = super().get_backup()
site = WebSite(backup.account_id, backup.account.primary_domain)
if not backup.can_restore_website(site):
if not available_website_restore_targets(backup):
raise Http404
return backup
def get_form_kwargs(self):
return super().get_form_kwargs() | {
"targets": available_website_restore_targets(self.backup)
}
def get_context_data(self, **kwargs):
targets = available_website_restore_targets(self.backup)
return super().get_context_data(
restore_site=next(iter(targets.values()))
if len(targets) == 1
else None,
**kwargs,
)
def queue_restore(self, backup, data, operator_username):
queue_website_restore(
backup,
@@ -1190,6 +1285,7 @@ class RequestWebsiteRestore(BackupRestoreView):
filename=data["filename"],
replace=data["replace"],
operator_username=operator_username,
site_key=data.get("site_key"),
)
@@ -1393,7 +1489,7 @@ class SiteSFTPKeys(PermissionRequiredMixin, FormView):
return super().form_valid(form)
class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
class CustomerList(TenantScopeMixin, PermissionRequiredMixin, ListView):
queryset = Customer.objects.select_related(
"user__hosting_reseller"
).order_by("user__username")
@@ -1404,7 +1500,10 @@ class CustomerList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
def get_queryset(self):
self.search = self.request.GET.get("q", "").strip()[:150]
reseller = reseller_for_user(self.request.user)
queryset = super().get_queryset()
if reseller is not None:
queryset = queryset.filter(pk__in=scoped_customers(reseller))
if self.search:
queryset = queryset.filter(user__username__icontains=self.search)
return queryset
@@ -1529,17 +1628,22 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
def customer(self):
return customer_for_user(self.request.user)
@cached_property
def reseller(self):
return reseller_for_user(self.request.user)
def has_permission(self):
return self.customer is not None or (
reseller_for_user(self.request.user) is None
and super().has_permission()
)
if self.reseller is not None:
return self.reseller.manage_resources
return self.customer is not None or super().has_permission()
@cached_property
def account(self):
accounts = HostingAccount.objects.filter(retired_at__isnull=True)
if self.customer is not None:
accounts = accounts.filter(customer=self.customer)
if self.reseller is not None:
accounts = accounts.filter(reseller=self.reseller)
return get_object_or_404(accounts, pk=self.kwargs["pk"])
def get_context_data(self, **kwargs):
@@ -1559,13 +1663,21 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
def form_valid(self, form):
try:
with support_write_session(self.request) as session:
self.object = self.create_request(
self.account.pk,
**form.cleaned_data,
customer_id=self.customer.pk
if self.customer is not None
else None,
)
if self.reseller is not None:
self.object = request_reseller_resource(
self.reseller,
self.account.pk,
self.create_request,
form.cleaned_data,
)
else:
self.object = self.create_request(
self.account.pk,
**form.cleaned_data,
customer_id=self.customer.pk
if self.customer is not None
else None,
)
if session is not None:
CustomerImpersonationAction.objects.create(
session=session,
@@ -1609,22 +1721,53 @@ class DownloadDatabaseManifest(
)
class RequestDatabaseProvisioning(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
permission_required = PROVISION_DATABASE
class ResourceProvisioningRequest(PermissionRequiredMixin, View):
@cached_property
def reseller(self):
return reseller_for_user(self.request.user)
def has_permission(self):
if self.reseller is not None:
return self.reseller.manage_resources
return (
customer_for_user(self.request.user) is None
and super().has_permission()
)
def post(self, request, pk):
if not settings.LOCAL_DATABASE_PROVISIONING:
if not getattr(settings, self.enabled_setting):
raise Http404
database = get_object_or_404(
HostingDatabase.objects.select_related("account"), pk=pk
)
queryset = self.queryset.all()
if self.reseller is not None:
queryset = queryset.filter(
**{f"{self.account_relation}__reseller": self.reseller}
)
resource = get_object_or_404(queryset, pk=pk)
account = self.get_account(resource)
try:
queue_database_provisioning(database)
if self.reseller is None:
self.provision(resource)
else:
provision_reseller_resource(
self.reseller, account.pk, self.provision, resource
)
except HostingAccount.DoesNotExist as error:
raise Http404 from error
except ValidationError as error:
return provisioning_conflict(error)
return redirect(database.account)
return redirect(account)
class RequestDatabaseProvisioning(ResourceProvisioningRequest):
permission_required = PROVISION_DATABASE
enabled_setting = "LOCAL_DATABASE_PROVISIONING"
queryset = HostingDatabase.objects.select_related("account")
account_relation = "account"
provision = staticmethod(queue_database_provisioning)
@staticmethod
def get_account(database):
return database.account
class DnsZoneEditor(PermissionRequiredMixin, FormView):
@@ -1905,23 +2048,16 @@ class MailboxQuotaEdit(OperatorOnlyMixin, PermissionRequiredMixin, UpdateView):
return redirect(self.object.mail_domain.account)
class RequestMailboxProvisioning(
OperatorOnlyMixin, PermissionRequiredMixin, View
):
class RequestMailboxProvisioning(ResourceProvisioningRequest):
permission_required = PROVISION_MAILBOX
enabled_setting = "LOCAL_MAILBOX_PROVISIONING"
queryset = HostingMailbox.objects.select_related("mail_domain__account")
account_relation = "mail_domain__account"
provision = staticmethod(queue_mailbox_provisioning)
def post(self, request, pk):
if not settings.LOCAL_MAILBOX_PROVISIONING:
raise Http404
mailbox = get_object_or_404(
HostingMailbox.objects.select_related("mail_domain__account"),
pk=pk,
)
try:
queue_mailbox_provisioning(mailbox)
except ValidationError as error:
return provisioning_conflict(error)
return redirect(mailbox.mail_domain.account)
@staticmethod
def get_account(mailbox):
return mailbox.mail_domain.account
class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
@@ -1937,6 +2073,8 @@ class HostingPlanEditor:
fields = (
"name",
"description",
"website_limit",
"website_job_limit",
"database_limit",
"mailbox_limit",
"mailbox_quota_mib",
@@ -1952,6 +2090,19 @@ class HostingPlanEditor:
template_name = "hosting/hosting_plan_form.html"
success_url = reverse_lazy("panel:hosting_plans")
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
if "data" in kwargs:
defaults = {"website_limit": 1, "website_job_limit": 0}
missing = defaults.keys() - kwargs["data"].keys()
if missing:
data = kwargs["data"].copy()
instance = kwargs.get("instance")
for field in missing:
data[field] = getattr(instance, field, defaults[field])
kwargs["data"] = data
return kwargs
class HostingPlanCreate(
OperatorOnlyMixin, PermissionRequiredMixin, HostingPlanEditor, CreateView
+122
View File
@@ -0,0 +1,122 @@
import socket
from contextlib import ExitStack, suppress
from coulobre.node_stream import STREAM_CHUNK_SIZE, encode_header, read_header
from coulobre.website_files import (
FILE_SOCKET,
LIST_PAGE_SIZE,
RESPONSE_HEADER_LIMIT,
validate_entry_name,
)
CONNECTION_TIMEOUT = 60
class WebsiteFileError(ValueError):
pass
def request_website_files(request, *, upload=None):
with ExitStack() as connection:
client = connection.enter_context(
socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
)
client.settimeout(CONNECTION_TIMEOUT)
client.connect(FILE_SOCKET)
try:
client.sendall(encode_header(request.manifest()))
if upload is not None:
for chunk in upload.chunks(STREAM_CHUNK_SIZE):
client.sendall(chunk)
except (BrokenPipeError, ConnectionResetError):
# The receiver can reply before the upload finishes.
with suppress(OSError):
client.shutdown(socket.SHUT_WR)
else:
client.shutdown(socket.SHUT_WR)
source = connection.enter_context(client.makefile("rb"))
response = validate_reply(
read_header(
source,
maximum=RESPONSE_HEADER_LIMIT,
label="website file reply",
),
request,
)
if request.operation == "download":
return WebsiteDownload(
connection.pop_all(), source, response["size"]
)
return response
def validate_reply(response, request):
invalid = "The web node returned an invalid file reply."
if (
not isinstance(response, dict)
or type(response.get("version")) is not int
or response["version"] != 1
or response.get("identity") != request.identity()
):
raise WebsiteFileError(invalid)
if response.get("state") == "failed" and isinstance(
response.get("problem"), str
):
raise WebsiteFileError(response["problem"][:400])
if response.get("state") != "ready":
raise WebsiteFileError(invalid)
if request.operation == "download" and not valid_size(
response.get("size")
):
raise WebsiteFileError(invalid)
if request.operation == "list":
validate_listing(response, invalid)
return response
def valid_size(value):
return type(value) is int and 0 <= value < 2**63
def validate_listing(response, message):
entries = response.get("entries")
after = response.get("after")
if not isinstance(entries, list) or len(entries) > LIST_PAGE_SIZE:
raise WebsiteFileError(message)
try:
for entry in entries:
if (
not isinstance(entry, dict)
or type(entry.get("is_directory")) is not bool
or not valid_size(entry.get("size"))
):
raise ValueError
validate_entry_name(entry.get("name"))
if after != "":
validate_entry_name(after)
if not entries or entries[-1]["name"] != after:
raise ValueError
except ValueError:
raise WebsiteFileError(message) from None
class WebsiteDownload:
def __init__(self, connection, stream, size):
self.connection = connection
self.stream = stream
self.size = size
def __iter__(self):
remaining = self.size
try:
while remaining:
chunk = self.stream.read(min(remaining, STREAM_CHUNK_SIZE))
if not chunk:
raise OSError("The website file download ended early.")
remaining -= len(chunk)
yield chunk
finally:
self.close()
def close(self):
self.connection.close()
+296
View File
@@ -0,0 +1,296 @@
from urllib.parse import urlencode
from django import forms
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.http import Http404, StreamingHttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.utils.http import content_disposition_header
from django.views import View
from django.views.decorators.cache import never_cache
from django.views.generic.detail import SingleObjectMixin
from coulobre.web_node import WebSite
from coulobre.website_files import (
UPLOAD_LIMIT,
WebsiteFileRequest,
directory_parts,
)
from .access import TenantScopeMixin, is_tenant
from .independent_websites import active_websites
from .models import HostingAccount
from .resource_requests import require_active_services
from .sftp import site_is_active
from .website_file_client import request_website_files
MANAGE_FILES = ("hosting.view_hostingaccount", "hosting.manage_website_files")
UNAVAILABLE = "The website files service is unavailable. Try again later."
def can_manage_website_files(request):
user = request.user
return (
settings.WEB_FILE_MANAGER
and getattr(request, "impersonation", None) is None
and (is_tenant(user) or user.has_perms(MANAGE_FILES))
)
class WebsiteUploadForm(forms.Form):
file = forms.FileField(
label="File to upload",
allow_empty_file=True,
help_text="Maximum upload size 64 MiB.",
)
def clean_file(self):
upload = self.cleaned_data["file"]
if upload.size > UPLOAD_LIMIT:
raise forms.ValidationError("Uploads can be at most 64 MiB.")
return upload
class FolderCreateForm(forms.Form):
name = forms.CharField(label="Folder name", max_length=255, strip=False)
class RenameEntryForm(forms.Form):
target = forms.CharField(label="New name", max_length=255, strip=False)
class DeleteEntryForm(forms.Form):
confirm = forms.BooleanField(label="Confirm removal")
@method_decorator(never_cache, name="dispatch")
class WebsiteFilesView(
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, View
):
queryset = HostingAccount.objects.filter(retired_at__isnull=True)
customer_relation = "customer"
permission_required = MANAGE_FILES
def dispatch(self, request, *args, **kwargs):
if not settings.WEB_FILE_MANAGER:
raise Http404
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_manage_website_files(self.request)
@cached_property
def account(self):
return self.get_object()
@cached_property
def site(self):
if "site_pk" not in self.kwargs:
if not site_is_active(self.account):
raise Http404
return WebSite(self.account.pk, self.account.primary_domain)
website = get_object_or_404(
active_websites(self.account), pk=self.kwargs["site_pk"]
)
if website.suspended:
raise ValidationError("This website is suspended.")
return website.spec
@property
def directory(self):
return self.request.GET.get("path", "")
def url(self, directory="", **query):
data = {"path": directory} if directory else {}
data.update(query)
return self.request.path + ("?" + urlencode(data) if data else "")
def context(self):
crumbs = [("Document root", self.url())]
parts = directory_parts(self.directory)
for index, part in enumerate(parts, start=1):
crumbs.append((part, self.url("/".join(parts[:index]))))
return {
"account": self.account,
"site": self.site,
"breadcrumbs": crumbs,
}
def get(self, request, *args, **kwargs):
try:
require_active_services(self.account)
action = request.GET.get("action", "")
if action == "download":
return self.download()
if action in ("rename", "delete"):
return self.entry_form(action)
return self.folder()
except ValidationError as error:
return self.unavailable(" ".join(error.messages), 409)
except ValueError as error:
return self.unavailable(str(error), 400)
except OSError:
return self.unavailable(UNAVAILABLE, 503)
def post(self, request, *args, **kwargs):
try:
require_active_services(self.account)
action = request.POST.get("operation")
if action in ("rename", "delete"):
return self.entry_form(action, data=request.POST)
if action == "upload":
form = WebsiteUploadForm(request.POST, request.FILES)
if form.is_valid():
upload = form.cleaned_data["file"]
request_website_files(
WebsiteFileRequest(
self.site,
"upload",
self.directory,
upload.name,
size=upload.size,
),
upload=upload,
)
return redirect(self.url(self.directory))
return self.folder(upload_form=form)
if action == "mkdir":
form = FolderCreateForm(request.POST)
if form.is_valid():
request_website_files(
WebsiteFileRequest(
self.site,
"mkdir",
self.directory,
form.cleaned_data["name"],
)
)
return redirect(self.url(self.directory))
return self.folder(folder_form=form)
raise ValueError("Choose a supported website file operation.")
except ValidationError as error:
return self.unavailable(" ".join(error.messages), 409)
except ValueError as error:
return self.unavailable(str(error), 400)
except OSError:
return self.unavailable(UNAVAILABLE, 503)
def unavailable(self, problem, status):
return render(
self.request,
"hosting/website_files_error.html",
{
"account": self.account,
"problem": problem,
"root_url": self.url(),
},
status=status,
)
def folder(self, *, upload_form=None, folder_form=None):
listing = request_website_files(
WebsiteFileRequest(
self.site,
"list",
self.directory,
after=self.request.GET.get("after", ""),
)
)
entries = []
for entry in listing["entries"]:
name = entry["name"]
path = "/".join(filter(None, (self.directory, name)))
entries.append(
entry
| {
"open_url": (
self.url(path)
if entry["is_directory"]
else self.url(
self.directory, action="download", name=name
)
),
"rename_url": self.url(
self.directory, action="rename", name=name
),
"delete_url": self.url(
self.directory, action="delete", name=name
),
}
)
return render(
self.request,
"hosting/website_files.html",
self.context()
| {
"entries": entries,
"upload_form": upload_form
if upload_form is not None
else WebsiteUploadForm(),
"folder_form": folder_form
if folder_form is not None
else FolderCreateForm(),
"next_url": (
self.url(self.directory, after=listing["after"])
if listing["after"]
else ""
),
"first_url": self.url(self.directory)
if self.request.GET.get("after")
else "",
},
)
def download(self):
name = self.request.GET.get("name", "")
download = request_website_files(
WebsiteFileRequest(self.site, "download", self.directory, name)
)
response = StreamingHttpResponse(
download, content_type="application/octet-stream"
)
response["Content-Length"] = download.size
response["Content-Disposition"] = content_disposition_header(
True, name
)
response["X-Content-Type-Options"] = "nosniff"
return response
def entry_form(self, action, data=None):
name = self.request.GET.get("name", "")
# Validate the name without acting on the entry.
WebsiteFileRequest(self.site, "delete", self.directory, name)
form = (
RenameEntryForm(data)
if action == "rename"
else DeleteEntryForm(data)
)
if form.is_bound and form.is_valid():
try:
request_website_files(
WebsiteFileRequest(
self.site,
action,
self.directory,
name,
target=form.cleaned_data.get("target", ""),
)
)
except ValueError as error:
form.add_error(None, str(error))
else:
return redirect(self.url(self.directory))
return render(
self.request,
"hosting/website_file_action.html",
self.context()
| {
"action": action,
"name": name,
"form": form,
"folder_url": self.url(self.directory),
},
)
@@ -0,0 +1,76 @@
import re
from bisect import bisect_right
from calendar import monthrange
from datetime import UTC, datetime
from celery.schedules import ParseException, crontab
MIN_INTERVAL = 5
MINUTES_PER_DAY = 24 * 60
CRON_VALUE = r"(?:[a-zA-Z]+|[0-9]+)"
CRON_PART = re.compile(
rf"(?:\*|{CRON_VALUE}-{CRON_VALUE})(?:/[0-9]+)?|{CRON_VALUE}"
)
def next_website_run(expression, now):
fields = expression.split()
if len(fields) != 5 or not all(
CRON_PART.fullmatch(part)
for field in fields
for part in field.split(",")
):
raise ValueError("Enter five cron fields in UTC.")
minute, hour, day, month, weekday = fields
try:
schedule = crontab(
minute=minute,
hour=hour,
day_of_month=day,
month_of_year=month,
day_of_week=weekday,
)
except (ParseException, ValueError, ZeroDivisionError):
raise ValueError("Enter a valid cron schedule.") from None
times = sorted(
hour * 60 + minute
for hour in schedule.hour
for minute in schedule.minute
)
if not times:
raise ValueError("Enter a valid cron schedule.")
following = times[1:] + [times[0] + MINUTES_PER_DAY]
if any(
end - start < MIN_INTERVAL
for start, end in zip(times, following, strict=True)
):
raise ValueError("Schedule jobs at least five minutes apart.")
now = now.astimezone(UTC)
months = sorted(schedule.month_of_year)
dates = sorted(schedule.day_of_month)
# The Gregorian calendar repeats every 400 years.
for year in range(now.year, min(now.year + 401, 10000)):
for month in months:
if year == now.year and month < now.month:
continue
days_in_month = monthrange(year, month)[1]
for day in dates:
if day > days_in_month:
break
date = datetime(year, month, day, tzinfo=UTC)
if (
date.date() < now.date()
or date.isoweekday() % 7 not in schedule.day_of_week
):
continue
offset = (
bisect_right(times, now.hour * 60 + now.minute)
if date.date() == now.date()
else 0
)
if offset < len(times):
hour, minute = divmod(times[offset], 60)
return date.replace(hour=hour, minute=minute)
raise ValueError("The cron schedule does not match a calendar date.")
+202
View File
@@ -0,0 +1,202 @@
from django import forms
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import ValidationError
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.views import View
from django.views.decorators.cache import never_cache
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.detail import SingleObjectMixin
from coulobre.website_job import MAX_JOB_COMMAND_LENGTH, validate_command
from .access import TenantScopeMixin, is_tenant
from .independent_websites import check_actor
from .models import HostingAccount
from .resource_requests import lock_hosting_account
from .website_job_schedule import next_website_run
from .website_jobs import (
available_job_sites,
save_website_job,
website_job_limit,
)
MANAGE_JOBS = ("hosting.view_hostingaccount", "hosting.manage_website_jobs")
def can_manage_website_jobs(request):
user = request.user
return (
settings.WEBSITE_JOBS
and getattr(request, "impersonation", None) is None
and (is_tenant(user) or user.has_perms(MANAGE_JOBS))
)
class WebsiteJobForm(forms.Form):
site = forms.ChoiceField(label="Website")
name = forms.CharField(max_length=120)
expression = forms.CharField(
label="Cron schedule (UTC)",
max_length=120,
help_text=(
"Use minute, hour, day of month, month, and day of week. "
"For example, */15 * * * *."
),
)
command = forms.CharField(
max_length=MAX_JOB_COMMAND_LENGTH,
help_text=(
"Runs from the document root. "
'Use "$PHP_CLI" to run the site\'s PHP series.'
),
)
enabled = forms.BooleanField(required=False, initial=True)
def __init__(self, *args, sites, job=None, **kwargs):
super().__init__(*args, **kwargs)
if job is None:
self.fields["site"].choices = [
(key, site.domain) for key, site in sites.items()
]
else:
self.fields.pop("site")
self.initial.update(
name=job.name,
expression=job.expression,
command=job.command,
enabled=job.enabled,
)
def clean_expression(self):
expression = " ".join(self.cleaned_data["expression"].split())
try:
next_website_run(expression, timezone.now())
except ValueError as error:
raise forms.ValidationError(str(error)) from None
return expression
def clean_command(self):
command = self.cleaned_data["command"]
try:
validate_command(command)
except ValueError as error:
raise forms.ValidationError(str(error)) from None
return command
@method_decorator(
[never_cache, sensitive_post_parameters("command")], name="dispatch"
)
class WebsiteJobAccountView(
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, View
):
queryset = HostingAccount.objects.filter(
retired_at__isnull=True
).select_related("hosting_plan")
customer_relation = "customer"
permission_required = MANAGE_JOBS
def dispatch(self, request, *args, **kwargs):
if not settings.WEBSITE_JOBS:
raise Http404
return super().dispatch(request, *args, **kwargs)
def has_permission(self):
return can_manage_website_jobs(self.request)
@cached_property
def account(self):
return self.get_object()
class WebsiteJobList(WebsiteJobAccountView):
def get(self, request, *args, **kwargs):
account = self.account
jobs = list(account.website_jobs.all())
limit = website_job_limit(account)
sites = (
{} if account.services_suspended else available_job_sites(account)
)
active = {(site.site_id, site.domain) for site in sites.values()}
enabled_count = 0
rows = []
for job in jobs:
if job.enabled:
enabled_count += 1
available = (
(job.website_id, job.domain) in active
and job.enabled
and enabled_count <= limit
)
rows.append((job, available))
return render(
request,
"hosting/website_jobs.html",
{
"account": account,
"rows": rows,
"limit": limit,
"add_job": len(jobs) < limit and bool(sites),
},
)
class WebsiteJobEditor(WebsiteJobAccountView):
@cached_property
def job(self):
if "job_pk" not in self.kwargs:
return None
return get_object_or_404(
self.account.website_jobs, pk=self.kwargs["job_pk"]
)
def get(self, request, *args, **kwargs):
return self.edit()
def post(self, request, *args, **kwargs):
return self.edit(request.POST)
def edit(self, data=None):
account, job = self.account, self.job
list_url = reverse("panel:website_jobs", args=[account.pk])
if (
job is not None
and data is not None
and data.get("action") == "remove"
):
with transaction.atomic():
locked = lock_hosting_account(account.pk, customer_id=None)
check_actor(locked, self.request.user)
locked.website_jobs.filter(pk=job.pk).delete()
return redirect(list_url)
sites = available_job_sites(account) if job is None else {}
form = WebsiteJobForm(data, sites=sites, job=job)
if form.is_bound and form.is_valid():
try:
save_website_job(
account.pk,
job.pk if job is not None else None,
form.cleaned_data,
self.request.user,
)
except ValidationError as error:
form.add_error(None, error)
else:
return redirect(list_url)
return render(
self.request,
"hosting/website_job_form.html",
{
"account": account,
"job": job,
"form": form,
"list_url": list_url,
},
)
+224
View File
@@ -0,0 +1,224 @@
from datetime import timedelta
from uuid import uuid4
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from coulobre.web_node import WebSite
from coulobre.website_job import JOB_RUNTIME, JOB_SOCKET, WebsiteJobRequest
from .independent_websites import active_websites, check_actor
from .models import HostingAccount, WebsiteScheduledJob
from .node_client import NodeReplyError, apply_on_local_node
from .resource_requests import lock_hosting_account, require_active_services
from .sftp import site_is_active
from .website_job_schedule import next_website_run
JOB_QUEUE = "coulobre-website-jobs"
DISPATCH_INTERVAL = timedelta(seconds=30)
MISSED_WINDOW = timedelta(seconds=90)
RESULT_DEADLINE = timedelta(minutes=3)
Result = WebsiteScheduledJob.Result
def website_job_limit(account):
plan = account.hosting_plan
return plan.website_job_limit if plan is not None else 0
def available_job_sites(account):
sites = {}
if site_is_active(account):
sites["primary"] = WebSite(account.pk, account.primary_domain)
for website in active_websites(account):
if website_accepts_jobs(website):
sites[str(website.pk)] = website.spec
return sites
def website_accepts_jobs(website):
return not website.suspended and (
website.finished_at is not None
or website.operation
not in (website.Operation.SUSPEND, website.Operation.RETIRE)
)
def job_site(job, account):
if job.website_id is None:
if account.primary_domain == job.domain and site_is_active(account):
return WebSite(account.pk, job.domain)
return None
website = (
active_websites(account)
.filter(pk=job.website_id, reservation__domain=job.domain)
.first()
)
return (
website.spec
if website is not None and website_accepts_jobs(website)
else None
)
@transaction.atomic
def save_website_job(account_id, job_id, values, actor):
account = lock_hosting_account(account_id, customer_id=None)
check_actor(account, actor)
if job_id is None:
require_active_services(account)
if account.website_jobs.count() >= website_job_limit(account):
raise ValidationError(
"This hosting account has reached its scheduled job limit."
)
target = available_job_sites(account).get(values["site"])
if target is None:
raise ValidationError("Choose an active website.")
job = WebsiteScheduledJob(
account=account, website_id=target.site_id, domain=target.domain
)
else:
job = account.website_jobs.filter(pk=job_id).first()
if job is None:
raise ValidationError("This scheduled job was removed.")
enabled = values["enabled"]
if enabled:
require_active_services(account)
if website_job_limit(account) == 0 or job_site(job, account) is None:
raise ValidationError(
"Scheduled jobs are unavailable for this website."
)
expression = values["expression"]
reschedule = job.next_run_at is None or expression != job.expression
job.name = values["name"]
job.expression = expression
job.command = values["command"]
job.enabled = enabled
if not enabled or reschedule:
job.next_run_at = (
next_website_run(expression, timezone.now()) if enabled else None
)
job.dispatched_at = None
if job_id is None:
job.save()
else:
job.save(
update_fields=[
"name",
"expression",
"command",
"enabled",
"next_run_at",
"dispatched_at",
]
)
return job
def due_website_jobs(now):
return (
WebsiteScheduledJob.objects.filter(
enabled=True,
next_run_at__lte=now,
account__retired_at__isnull=True,
account__services_suspended=False,
account__hosting_plan__website_job_limit__gt=0,
)
.filter(
Q(dispatched_at__isnull=True)
| Q(dispatched_at__lte=now - DISPATCH_INTERVAL),
)
.order_by("next_run_at", "pk")
)
@transaction.atomic
def claim_website_job(account_id, job_id, expected_run):
try:
account = lock_hosting_account(account_id, customer_id=None)
except HostingAccount.DoesNotExist:
return None
job = account.website_jobs.filter(
pk=job_id, next_run_at=expected_run, enabled=True
).first()
now = timezone.now()
if job is None or expected_run > now:
return None
try:
require_active_services(account)
except ValidationError:
return None
limit = website_job_limit(account)
if limit == 0:
return None
job.next_run_at = next_website_run(job.expression, now)
job.dispatched_at = None
fields = ["next_run_at", "dispatched_at"]
older_jobs = account.website_jobs.filter(enabled=True, pk__lt=job.pk)
site = job_site(job, account)
request = None
if (
site is not None
and now - expected_run <= MISSED_WINDOW
and job.run_token is None
and older_jobs.count() < limit
):
token = uuid4()
request = WebsiteJobRequest(site, token.hex, job.command)
job.run_token = token
job.last_result = Result.RUNNING
job.last_run_at = now
job.finished_at = None
job.last_exit_code = None
fields.extend(
(
"run_token",
"last_result",
"last_run_at",
"finished_at",
"last_exit_code",
)
)
job.save(update_fields=fields)
return request
def recover_interrupted_runs(now):
WebsiteScheduledJob.objects.filter(
run_token__isnull=False,
last_run_at__lt=now - RESULT_DEADLINE,
).update(run_token=None, last_result=Result.UNCONFIRMED, finished_at=now)
def run_website_job(request):
reply = apply_on_local_node(
request,
JOB_SOCKET,
"web node",
"scheduled website job",
identity={"run_id": request.run_id},
timeout=JOB_RUNTIME + 20,
)
timed_out = reply.get("timed_out")
code = reply.get("exit_code")
if timed_out is True and "exit_code" in reply and code is None:
return Result.TIMED_OUT, None
if (
timed_out is not False
or type(code) is not int
or not -255 <= code <= 255
):
raise NodeReplyError("The web node returned an invalid job result.")
return (Result.SUCCEEDED if code == 0 else Result.FAILED), code
def save_website_job_result(job_id, token, result, code):
WebsiteScheduledJob.objects.filter(pk=job_id, run_token=token).update(
finished_at=timezone.now(),
last_result=result,
last_exit_code=code,
run_token=None,
)
+7 -10
View File
@@ -1,5 +1,4 @@
import hashlib
import json
import os
import re
import socket
@@ -10,6 +9,7 @@ from shutil import copyfileobj
from tempfile import TemporaryDirectory
from uuid import UUID
from . import node_stream
from .mail_node import MailboxSpec
BACKUP_RELAY = "/run/coulobre-mail-archive-backup.sock"
@@ -89,19 +89,16 @@ def valid_size(size):
def read_header(source):
body = source.readline(HEADER_LIMIT + 1)
if not body.endswith(b"\n") or len(body) > HEADER_LIMIT:
raise MailArchiveConnectionError("Incomplete mailbox archive header.")
try:
return json.loads(body.decode("utf-8"))
except (ValueError, RecursionError):
raise MailArchiveConnectionError(
"Invalid mailbox archive header."
) from None
return node_stream.read_header(
source, maximum=HEADER_LIMIT, label="mailbox archive"
)
except ValueError as error:
raise MailArchiveConnectionError(str(error)) from None
def encode_header(fields):
return json.dumps(fields, separators=(",", ":")).encode("utf-8") + b"\n"
return node_stream.encode_header(fields)
def receive_archive(source, archive, size, *, digest=None):
+17
View File
@@ -0,0 +1,17 @@
import json
STREAM_CHUNK_SIZE = 1024 * 1024
def encode_header(fields):
return json.dumps(fields, separators=(",", ":")).encode("utf-8") + b"\n"
def read_header(source, *, maximum, label):
body = source.readline(maximum + 1)
if len(body) > maximum or not body.endswith(b"\n"):
raise ValueError(f"Incomplete {label} header.")
try:
return json.loads(body.decode("utf-8"))
except (ValueError, RecursionError):
raise ValueError(f"Invalid {label} header.") from None
+82
View File
@@ -0,0 +1,82 @@
import re
from dataclasses import dataclass
from uuid import UUID
OFFSITE_SOCKET = "/run/coulobre-account-offsite.sock"
TRANSFER_TIMEOUT_SECONDS = 30 * 60
MAX_DESTINATION_LENGTH = 48
DESTINATION_ID = re.compile(r"[a-z][a-z0-9-]{0,47}")
HEX_DIGEST = re.compile(r"[0-9a-f]{64}")
def validate_destination(destination):
if not isinstance(destination, str) or not DESTINATION_ID.fullmatch(
destination
):
raise ValueError("Choose a configured off-site backup destination.")
def destination_labels(value):
if not isinstance(value, dict) or len(value) > 20:
raise ValueError("Configure an object with up to 20 destinations.")
for destination, label in value.items():
validate_destination(destination)
if (
not isinstance(label, str)
or not label.strip()
or not label.isprintable()
or len(label) > 80
):
raise ValueError(
"Each destination needs a label of up to 80 characters."
)
return value
@dataclass(frozen=True)
class OffsiteBackupRequest:
account_id: int
backup_id: UUID
destination: str
def __post_init__(self):
if (
type(self.account_id) is not int
or not 1 <= self.account_id < 2**63
):
raise ValueError("Expected a valid backup account ID.")
if not isinstance(self.backup_id, UUID):
raise ValueError("Expected a backup UUID.")
validate_destination(self.destination)
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys()
!= {"version", "account_id", "backup_id", "destination"}
or type(data["version"]) is not int
or data["version"] != 1
or not isinstance(data["backup_id"], str)
):
raise ValueError("Expected a version 1 off-site backup request.")
backup_id = UUID(data["backup_id"])
if str(backup_id) != data["backup_id"]:
raise ValueError("Expected a canonical backup ID.")
return cls(data["account_id"], backup_id, data["destination"])
def manifest(self):
return {
"version": 1,
"account_id": self.account_id,
"backup_id": str(self.backup_id),
"destination": self.destination,
}
@property
def tag(self):
return f"coulobre-{self.backup_id}"
@property
def archive_name(self):
return f"account-{self.account_id}-{self.backup_id}.zip"
+268
View File
@@ -0,0 +1,268 @@
import hashlib
import json
import os
import re
import subprocess
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from tempfile import NamedTemporaryFile
from zipfile import BadZipFile
from .account_backup import open_account_bundle, private_path
from .account_backup_request import backup_archive, expiration_marker
from .node_files import (
check_root_file,
locked_root_directory,
require_root_directory,
)
from .node_requests import serve_apply_request
from .node_stream import STREAM_CHUNK_SIZE
from .offsite_backup import (
HEX_DIGEST,
TRANSFER_TIMEOUT_SECONDS,
OffsiteBackupRequest,
validate_destination,
)
CONFIG = Path("/etc/coulobre/offsite")
STATE = Path("/var/lib/coulobre/offsite")
REPOSITORY = re.compile(r"sftp:coulobre-offsite:/?[A-Za-z0-9._/-]{1,512}")
SHA_TAG = "coulobre-sha256-"
UNREACHABLE = (
"Could not access the off-site repository. Check its configuration."
)
class OffsiteRepositoryError(ValueError):
pass
@dataclass(frozen=True)
class Repository:
directory: Path
@classmethod
def for_destination(cls, destination):
validate_destination(destination)
if os.geteuid() != 0:
raise ValueError("Run off-site backup commands as root.")
directory = CONFIG / destination
require_root_directory(directory)
for name in (
"repository",
"password",
"ssh_config",
"identity",
"known_hosts",
):
check_root_file(directory / name, mode=0o600)
with (directory / "repository").open(encoding="ascii") as stream:
location = stream.read(1024).strip()
if not REPOSITORY.fullmatch(location) or {"..", "."}.intersection(
location.removeprefix("sftp:coulobre-offsite:").split("/")
):
raise ValueError(
"Use the coulobre-offsite SSH host alias in the repository."
)
return cls(directory)
def arguments(self, *args):
directory = self.directory
ssh = (
f"-F {directory / 'ssh_config'} -i {directory / 'identity'} "
"-o BatchMode=yes -o StrictHostKeyChecking=yes "
"-o IdentitiesOnly=yes "
"-o GlobalKnownHostsFile=/dev/null "
f"-o UserKnownHostsFile={directory / 'known_hosts'}"
)
return [
"/usr/bin/restic",
"--no-cache",
"--repository-file",
str(directory / "repository"),
"--password-file",
str(directory / "password"),
"-o",
f"sftp.args={ssh}",
*args,
]
def run(self, *args, source=None, capture=False, timeout=30):
try:
result = subprocess.run(
self.arguments(*args),
stdin=subprocess.DEVNULL if source is None else source,
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"},
timeout=timeout,
check=True,
)
except (OSError, subprocess.SubprocessError):
raise OffsiteRepositoryError(UNREACHABLE) from None
return result.stdout
def snapshot(self, request):
raw = self.run(
"--json", "snapshots", "--tag", request.tag, capture=True
)
try:
entries = json.loads(raw)
if not isinstance(entries, list):
raise ValueError
if not entries:
return None
if len(entries) != 1:
raise ValueError
entry = entries[0]
identifier = entry["id"]
tags = entry["tags"]
digests = [
tag[len(SHA_TAG) :] for tag in tags if tag.startswith(SHA_TAG)
]
if (
not HEX_DIGEST.fullmatch(identifier)
or request.tag not in tags
or len(digests) != 1
or not HEX_DIGEST.fullmatch(digests[0])
or entry["paths"] != [f"/{request.archive_name}"]
):
raise ValueError
return identifier, digests[0]
except (
AttributeError,
KeyError,
RecursionError,
TypeError,
ValueError,
):
raise OffsiteRepositoryError(
"The off-site repository has conflicting snapshot metadata."
) from None
def read_archive(
self, request, snapshot, *, target=None, expected_size=None
):
digest = hashlib.sha256()
size = 0
with subprocess.Popen(
self.arguments("dump", snapshot, f"/{request.archive_name}"),
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"},
) as process:
try:
while chunk := process.stdout.read(STREAM_CHUNK_SIZE):
size += len(chunk)
if expected_size is not None and size > expected_size:
raise OffsiteRepositoryError(
"The off-site copy has a different size."
)
digest.update(chunk)
if target is not None:
target.write(chunk)
if process.wait() != 0:
raise OffsiteRepositoryError(
"Could not read back the off-site copy."
)
except BaseException:
with suppress(ProcessLookupError):
process.kill()
raise
if expected_size is not None and size != expected_size:
raise OffsiteRepositoryError(
"The off-site copy has a different size."
)
return digest.hexdigest()
def transfer_offsite_backup(request):
repository = Repository.for_destination(request.destination)
archive = backup_archive(request.account_id, request.backup_id)
with locked_root_directory(STATE):
if os.path.lexists(expiration_marker(archive)):
raise OffsiteRepositoryError("The local archive has expired.")
try:
with open_account_bundle(archive) as (_, backup):
if backup.website.account_id != request.account_id:
raise ValueError
except (OSError, BadZipFile, ValueError):
raise OffsiteRepositoryError(
"The local archive could not be validated."
) from None
with archive.open("rb") as source:
size = os.fstat(source.fileno()).st_size
digest = hashlib.file_digest(source, "sha256").hexdigest()
snapshot = repository.snapshot(request)
if snapshot is None:
source.seek(0)
repository.run(
"backup",
"--stdin",
"--stdin-filename",
request.archive_name,
"--tag",
request.tag,
"--tag",
SHA_TAG + digest,
source=source,
timeout=TRANSFER_TIMEOUT_SECONDS - 15,
)
snapshot = repository.snapshot(request)
if snapshot is None or snapshot[1] != digest:
raise OffsiteRepositoryError(
"The off-site snapshot has a different checksum."
)
snapshot_id, _ = snapshot
if (
repository.read_archive(request, snapshot_id, expected_size=size)
!= digest
):
raise OffsiteRepositoryError(
"The off-site copy failed read-back verification."
)
return {"snapshot": snapshot_id, "sha256": digest}
def verify_destination(destination):
Repository.for_destination(destination).run("cat", "config")
def recover_offsite_backup(request, output):
repository = Repository.for_destination(request.destination)
snapshot = repository.snapshot(request)
if snapshot is None:
raise ValueError("No off-site snapshot matches this backup ID.")
output = private_path(output, new=True)
snapshot_id, digest = snapshot
with NamedTemporaryFile(dir=output.parent) as staged:
recovered = repository.read_archive(
request, snapshot_id, target=staged
)
if recovered != digest:
raise ValueError(
"The off-site copy failed read-back verification."
)
staged.flush()
with open_account_bundle(Path(staged.name)) as (_, backup):
if backup.website.account_id != request.account_id:
raise ValueError("The archive belongs to a different account.")
os.fsync(staged.fileno())
os.link(staged.name, output)
return snapshot_id
def serve_offsite_request():
def apply(request):
try:
return transfer_offsite_backup(request)
except OSError:
raise ValueError(
"The backup node could not access the archive or destination."
) from None
return serve_apply_request(
1, OffsiteBackupRequest.from_manifest, apply, include_result=True
)
+8
View File
@@ -14,6 +14,14 @@ SERVICES = {
"panel": ("Coulobre Panel", "coulobre-panel.service"),
"worker": ("Coulobre worker", "coulobre-worker.service"),
"scheduler": ("Coulobre scheduler", "coulobre-beat.service"),
"website-jobs": (
"Coulobre website job worker",
"coulobre-website-job-worker.service",
),
"offsite-backups": (
"Coulobre off-site backup worker",
"coulobre-offsite-worker.service",
),
"apache": ("Apache", "apache2.service"),
"php-fpm": ("PHP-FPM", f"{DEFAULT_PHP_RUNTIME.service}.service"),
"mariadb": ("MariaDB", "mariadb.service"),
+81
View File
@@ -1,3 +1,4 @@
import json
import os
import re
from ipaddress import ip_address
@@ -7,6 +8,7 @@ from urllib.parse import urlsplit
from django.core.exceptions import ImproperlyConfigured
from .domain_names import canonical_domain
from .offsite_backup import destination_labels
from .service_health import load_health_targets
@@ -42,6 +44,16 @@ def ip_addresses_env(name, limit):
SECRET_KEY = required_env("COULOBRE_SECRET_KEY")
HTTPS_PROXY = os.environ.get("COULOBRE_HTTPS_PROXY") == "1"
REQUIRE_PRIVILEGED_MFA = (
os.environ.get(
"COULOBRE_REQUIRE_PRIVILEGED_MFA", "1" if HTTPS_PROXY else "0"
)
== "1"
)
OTP_TOTP_ISSUER = "Coulobre Panel"
TRUST_APACHE_CLIENT_IP = (
os.environ.get("COULOBRE_TRUST_APACHE_CLIENT_IP") == "1"
)
DEBUG = not HTTPS_PROXY and os.environ.get("COULOBRE_DEBUG") == "1"
ALLOWED_HOSTS = os.environ.get(
"COULOBRE_ALLOWED_HOSTS", "localhost,127.0.0.1,[::1]"
@@ -61,6 +73,9 @@ INSTALLED_APPS = [
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django_otp",
"django_otp.plugins.otp_totp",
"django_otp.plugins.otp_email",
"coulobre.hosting",
]
@@ -70,6 +85,8 @@ MIDDLEWARE = [
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django_otp.middleware.OTPMiddleware",
"coulobre.hosting.sign_in.PrivilegedFactorMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"coulobre.hosting.impersonation.CustomerImpersonationMiddleware",
@@ -141,6 +158,42 @@ LOGIN_URL = "panel:login"
LOGIN_REDIRECT_URL = "panel:accounts"
LOGOUT_REDIRECT_URL = "panel:login"
PASSWORD_RESET_TIMEOUT = 1800
PASSWORD_RESET_ORIGIN = os.environ.get("COULOBRE_PASSWORD_RESET_ORIGIN", "")
if PASSWORD_RESET_ORIGIN:
try:
reset_origin = urlsplit(PASSWORD_RESET_ORIGIN)
if (
reset_origin.scheme != "https"
or not reset_origin.hostname
or reset_origin.username is not None
or reset_origin.path not in ("", "/")
or reset_origin.query
or reset_origin.fragment
or reset_origin.port == 0
or any(char.isspace() for char in PASSWORD_RESET_ORIGIN)
):
raise ValueError
except ValueError:
raise ImproperlyConfigured(
"Set COULOBRE_PASSWORD_RESET_ORIGIN to the HTTPS panel origin."
) from None
EMAIL_HOST = os.environ.get("COULOBRE_SMTP_HOST", "")
EMAIL_PORT = int(os.environ.get("COULOBRE_SMTP_PORT", "587"))
EMAIL_HOST_USER = os.environ.get("COULOBRE_SMTP_USER", "")
EMAIL_HOST_PASSWORD = os.environ.get("COULOBRE_SMTP_PASSWORD", "")
EMAIL_USE_TLS = os.environ.get("COULOBRE_SMTP_STARTTLS", "1") == "1"
EMAIL_TIMEOUT = 10
DEFAULT_FROM_EMAIL = os.environ.get(
"COULOBRE_EMAIL_FROM", "Coulobre Panel <panel@localhost>"
)
OTP_EMAIL_SUBJECT = "Your Coulobre Panel verification code"
OTP_EMAIL_BODY_TEMPLATE = (
"Your Coulobre Panel verification code is {{ token }}. "
"It expires in five minutes."
)
CELERY_BROKER_URL = os.environ.get(
"COULOBRE_BROKER_URL", "amqp://guest:guest@127.0.0.1:5672//"
)
@@ -156,6 +209,8 @@ except ValueError as error:
LOCAL_WEB_ACTIVATION = os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") == "1"
LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1"
WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1"
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
LOCAL_DATABASE_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
@@ -249,6 +304,16 @@ if ROUNDCUBE_URL:
)
LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1"
try:
OFFSITE_BACKUP_DESTINATIONS = destination_labels(
json.loads(
os.environ.get("COULOBRE_OFFSITE_BACKUP_DESTINATIONS", "{}")
)
)
except (ValueError, RecursionError) as error:
raise ImproperlyConfigured(
f"COULOBRE_OFFSITE_BACKUP_DESTINATIONS: {error}"
) from None
LOCAL_ACCOUNT_BACKUP_MAIL = (
os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL") == "1"
)
@@ -282,6 +347,10 @@ if (LOCAL_ACCOUNT_BACKUP_MAIL and REMOTE_ACCOUNT_BACKUP_MAIL) or (
"Choose one mailbox transport for backup and one for restore."
)
CELERY_BEAT_SCHEDULE = {
"expire-panel-sign-in-windows": {
"task": "coulobre.hosting.tasks.expire_sign_in_windows",
"schedule": 600.0,
},
"dispatch-account-retirements": {
"task": "coulobre.hosting.tasks.dispatch_account_retirements",
"schedule": 5.0,
@@ -320,6 +389,12 @@ if LOCAL_WEB_HTTPS:
"schedule": 5.0,
"options": {"expires": 4.0},
}
if WEBSITE_JOBS:
CELERY_BEAT_SCHEDULE["dispatch-website-jobs"] = {
"task": "coulobre.hosting.tasks.dispatch_website_jobs",
"schedule": 15.0,
"options": {"expires": 14.0},
}
if LOCAL_WEB_SFTP:
CELERY_BEAT_SCHEDULE["dispatch-web-sftp"] = {
"task": "coulobre.hosting.tasks.dispatch_web_sftp",
@@ -357,3 +432,9 @@ if LOCAL_BACKUP_RETENTION:
"schedule": 300.0,
"options": {"expires": 295.0},
}
if LOCAL_ACCOUNT_BACKUPS and OFFSITE_BACKUP_DESTINATIONS:
CELERY_BEAT_SCHEDULE["dispatch-offsite-backups"] = {
"task": "coulobre.hosting.tasks.dispatch_offsite_backups",
"schedule": 15.0,
"options": {"expires": 14.0},
}
+57 -17
View File
@@ -16,6 +16,7 @@ from .php_runtime import validate_php_version, validate_php_versions
from .service_access import ServiceAccessRequest, parse_service_request
MANIFEST_VERSION = 1
INDEPENDENT_SITE_VERSION = 2
MAX_STORAGE_BYTES = 2**63 - 1
MAX_STORAGE_LIMIT_MIB = 2**31 - 1
CONFIGURATIONS = {
@@ -28,6 +29,7 @@ CONFIGURATIONS = {
class WebSite:
account_id: int
domain: str
site_id: int | None = None
def __post_init__(self):
if (
@@ -37,40 +39,62 @@ class WebSite:
raise ValueError(
"The account ID must be a positive 64-bit integer."
)
if self.site_id is not None and (
type(self.site_id) is not int or not 1 <= self.site_id <= 2**63 - 1
):
raise ValueError("The site ID must be a positive 64-bit integer.")
if not isinstance(self.domain, str):
raise ValueError("The domain must be a string.")
object.__setattr__(self, "domain", canonical_domain(self.domain))
@property
def node_key(self):
return (
str(self.account_id)
if self.site_id is None
else f"s{self.site_id}"
)
@property
def service_user(self):
return f"coulobre-{self.node_key}"
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != {
"version",
"account_id",
"domain",
}:
raise ValueError(
"Expected a manifest with version, account_id, and domain."
)
version = data["version"]
if type(version) is not int or version != MANIFEST_VERSION:
if not isinstance(data, dict):
raise ValueError("Expected a website manifest.")
version = data.get("version")
if type(version) is not int or version not in (
MANIFEST_VERSION,
INDEPENDENT_SITE_VERSION,
):
raise ValueError("Unsupported web deployment manifest version.")
return cls(data["account_id"], data["domain"])
fields = {"version", "account_id", "domain"}
if version == INDEPENDENT_SITE_VERSION:
fields.add("site_id")
if data.keys() != fields or (
version == INDEPENDENT_SITE_VERSION and data["site_id"] is None
):
raise ValueError("Expected a website manifest.")
return cls(data["account_id"], data["domain"], data.get("site_id"))
def manifest(self):
return {
data = {
"version": MANIFEST_VERSION,
"account_id": self.account_id,
"domain": self.domain,
}
if self.site_id is not None:
data.update(version=INDEPENDENT_SITE_VERSION, site_id=self.site_id)
return data
def configuration(self):
service_user = f"coulobre-{self.account_id}"
return {
"account_id": self.account_id,
"domain": self.domain,
"service_user": service_user,
"document_root": f"/srv/coulobre/web/{self.account_id}/public",
"socket_path": f"/run/php/{service_user}.sock",
"service_user": self.service_user,
"document_root": f"/srv/coulobre/web/{self.node_key}/public",
"socket_path": f"/run/php/{self.service_user}.sock",
}
def render(
@@ -119,7 +143,7 @@ class WebAlias:
@property
def name(self):
suffix = sha256(self.domain.encode("ascii")).hexdigest()[:24]
return f"coulobre-{self.site.account_id}-alias-{suffix}"
return f"{self.site.service_user}-alias-{suffix}"
@classmethod
def from_manifest(cls, data):
@@ -470,10 +494,26 @@ def main(argv=None):
restore_site.add_argument("archive", type=Path)
restore_site.add_argument("--file", help="Restore one document-root path.")
restore_site.add_argument("--replace", action="store_true")
commands.add_parser(
"files-request", help="Handle a scoped website file operation."
)
commands.add_parser(
"job-request", help="Run a scheduled job as the website user."
)
args = parser.parse_args(argv)
if args.command == "restore-site" and args.replace and args.file is None:
parser.error("--replace requires --file.")
if args.command == "files-request":
from .web_node_files import serve_website_files
return serve_website_files()
if args.command == "job-request":
from .web_node_jobs import serve_website_job
return serve_website_job()
if args.command == "apply-request":
return serve_apply_request(
MANIFEST_VERSION,
+17 -2
View File
@@ -9,6 +9,14 @@ APACHE_CONFIG = Path("/etc/apache2/conf-enabled")
SSH_CONFIG = Path("/etc/ssh/sshd_config.d")
def website_suspension_path(site):
return APACHE_CONFIG / f"coulobre-suspended-{site.node_key}.conf"
def sftp_suspension_path(site):
return SSH_CONFIG / f"01-coulobre-suspended-{site.node_key}.conf"
def set_website_access(site, suspended):
document_root = site.configuration()["document_root"]
# The shared ACME webroot is outside the hosted document root.
@@ -17,17 +25,24 @@ def set_website_access(site, suspended):
" Require all denied\n"
"</DirectoryMatch>\n"
)
path = APACHE_CONFIG / f"coulobre-suspended-{site.account_id}.conf"
path = website_suspension_path(site)
def validate():
web.run("/usr/sbin/apache2ctl", "configtest")
set_configuration(site, suspended, path, config, validate, "apache2")
if site.site_id is not None:
from .web_node_sftp import AUTHORIZED_KEYS
if os.path.lexists(
AUTHORIZED_KEYS / site.service_user
) or os.path.lexists(sftp_suspension_path(site)):
set_sftp_access(site, suspended)
def set_sftp_access(site, suspended):
user = site.configuration()["service_user"]
path = SSH_CONFIG / f"01-coulobre-suspended-{site.account_id}.conf"
path = sftp_suspension_path(site)
def validate():
configuration = web.run(
+13 -8
View File
@@ -54,7 +54,7 @@ class SitePaths:
def for_site(cls, site, *, version=None, archived_account=None):
configuration = site.configuration()
name = configuration["service_user"]
account = WEB_ROOT / str(site.account_id)
account = WEB_ROOT / site.node_key
socket = Path(configuration["socket_path"])
runtime = DEFAULT_PHP_RUNTIME
route = (archived_account or account) / ".coulobre-php.sock"
@@ -132,7 +132,7 @@ def install_site(site, *, php_settings=None, allowed=()):
create_route = not (
paths.routed
or (
os.path.lexists(STATE_DIRECTORY / f"{site.account_id}.json")
os.path.lexists(STATE_DIRECTORY / f"{site.node_key}.json")
and (os.path.lexists(paths.apache) or os.path.lexists(paths.pool))
)
)
@@ -171,7 +171,7 @@ def site_status(site):
require_root_directory(STATE_DIRECTORY)
except FileNotFoundError:
return report
marker = STATE_DIRECTORY / f"{site.account_id}.json"
marker = STATE_DIRECTORY / f"{site.node_key}.json"
if not os.path.lexists(marker):
return report
@@ -195,7 +195,7 @@ def site_status(site):
def check_reservation(site):
marker = STATE_DIRECTORY / f"{site.account_id}.json"
marker = STATE_DIRECTORY / f"{site.node_key}.json"
try:
saved = json.loads(read_root_file(marker))
except FileNotFoundError:
@@ -208,7 +208,7 @@ def check_reservation(site):
def site_storage(site):
check_reservation(site)
account = WEB_ROOT / str(site.account_id)
account = WEB_ROOT / site.node_key
require_root_directory(account)
user = site.configuration()["service_user"]
uid, gid = check_system_account(user, account)
@@ -254,7 +254,7 @@ def check_services(runtime):
def reserve_account(site, user, paths):
marker = STATE_DIRECTORY / f"{site.account_id}.json"
marker = STATE_DIRECTORY / f"{site.node_key}.json"
if os.path.lexists(marker.with_suffix(".retired")):
raise ValueError("This website belongs to a retired hosting account.")
manifest = site.manifest()
@@ -263,7 +263,7 @@ def reserve_account(site, user, paths):
if existing == marker:
if saved != manifest:
raise ValueError(
"The account is already reserved with a different "
"The website is already reserved with a different "
"manifest."
)
elif saved["domain"] == site.domain:
@@ -271,7 +271,10 @@ def reserve_account(site, user, paths):
"The primary domain is already reserved by another account."
)
from .web_node_aliases import check_alias_domain_available
from .web_node_aliases import (
check_alias_domain_available,
check_apache_hostname_available,
)
check_alias_domain_available(site.domain)
@@ -285,6 +288,8 @@ def reserve_account(site, user, paths):
raise ValueError(
"The web node already has unmanaged resources for this account."
)
if site.site_id is not None:
check_apache_hostname_available(site.domain)
write_new_file(marker, json.dumps(manifest) + "\n", mode=0o600)
+326
View File
@@ -0,0 +1,326 @@
import ctypes
import errno
import fcntl
import heapq
import os
import signal
import stat
import sys
from contextlib import contextmanager, suppress
from uuid import uuid4
from . import web_node_apply as web
from .node_stream import STREAM_CHUNK_SIZE, encode_header, read_header
from .web_node_access import website_suspension_path
from .website_files import (
LIST_PAGE_SIZE,
REQUEST_HEADER_LIMIT,
TEMPORARY_PREFIX,
WebsiteFileRequest,
directory_parts,
validate_entry_name,
)
OPEN_DIRECTORY = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
RENAME_NOREPLACE = 1
PROBLEMS = {
errno.EDQUOT: "The website storage quota has been reached.",
errno.ENOSPC: "The web node has no space for this upload.",
errno.EEXIST: "A file or folder with that name already exists.",
errno.ENOENT: "The selected file or folder is no longer available.",
errno.ENOTEMPTY: "Empty the folder before removing it.",
errno.ELOOP: "The path must point to a regular website file or folder.",
errno.ENOTDIR: "The selected folder is unavailable.",
errno.EACCES: "The website user cannot access this entry.",
errno.EPERM: "The website user cannot change this entry.",
}
# Resolve libc before entering the website filesystem.
renameat2 = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None)
if renameat2 is not None:
renameat2.argtypes = (
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_uint,
)
renameat2.restype = ctypes.c_int
@contextmanager
def website_user(site):
if os.geteuid() != 0:
raise ValueError("Run the website files receiver as root.")
with web.locked_web_node(fcntl.LOCK_SH):
if os.path.lexists(website_suspension_path(site)):
raise ValueError("This website is suspended.")
try:
public, uid, web_gid = web.site_storage(site)
account = web.current_user(site.service_user)
if account is None or account.pw_uid != uid:
raise ValueError
except (OSError, ValueError):
raise ValueError(
"This website is unavailable on the web node."
) from None
file_descriptor = os.open(public, OPEN_DIRECTORY)
try:
root = os.fstat(file_descriptor)
if uid == 0 or (root.st_uid, root.st_gid) != (uid, web_gid):
raise ValueError(
"This website is unavailable on the web node."
)
os.fchdir(file_descriptor)
os.chroot(".")
os.chdir("/")
os.setgroups([web_gid])
os.setresgid(account.pw_gid, account.pw_gid, account.pw_gid)
os.setresuid(uid, uid, uid)
finally:
os.close(file_descriptor)
yield uid, web_gid, root.st_dev
def permitted(info, uid, device):
return (
info.st_uid == uid
and info.st_dev == device
and (
stat.S_ISDIR(info.st_mode)
or (stat.S_ISREG(info.st_mode) and info.st_nlink == 1)
)
)
@contextmanager
def open_folder(path, uid, device):
folder = os.open("/", OPEN_DIRECTORY)
try:
for part in directory_parts(path):
child = os.open(part, OPEN_DIRECTORY, dir_fd=folder)
os.close(folder)
folder = child
if not permitted(os.fstat(folder), uid, device):
raise ValueError("The selected folder is unavailable.")
yield folder
finally:
os.close(folder)
def entry_info(folder, name, uid, device):
info = os.stat(name, dir_fd=folder, follow_symlinks=False)
if not permitted(info, uid, device):
raise ValueError("The selected website entry is unavailable.")
return info
def list_folder(folder, after, uid, device):
def candidates(entries):
for entry in entries:
if entry.name <= after:
continue
try:
validate_entry_name(entry.name)
info = entry.stat(follow_symlinks=False)
except (FileNotFoundError, ValueError):
continue
if permitted(info, uid, device):
yield entry.name, stat.S_ISDIR(info.st_mode), info.st_size
with os.scandir(folder) as entries:
items = heapq.nsmallest(LIST_PAGE_SIZE + 1, candidates(entries))
page = [
{
"name": name,
"is_directory": directory,
"size": 0 if directory else size,
}
for name, directory, size in items[:LIST_PAGE_SIZE]
]
after = page[-1]["name"] if len(items) > LIST_PAGE_SIZE else ""
return {"entries": page, "after": after}
def rename_entry(folder, source, target):
if renameat2 is None:
raise ValueError(
"This web node cannot rename files without replacing them."
)
result = renameat2(
folder,
os.fsencode(source),
folder,
os.fsencode(target),
RENAME_NOREPLACE,
)
if result:
error = ctypes.get_errno()
raise OSError(error, os.strerror(error))
def upload_file(folder, name, size, source, web_gid):
staged = TEMPORARY_PREFIX + uuid4().hex
descriptor = os.open(
staged,
os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
0o600,
dir_fd=folder,
)
try:
with os.fdopen(descriptor, "wb") as output:
remaining = size
while remaining:
chunk = source.read(min(STREAM_CHUNK_SIZE, remaining))
if not chunk:
raise ValueError(
"The upload ended before the file was complete."
)
output.write(chunk)
remaining -= len(chunk)
if source.read(1):
raise ValueError("The upload exceeded its declared file size.")
output.flush()
os.fchown(output.fileno(), -1, web_gid)
os.fchmod(output.fileno(), 0o640)
os.fsync(output.fileno())
rename_entry(folder, staged, name)
os.fsync(folder)
finally:
with suppress(FileNotFoundError):
os.unlink(staged, dir_fd=folder)
def open_download(folder, name, uid, device):
if not stat.S_ISREG(entry_info(folder, name, uid, device).st_mode):
raise ValueError("Choose a file to download.")
descriptor = os.open(
name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder
)
source = os.fdopen(descriptor, "rb")
info = os.fstat(source.fileno())
if not stat.S_ISREG(info.st_mode) or not permitted(info, uid, device):
source.close()
raise ValueError(
"The file changed before download. Refresh the folder."
)
return source, info.st_size
def create_directory(folder, name, web_gid):
staged = TEMPORARY_PREFIX + uuid4().hex
os.mkdir(staged, 0o700, dir_fd=folder)
try:
descriptor = os.open(staged, OPEN_DIRECTORY, dir_fd=folder)
try:
os.fchown(descriptor, -1, web_gid)
os.fchmod(descriptor, 0o750)
finally:
os.close(descriptor)
rename_entry(folder, staged, name)
finally:
with suppress(FileNotFoundError):
os.rmdir(staged, dir_fd=folder)
def change_entry(request, folder, uid, web_gid, device):
if request.operation == "mkdir":
create_directory(folder, request.name, web_gid)
else:
info = entry_info(folder, request.name, uid, device)
if request.operation == "rename":
rename_entry(folder, request.name, request.target)
elif stat.S_ISDIR(info.st_mode):
os.rmdir(request.name, dir_fd=folder)
else:
os.unlink(request.name, dir_fd=folder)
os.fsync(folder)
def reply(output, identity, state, **data):
output.write(
encode_header(
{
"version": 1,
"identity": identity,
"state": state,
**data,
}
)
)
output.flush()
def cancel_upload(signum, frame):
raise InterruptedError("The file request expired.")
def discard_upload(source, size):
while size:
chunk = source.read1(min(STREAM_CHUNK_SIZE, size))
if not chunk:
return
size -= len(chunk)
def serve_website_files():
source, output = sys.stdin.buffer, sys.stdout.buffer
request = None
identity = ""
started_download = False
signal.signal(signal.SIGTERM, cancel_upload)
try:
request = WebsiteFileRequest.from_manifest(
read_header(
source,
maximum=REQUEST_HEADER_LIMIT,
label="website file request",
)
)
identity = request.identity()
with (
website_user(request.site) as (uid, web_gid, device),
open_folder(request.directory, uid, device) as folder,
):
if request.operation == "download":
file, remaining = open_download(
folder, request.name, uid, device
)
with file:
reply(output, identity, "ready", size=remaining)
started_download = True
while remaining:
chunk = file.read(min(STREAM_CHUNK_SIZE, remaining))
if not chunk:
return 1
output.write(chunk)
remaining -= len(chunk)
output.flush()
return 0
if request.operation == "list":
result = list_folder(folder, request.after, uid, device)
else:
if request.operation == "upload":
upload_file(
folder, request.name, request.size, source, web_gid
)
else:
change_entry(request, folder, uid, web_gid, device)
result = {}
reply(output, identity, "ready", **result)
return 0
except (OSError, ValueError) as error:
if not started_download:
problem = (
str(error)
if isinstance(error, ValueError)
else PROBLEMS.get(
error.errno,
"The web node could not complete this file operation.",
)
)
with suppress(OSError):
reply(output, identity, "failed", problem=problem)
if request is not None and request.operation == "upload":
discard_upload(source, request.size)
return 1
+61
View File
@@ -0,0 +1,61 @@
import fcntl
import os
import subprocess
from . import web_node_apply as web
from .node_requests import serve_apply_request
from .web_node_access import website_suspension_path
from .website_job import JOB_MANIFEST_VERSION, JOB_RUNTIME, WebsiteJobRequest
MAX_REQUEST_BYTES = 16 * 1024
def execute_website_job(request):
if os.geteuid() != 0:
raise ValueError("Run the website job receiver as root.")
site = request.site
with web.locked_web_node(fcntl.LOCK_SH):
if os.path.lexists(website_suspension_path(site)):
raise ValueError("The website is suspended.")
public, uid, _ = web.site_storage(site)
account = web.current_user(site.service_user)
if account is None or account.pw_uid != uid or uid == 0:
raise ValueError("The website user is unavailable.")
runtime = web.SitePaths.for_site(site).runtime
try:
process = subprocess.run(
["/bin/sh", "-s"],
input=(request.command + "\n").encode("utf-8"),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
cwd=public,
env={
"PATH": "/usr/local/bin:/usr/bin:/bin",
"HOME": str(public),
"USER": site.service_user,
"LOGNAME": site.service_user,
"LANG": "C.UTF-8",
"TZ": "UTC",
"PHP_CLI": f"/usr/bin/php{runtime.version}",
},
user=uid,
group=account.pw_gid,
extra_groups=[],
umask=0o027,
timeout=JOB_RUNTIME,
check=False,
)
except subprocess.TimeoutExpired:
return {"timed_out": True, "exit_code": None}
return {"timed_out": False, "exit_code": process.returncode}
def serve_website_job():
return serve_apply_request(
JOB_MANIFEST_VERSION,
WebsiteJobRequest.from_manifest,
execute_website_job,
limit=MAX_REQUEST_BYTES,
identity=lambda request: {"run_id": request.run_id},
include_result=True,
)
+49 -11
View File
@@ -30,14 +30,21 @@ def retire_site(request):
retirement = RetirementRecord(web.STATE_DIRECTORY, request)
if retirement.is_complete:
return
reservation = web.STATE_DIRECTORY / f"{site.account_id}.json"
reservation = web.STATE_DIRECTORY / f"{site.node_key}.json"
started = retirement.matches(retirement.started)
if (
site.site_id is not None
and not os.path.lexists(reservation)
and not (retirement.directory / "site").is_file()
):
retire_unprovisioned_site(site, reservation, retirement)
return
if os.path.lexists(reservation) or not started:
web.check_reservation(site)
elif not (retirement.directory / "site").is_file():
raise ValueError("The original website reservation is missing.")
archived_account = web.WEB_ROOT / ".retired" / request.operation_id
account = web.WEB_ROOT / str(site.account_id)
account = web.WEB_ROOT / site.node_key
paths = web.SitePaths.for_site(
site,
archived_account=archived_account
@@ -67,13 +74,45 @@ def retire_site(request):
apache = managed_vhosts(site, paths)
retirement.begin()
detach_site(site, paths, key_file, apache, retirement)
marker = reservation.with_suffix(".retired")
if not os.path.lexists(marker):
write_new_file(marker, retirement.document, mode=0o600)
elif read_root_file(marker, mode=0o600) != retirement.document:
raise ValueError("The website has a different retirement record.")
archive_path(reservation, retirement.directory / "site")
retirement.finish()
finish_site_retirement(reservation, retirement)
def retire_unprovisioned_site(site, reservation, retirement):
paths = web.SitePaths.for_site(site)
https, enabled = https_paths(paths)
if (
web.current_user(site.service_user)
or web.current_group(site.service_user)
or any(
os.path.lexists(path)
for path in (
paths.account,
paths.apache,
paths.enabled,
paths.pool,
paths.socket,
https,
enabled,
AUTHORIZED_KEYS / site.service_user,
)
)
):
raise ValueError(
"The web node has unmanaged resources for this website."
)
check_aliases(site)
retirement.begin()
finish_site_retirement(reservation, retirement)
def finish_site_retirement(reservation, retirement):
marker = reservation.with_suffix(".retired")
if not os.path.lexists(marker):
write_new_file(marker, retirement.document, mode=0o600)
elif read_root_file(marker, mode=0o600) != retirement.document:
raise ValueError("The website has a different retirement record.")
archive_path(reservation, retirement.directory / "site")
retirement.finish()
def check_aliases(site):
@@ -82,8 +121,7 @@ def check_aliases(site):
return
require_root_directory(directory)
if any(
read_alias(marker).site.account_id == site.account_id
for marker in directory.glob("*.json")
read_alias(marker).site == site for marker in directory.glob("*.json")
):
raise ValueError(
"Remove the managed website aliases before retiring the site."
+1 -1
View File
@@ -32,7 +32,7 @@ def switch_php_version(site, version):
raise ValueError(
f"Install stable PHP {version} FPM on the web node."
)
if current.socket.name == f"coulobre-{site.account_id}.sock" and (
if current.socket.name == f"{site.service_user}.sock" and (
current.routed or current.runtime.version != version
):
current = route_legacy_site(site, current)
+7
View File
@@ -37,6 +37,13 @@ def apply_sftp_keys(request):
target = AUTHORIZED_KEYS / user
with locked_web_node(fcntl.LOCK_EX):
if site.site_id is not None:
from .web_node_access import website_suspension_path
if os.path.lexists(website_suspension_path(site)):
raise ValueError(
"Resume the website before changing SFTP keys."
)
check_reservation(site)
if os.path.lexists(target):
check_root_file(target, mode=0o644)
+1 -5
View File
@@ -158,11 +158,7 @@ def https_paths(paths):
def certbot_lineage(site):
name = (
site.name
if isinstance(site, WebAlias)
else f"coulobre-{site.account_id}"
)
name = site.name if isinstance(site, WebAlias) else site.service_user
return CERTBOT_ROOT / "live" / name
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more