Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d691e20b16 | ||
|
|
1bd09f8cd7 | ||
|
|
0de4d0c854 | ||
|
|
23e6e01303 | ||
|
|
f8643bf60d | ||
|
|
f5e8e84e3c | ||
|
|
2f686b6499 | ||
|
|
22205f4e4b | ||
|
|
3d1c666f5e | ||
|
|
1bb081f202 | ||
|
|
d34654c956 | ||
|
|
f4a889660f | ||
|
|
187c80ff6d | ||
|
|
0f12e7c456 | ||
|
|
a8985c3041 | ||
|
|
cf9ce8e5b6 | ||
|
|
b92edc02f5 | ||
|
|
f50bfbc60d | ||
|
|
3e15cb010b | ||
|
|
b7a156b45e | ||
|
|
7c69c65d36 |
No files matched your search
@@ -47,6 +47,16 @@
|
||||
instructions, and known limitations. Mark a release candidate as a
|
||||
prerelease. Close the milestone when its target version is published.
|
||||
|
||||
For a release tested through the web updater, generate and attach
|
||||
`web-update.json` alongside the matching wheel. List each tested starting
|
||||
package version after the wheel path. Only list versions that can upgrade
|
||||
with the dependencies and service units they already have.
|
||||
|
||||
```sh
|
||||
python tools/web_update_manifest.py dist/coulobre_panel-0.10.2rc1-py3-none-any.whl \
|
||||
0.10.1rc1 > dist/web-update.json
|
||||
```
|
||||
|
||||
## Pull requests
|
||||
|
||||
- Start changes on a dedicated branch from the default branch, named main.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Coulobre Panel
|
||||
|
||||
<img src="src/coulobre/hosting/static/hosting/coulobre-mark.svg" alt="" width="72">
|
||||
|
||||
Coulobre Panel is an open-source web hosting control panel for hosting providers
|
||||
and resellers. The project is in early development.
|
||||
|
||||
@@ -18,6 +20,8 @@ work items in [Gitea issues][issues]. Published versions and their release
|
||||
notes are available on [Gitea Releases][releases].
|
||||
|
||||
See [Contributing](CONTRIBUTING.md) for the project workflow.
|
||||
See [Security](docs/security.md) for deployment hardening and private
|
||||
vulnerability reporting.
|
||||
|
||||
[milestones]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/milestones
|
||||
[issues]: https://code.hosting.hippogrief.nl/hippogrief/coulobre/issues
|
||||
|
||||
@@ -61,6 +61,7 @@ if [ ! -x "$venv/bin/python" ]; then
|
||||
python3 -m venv "$venv"
|
||||
fi
|
||||
if [ -z "$installed" ]; then
|
||||
"$venv/bin/pip" install .
|
||||
"$venv/bin/python" -m pip install --only-binary=:all: 'pip>=26.2'
|
||||
"$venv/bin/python" -m pip install .
|
||||
fi
|
||||
exec "$venv/bin/coulobre-node-setup" install-receiver "$@"
|
||||
@@ -1,4 +1,4 @@
|
||||
Match User coulobre-dns-request,coulobre-mail-request
|
||||
Match User coulobre-dns-request,coulobre-mail-request,coulobre-dns-p-*,coulobre-mail-p-*
|
||||
AuthenticationMethods publickey
|
||||
PubkeyAuthentication yes
|
||||
PasswordAuthentication no
|
||||
@@ -11,10 +11,10 @@ Match User coulobre-dns-request,coulobre-mail-request
|
||||
PermitTTY no
|
||||
PermitUserRC no
|
||||
|
||||
Match User coulobre-dns-request
|
||||
Match User coulobre-dns-request,coulobre-dns-p-*
|
||||
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-dns-apply.sock
|
||||
|
||||
Match User coulobre-mail-request
|
||||
Match User coulobre-mail-request,coulobre-mail-p-*
|
||||
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-mail-apply.sock
|
||||
|
||||
Match all
|
||||
@@ -282,6 +282,18 @@ def install_release(release, *, step=nullcontext):
|
||||
if key in os.environ
|
||||
}
|
||||
with step("Installing Coulobre and its Python dependencies"):
|
||||
run(
|
||||
BINDIR / "python",
|
||||
"-m",
|
||||
"pip",
|
||||
"install",
|
||||
"--disable-pip-version-check",
|
||||
"--only-binary=:all:",
|
||||
"pip>=26.2",
|
||||
label="Update the virtual environment installer",
|
||||
env=pip_env,
|
||||
timeout=1200,
|
||||
)
|
||||
run(
|
||||
BINDIR / "pip",
|
||||
"install",
|
||||
@@ -579,8 +591,12 @@ class Installer:
|
||||
f"amqp://coulobre:{self.state['broker_password']}@127.0.0.1:5672/coulobre"
|
||||
),
|
||||
"COULOBRE_LOCAL_DATABASE_PROVISIONING": "1",
|
||||
"COULOBRE_SERVICE_HEALTH": json.dumps(
|
||||
{"panel": {"local": services}}, separators=(",", ":")
|
||||
"COULOBRE_SERVICE_HEALTH": (
|
||||
"'"
|
||||
+ json.dumps(
|
||||
{"panel": {"local": services}}, separators=(",", ":")
|
||||
)
|
||||
+ "'"
|
||||
),
|
||||
}
|
||||
if self.php:
|
||||
@@ -598,6 +614,8 @@ class Installer:
|
||||
COULOBRE_SMTP_PORT="25",
|
||||
COULOBRE_SMTP_STARTTLS="0",
|
||||
COULOBRE_EMAIL_FROM=f"panel@{self.plan.mail.host}",
|
||||
COULOBRE_MAIL_IMAP_HOST=self.plan.mail.host,
|
||||
COULOBRE_MAIL_SUBMISSION_HOST=self.plan.mail.host,
|
||||
)
|
||||
hosting = self.plan.hosting
|
||||
if hosting.public_addresses:
|
||||
@@ -854,6 +872,9 @@ class Installer:
|
||||
HEALTH_TIMER,
|
||||
):
|
||||
install_unit(unit)
|
||||
install_unit("coulobre-update.socket")
|
||||
install_unit("coulobre-update@.service")
|
||||
workers.append("coulobre-update.socket")
|
||||
systemctl("daemon-reload")
|
||||
systemctl(
|
||||
"enable", "--now", *PANEL_UNITS, *workers, "apache2.service"
|
||||
|
||||
@@ -11,10 +11,11 @@ from urllib.parse import parse_qs
|
||||
|
||||
from .cli import comma_separated, number
|
||||
from .config import REMOTE_MODES, InstallError, parse_plan, port
|
||||
from .engine import Installer
|
||||
from .engine import SOURCE, Installer
|
||||
|
||||
COOKIE = "coulobre_installer"
|
||||
MAX_FORM = 16384
|
||||
BRAND_MARK = SOURCE / "src/coulobre/hosting/static/hosting/coulobre-mark.svg"
|
||||
FORM = """<form method="post" action="/review">
|
||||
<p>Full-service setup is recommended for a public single server. The panel,
|
||||
websites, databases, DNS and mail run locally. Adjust the settings below
|
||||
@@ -44,7 +45,10 @@ for a different deployment.</p>
|
||||
<input name="mail_sending_addresses"></label>
|
||||
</fieldset>
|
||||
<button type="submit">Review installation</button></form>"""
|
||||
STYLE = """body{font:1rem system-ui,sans-serif;max-width:46rem;margin:auto;
|
||||
STYLE = """:root{color-scheme:light}
|
||||
h1{display:flex;align-items:center;gap:.65rem}
|
||||
h1 img{width:1.9rem;height:1.9rem;flex:none}
|
||||
body{font:1rem system-ui,sans-serif;max-width:46rem;margin:auto;
|
||||
padding:1rem;color:#14372e} fieldset{margin:1rem 0;border:1px solid #a9beb2;
|
||||
border-radius:.4rem;padding:1rem} label{display:block;margin-bottom:.75rem}
|
||||
input,select{display:block;box-sizing:border-box;width:100%;padding:.45rem;
|
||||
@@ -223,8 +227,10 @@ class WizardHandler(BaseHTTPRequestHandler):
|
||||
head = '<meta http-equiv="refresh" content="2">' if refresh else ""
|
||||
html = f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
{head}<title>Install Coulobre Panel</title><style>{STYLE}</style></head>
|
||||
<body><main><h1>Install Coulobre Panel</h1>{body}</main></body>
|
||||
<body><main><h1><img src="/favicon.svg" alt="">Install Coulobre Panel</h1>
|
||||
{body}</main></body>
|
||||
</html>""".encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
@@ -234,7 +240,7 @@ class WizardHandler(BaseHTTPRequestHandler):
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'none'; style-src 'unsafe-inline'; "
|
||||
"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; "
|
||||
"form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
|
||||
)
|
||||
if cookie:
|
||||
@@ -254,12 +260,21 @@ class WizardHandler(BaseHTTPRequestHandler):
|
||||
return self.headers.get("Host") == self.server.authority
|
||||
|
||||
def do_GET(self):
|
||||
if not self.host_allowed() or self.path != "/":
|
||||
if not self.host_allowed() or self.path not in {"/", "/favicon.svg"}:
|
||||
self.page(
|
||||
"<p>Use the installer address shown in the terminal.</p>",
|
||||
status=403,
|
||||
)
|
||||
return
|
||||
if self.path == "/favicon.svg":
|
||||
svg = BRAND_MARK.read_bytes()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "image/svg+xml")
|
||||
self.send_header("Content-Length", str(len(svg)))
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.end_headers()
|
||||
self.wfile.write(svg)
|
||||
return
|
||||
state = self.server.wizard
|
||||
if not self.authorized():
|
||||
self.page(
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Coulobre single-server release updater socket
|
||||
|
||||
[Socket]
|
||||
ListenStream=/run/coulobre-update.sock
|
||||
SocketUser=coulobre-panel
|
||||
SocketGroup=root
|
||||
SocketMode=0600
|
||||
Accept=yes
|
||||
MaxConnections=3
|
||||
RemoveOnStop=true
|
||||
|
||||
[Install]
|
||||
WantedBy=sockets.target
|
||||
@@ -0,0 +1,22 @@
|
||||
[Unit]
|
||||
Description=Coulobre single-server release update
|
||||
After=mariadb.service network-online.target
|
||||
CollectMode=inactive-or-failed
|
||||
|
||||
[Service]
|
||||
Type=exec
|
||||
User=root
|
||||
WorkingDirectory=/opt/coulobre
|
||||
EnvironmentFile=/etc/coulobre/panel.env
|
||||
StateDirectory=coulobre-update
|
||||
StateDirectoryMode=0700
|
||||
UMask=0077
|
||||
ExecStart=/opt/coulobre/bin/coulobre-update
|
||||
StandardInput=socket
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
RuntimeMaxSec=60min
|
||||
NoNewPrivileges=true
|
||||
ProtectHome=true
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/opt/coulobre
|
||||
+196
-9
@@ -542,7 +542,8 @@ From the unpacked source release, upgrade the existing virtual environment
|
||||
and use the [management command helper](#prepare-the-panel).
|
||||
|
||||
```sh
|
||||
sudo /opt/coulobre/bin/pip install --upgrade '.[server,mariadb]'
|
||||
sudo /opt/coulobre/bin/python -m pip install --only-binary=:all: 'pip>=26.2'
|
||||
sudo /opt/coulobre/bin/python -m pip install --upgrade '.[server,mariadb]'
|
||||
panel_manage migrate --noinput
|
||||
panel_manage collectstatic --noinput
|
||||
```
|
||||
@@ -573,6 +574,189 @@ sudo systemctl daemon-reload
|
||||
sudo systemctl start coulobre-panel.service coulobre-worker.service coulobre-beat.service
|
||||
```
|
||||
|
||||
### Upgrade from v0.10 to v0.10.1
|
||||
|
||||
Use the in-place procedure above to install v0.10.1 and apply its migrations.
|
||||
Existing DNS zones keep their records. Use **DNS zone template** under
|
||||
**Server and services** to change the defaults for new zones. Use **Complete
|
||||
hosting setup** on an existing account to review and add missing services.
|
||||
|
||||
To include mail client details in new invitations, set
|
||||
`COULOBRE_MAIL_IMAP_HOST` and `COULOBRE_MAIL_SUBMISSION_HOST` to the respective
|
||||
client-facing names when these services are available. For an upgraded panel
|
||||
without service checks, follow [the collector setup](#monitor-local-and-remote-services).
|
||||
|
||||
### Install a compatible release from the panel
|
||||
|
||||
The installer enables **Updates** for installer-managed panels. On an
|
||||
existing panel, install the updater units from the source release matching
|
||||
the installed package:
|
||||
|
||||
```sh
|
||||
sudo install -m 0644 deploy/systemd/coulobre-update.socket \
|
||||
deploy/systemd/coulobre-update@.service /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now coulobre-update.socket
|
||||
```
|
||||
|
||||
A superuser with a verified second factor can choose a compatible release
|
||||
from **Server and services → Updates**. The updater uses the official Gitea
|
||||
release over HTTPS and checks the wheel against its published SHA-256 hash.
|
||||
It supports the installer-managed local MariaDB database and installer
|
||||
layout. The update manifest lists the tested starting versions. Use the
|
||||
in-place procedure for custom service unit changes and for environments
|
||||
missing a dependency required by the target version. From 0.11 onward, the
|
||||
updater checks installed dependencies before stopping panel services.
|
||||
|
||||
The panel and its workers pause during the upgrade. Refresh **Updates** after
|
||||
the panel returns. The latest update status names the recovery directory in
|
||||
`/var/lib/coulobre-update/`. The root-only directory holds the previous
|
||||
virtual environment, `/etc/coulobre` configuration, MariaDB dump, unit list
|
||||
and operation log. Keep enough free space for these copies. Review progress
|
||||
and service errors with `sudo journalctl -u 'coulobre-update@*'`.
|
||||
|
||||
If recovery is required, keep the panel and its workers stopped. Use the
|
||||
saved `units.json` to identify the active units before the update. Restore
|
||||
`venv` to `/opt/coulobre` at the same path and restore the saved `config` to
|
||||
`/etc/coulobre` if needed. Import `panel.sql` with `sudo mariadb` to replace
|
||||
the panel database with the pre-upgrade copy. Rebuild panel static files
|
||||
with `panel_manage collectstatic --noinput`, restart the saved units and
|
||||
verify sign-in and service health. Archive `status.json` as root after
|
||||
recovery to allow a later update. Check that `panel.sql` and `venv` exist
|
||||
before restoring from a directory created by an interrupted update.
|
||||
|
||||
### Coordinate a release across linked mail and DNS receivers
|
||||
|
||||
Use the in-place procedure for the first upgrade from 0.10 to 0.11 in a
|
||||
linked deployment. The older web updater supports single-server upgrades.
|
||||
Bring the receiver and all attached panels to the same release before
|
||||
resuming provisioning. For manually configured relays, including separate
|
||||
mail credential and archive relays, use the in-place procedure for the
|
||||
whole fleet.
|
||||
|
||||
The **Updates** page in 0.11 reports the release, host, and status probe
|
||||
protocol of each installer-enrolled receiver. Protocol 1 reports readiness
|
||||
and release. Protocol 2 also reports a staged maintenance target. This is
|
||||
a read-only addition to the probe. The mail and DNS apply request formats
|
||||
keep their existing per-operation versions. Active provisioning requires
|
||||
matching package releases. During a coordinated upgrade, the receiver
|
||||
keeps provisioning requests paused while panels are on different releases.
|
||||
Normal mail delivery, IMAP, and existing DNS answers can continue while
|
||||
the provisioning socket is stopped or paused.
|
||||
|
||||
1. At each receiver, list the authorized panel keys. Match each fingerprint
|
||||
to a panel and confirm its installed version on that host. Include every
|
||||
key, including panels operated by another team. Back up the panels, the
|
||||
receiver packages, and the managed mail or DNS configuration. Pause
|
||||
new provisioning requests and let current jobs finish.
|
||||
|
||||
```sh
|
||||
sudo /opt/coulobre/bin/coulobre-node-setup list-panels dns
|
||||
```
|
||||
|
||||
2. Save a root-owned JSON inventory with mode 0600, the target package version and a
|
||||
fingerprint-to-version map. Replace the fingerprints and versions with
|
||||
your actual values. Make a separate inventory for each role on a host.
|
||||
|
||||
```json
|
||||
{
|
||||
"target": "0.11.1rc1",
|
||||
"panels": {
|
||||
"SHA256:panel-one-fingerprint": "0.11.0rc1",
|
||||
"SHA256:panel-two-fingerprint": "0.11.0rc1"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. Stop the receiver socket and let instances of the corresponding apply
|
||||
service finish. Stage the inventory, update the receiver to the target,
|
||||
then start its socket again. Replace `dns` with `mail` for a mail receiver.
|
||||
The staged receiver answers status probes and rejects apply requests.
|
||||
|
||||
```sh
|
||||
sudo systemctl stop coulobre-dns-apply.socket
|
||||
sudo /opt/coulobre/bin/coulobre-node-setup begin-maintenance dns /root/dns-upgrade.json
|
||||
# Install the reviewed target package using its release instructions.
|
||||
sudo systemctl start coulobre-dns-apply.socket
|
||||
```
|
||||
|
||||
4. Refresh **Updates** on each panel. Install the target when all its
|
||||
receivers report that release in maintenance mode and the compatible
|
||||
release is offered. Use the in-place procedure if its update requires
|
||||
additional dependencies or unit changes. Keep the receivers staged if
|
||||
any panel upgrade is interrupted. Check the recovery files and repair or
|
||||
roll back before reopening provisioning.
|
||||
5. Once every panel is running and verified at the target, update each
|
||||
inventory with the observed installed versions. Finish maintenance on each
|
||||
receiver, then resume provisioning and retry any affected operations.
|
||||
The command checks the receiver release and the inventory against the
|
||||
current authorized keys. The receiver administrator is responsible for
|
||||
checking the installed version reported by every panel operator.
|
||||
|
||||
```sh
|
||||
sudo /opt/coulobre/bin/coulobre-node-setup finish-maintenance dns /root/dns-upgrade.json
|
||||
```
|
||||
|
||||
### Limit linked provisioning to assigned domains
|
||||
|
||||
Use scoped keys when independent panels share a DNS or mail receiver. The
|
||||
receiver authenticates a dedicated Unix account for each panel and checks
|
||||
the requested domain before applying changes or inspecting its mail queue.
|
||||
Each scope lists exact domains. DNS parent and child zones must belong to
|
||||
the same panel if their scopes overlap.
|
||||
|
||||
Upgrade the receiver and the panels, then apply the current receiver SSH
|
||||
configuration with `coulobre-node-setup --source /path/to/release
|
||||
install-receiver dns` (or `mail`). Prepare the panel's role-specific key.
|
||||
Copy its public half to the receiver and authorize the domains.
|
||||
|
||||
```sh
|
||||
# On the panel
|
||||
sudo /opt/coulobre/bin/coulobre-node-setup prepare-panel dns
|
||||
|
||||
# On the receiver
|
||||
sudo /opt/coulobre/bin/coulobre-node-setup authorize-scoped-panel \
|
||||
dns panel-one /root/panel-one-dns.pub example.net
|
||||
|
||||
# On the panel, using the receiver's verified host key
|
||||
sudo /opt/coulobre/bin/coulobre-node-setup --source /path/to/release \
|
||||
enrol-panel dns dns.example.org /root/dns-host.pub --scope panel-one
|
||||
```
|
||||
|
||||
Repeat authorization with the same public key and the complete desired
|
||||
domain list when assignments change. For an existing unrestricted receiver,
|
||||
coordinate a maintenance window, back up and remove unrestricted panel
|
||||
keys, enroll the scoped identities, and check both panels before resuming
|
||||
provisioning. For an existing panel relay, update the `User` directive in
|
||||
its role-specific `/etc/coulobre-remote/<role>/ssh_config` to the scoped
|
||||
username printed by authorization. Keep its pinned host key and run
|
||||
`coulobre-node-setup check-panel <role>` before enabling jobs.
|
||||
|
||||
On scoped mail receivers, use local administrative workflows for mailbox
|
||||
credential and archive operations. The separate legacy SSH transports for
|
||||
those operations are unavailable on a scoped receiver. Local mail
|
||||
delivery and IMAP keep using their existing configuration.
|
||||
|
||||
### Use SHA-2 for new managed database logins
|
||||
|
||||
On a MariaDB build with `auth_mysql_sha2`, you can provision new managed
|
||||
database logins with `caching_sha2_password`. Verify the active site's PHP
|
||||
driver, phpMyAdmin, and administrative clients against a test login before
|
||||
changing the policy. Coulobre retains the authentication plugin and password
|
||||
for each existing login.
|
||||
|
||||
```sh
|
||||
sudo mariadb -e "INSTALL SONAME 'auth_mysql_sha2';"
|
||||
printf '%s\n' caching_sha2_password | sudo tee /etc/coulobre/database-authentication
|
||||
sudo chown root:root /etc/coulobre/database-authentication
|
||||
sudo chmod 0644 /etc/coulobre/database-authentication
|
||||
```
|
||||
|
||||
Managed logins remain restricted to localhost. If the target host needs an
|
||||
older driver or does not supply the SHA-2 plugin, use
|
||||
`mysql_native_password` as the policy for new logins. Keep the SHA-2 plugin
|
||||
loaded as long as any existing managed login uses it.
|
||||
|
||||
### Upgrade from v0.9 to v0.10
|
||||
|
||||
Use the in-place procedure above with the v0.10 source release. Keep a copy
|
||||
@@ -1065,10 +1249,12 @@ sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
|
||||
sudo systemctl enable --now coulobre-database-provisioner.service
|
||||
```
|
||||
|
||||
Open a hosting account and select **Provision database** for a database request.
|
||||
Reload the account page to see the status. Use **Retry provisioning** after a
|
||||
reported failure. Operators need permission to view hosting accounts and
|
||||
database requests and the **Can add database provisioning** permission.
|
||||
Select **Add database** on a hosting account to queue its provisioning.
|
||||
Customers can add databases on their own accounts. Customer managers need
|
||||
permission to manage resources for their assigned accounts. For a pending
|
||||
request, an operator can select **Provision database**. Operators need
|
||||
permission to view hosting accounts and databases and the **Can add database
|
||||
provisioning** permission. Use **Retry provisioning** after a reported failure.
|
||||
|
||||
The MariaDB node stores the application login in the root-only file
|
||||
`/var/lib/coulobre/database-node/<database-name>.json`. Use the credentials
|
||||
@@ -1724,10 +1910,11 @@ sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
|
||||
sudo systemctl enable --now coulobre-dns-publisher.service
|
||||
```
|
||||
|
||||
Open a hosting account and select **Publish zone**. Reload the account page to
|
||||
see progress and the last SOA serial confirmed by the local BIND9 node.
|
||||
Operators need permission to view hosting accounts and DNS zones and the
|
||||
**Can add DNS publication** permission.
|
||||
Select **Save and publish zone** to queue a new zone from a hosting account.
|
||||
Use **Publish zone** to publish a pending revision of an existing zone.
|
||||
The account page shows progress and the last SOA serial confirmed by the
|
||||
local BIND9 node. Operators need permission to view hosting accounts and DNS
|
||||
zones and the **Can add DNS publication** permission.
|
||||
|
||||
Each request captures the reviewed SOA serial and records. You can edit the
|
||||
zone while it publishes. Publish the newer revision after the current request
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# Security
|
||||
|
||||
## Report vulnerabilities privately
|
||||
|
||||
Contact a project maintainer privately with the affected release, the
|
||||
deployment layout, the affected roles, and a description of the impact.
|
||||
Share minimal evidence using test data. Remove credentials, tokens,
|
||||
customer data, private keys, and identifiable account information. If you
|
||||
cannot find a private channel, open a Gitea issue requesting private
|
||||
contact and leave the technical details out of the issue.
|
||||
|
||||
Maintainers confirm scope, coordinate remediation with the reporter, and
|
||||
publish an advisory with the fixed releases and any operational mitigations
|
||||
after users have a way to update.
|
||||
|
||||
## Panel and account access
|
||||
|
||||
- Serve the panel over HTTPS. If you use a reverse proxy, restrict the
|
||||
private origin to that proxy and let the managed Apache configuration set
|
||||
the forwarding headers. Keep debug mode off on shared or public hosts.
|
||||
- Require two-factor authentication for staff and customer managers. Use an
|
||||
authenticator app for administrative accounts and keep recovery codes in a
|
||||
protected location. The **My account** page lets users verify a new email
|
||||
address, replace their authenticator, renew recovery codes, and revoke
|
||||
other panel sessions. Revoking panel sessions also clears unused service
|
||||
login tickets. Webmail, database, and SSH sessions established separately
|
||||
have their own lifetimes.
|
||||
- During customer impersonation, use only the approved support
|
||||
actions. Review impersonation and credential access events. Account
|
||||
security actions are recorded separately and visible to the account owner.
|
||||
- Verify that the panel can deliver account messages and email factors.
|
||||
Treat an address used for password recovery or an email factor as a
|
||||
credential and check it after changing it.
|
||||
|
||||
## Service boundaries and recovery
|
||||
|
||||
- Restrict the panel database and RabbitMQ to local access. Expose only
|
||||
the client-facing ports for the functions you run. Keep Unix sockets and
|
||||
environment files restricted to the identities listed in the deployment
|
||||
guide. Keep each site's PHP-FPM pool and SFTP keys scoped to that site.
|
||||
- Pin SSH host keys for linked nodes and off-site backups. Use separate
|
||||
domain-scoped keys for independent panels that share a receiver. Keep
|
||||
unrestricted keys within one trusted operator group. The linked-node
|
||||
upgrade runbook accounts for every authorized panel key.
|
||||
- Review DNS delegation, mail routing permissions, and allowed forwarding.
|
||||
Keep private DKIM material on the mail receiver and publish the matching
|
||||
public records. Verify the mail configuration after changing packages.
|
||||
- Store backup destinations and their keys separately from hosted content.
|
||||
Protect recovery copies of the virtual environment and database. Test
|
||||
website, database, and mailbox restores with isolated accounts and check
|
||||
ownership and access afterwards.
|
||||
- Keep Ubuntu or Debian packages and the panel's Python environment on
|
||||
security-supported versions. Check installed dependencies against a
|
||||
vulnerability advisory source such as OSV before a release. Verify both
|
||||
distribution files against the reviewed Git revision and check the
|
||||
wheel digest before enabling a web update.
|
||||
|
||||
Use the [deployment guide](deployment.md) for operating-system support,
|
||||
configuration and recovery steps.
|
||||
+7
-5
@@ -4,18 +4,18 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "coulobre-panel"
|
||||
version = "0.10.0rc1"
|
||||
version = "0.11.1rc1"
|
||||
description = "A web hosting control panel for hosting providers and resellers."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
license = "Apache-2.0"
|
||||
dependencies = [
|
||||
"Django>=5.2.8,<5.3",
|
||||
"Django>=5.2.17,<5.3",
|
||||
"django-otp>=1.7.5,<2",
|
||||
"celery>=5.6,<6",
|
||||
"cryptography>=45",
|
||||
"dnspython>=2.7,<3",
|
||||
"idna>=3,<4",
|
||||
"cryptography>=50",
|
||||
"dnspython>=2.9.2,<3",
|
||||
"idna>=3.15,<4",
|
||||
"qrcode>=8.2,<9",
|
||||
]
|
||||
|
||||
@@ -30,6 +30,7 @@ coulobre-mail-node = "coulobre.mail_node:main"
|
||||
coulobre-node-setup = "coulobre.node_setup:main"
|
||||
coulobre-service-credentials = "coulobre.service_credentials:main"
|
||||
coulobre-service-health = "coulobre.service_health:main"
|
||||
coulobre-update = "coulobre.local_update:main"
|
||||
coulobre-web-node = "coulobre.web_node:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
@@ -41,6 +42,7 @@ server = ["gunicorn>=27.0.1,<28"]
|
||||
"coulobre.hosting" = [
|
||||
"static/hosting/*.js",
|
||||
"static/hosting/*.css",
|
||||
"static/hosting/*.svg",
|
||||
"templates/*.html",
|
||||
"templates/hosting/*.conf",
|
||||
"templates/hosting/*.html",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from contextlib import closing, contextmanager, suppress
|
||||
from pathlib import Path
|
||||
@@ -8,6 +9,7 @@ from pathlib import Path
|
||||
from .credential_rotation import (
|
||||
ROTATION_IN_PROGRESS,
|
||||
rotation_path,
|
||||
save_credential_record,
|
||||
valid_generation,
|
||||
)
|
||||
from .node_files import read_root_file, require_root_directory, write_new_file
|
||||
@@ -15,6 +17,10 @@ from .node_retirement import RetirementRecord
|
||||
|
||||
STATE_DIRECTORY = Path("/var/lib/coulobre/database-node")
|
||||
MANAGED_COMMENT_PREFIX = "Coulobre managed database "
|
||||
AUTHENTICATION_POLICY = Path("/etc/coulobre/database-authentication")
|
||||
NATIVE_PASSWORD = "mysql_native_password"
|
||||
SHA2_PASSWORD = "caching_sha2_password"
|
||||
SHA2_VERIFIER = re.compile(r"[0-9A-F]+")
|
||||
|
||||
|
||||
def apply_database(database, socket):
|
||||
@@ -25,8 +31,8 @@ def apply_database(database, socket):
|
||||
require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750)
|
||||
require_root_directory(STATE_DIRECTORY, create_mode=0o700)
|
||||
record_path = STATE_DIRECTORY / f"{database.name}.json"
|
||||
with locked_cursor(database, socket) as (_, cursor):
|
||||
install_database(cursor, database, socket, record_path)
|
||||
with locked_cursor(database, socket) as (driver, cursor):
|
||||
install_database(cursor, database, socket, record_path, driver=driver)
|
||||
return record_path
|
||||
|
||||
|
||||
@@ -71,18 +77,25 @@ def locked_cursor(database, socket):
|
||||
) from None
|
||||
|
||||
|
||||
def read_resources(cursor, name):
|
||||
def read_resources(cursor, name, *, sha2=False):
|
||||
cursor.execute(
|
||||
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA "
|
||||
"WHERE SCHEMA_NAME = %s",
|
||||
(name,),
|
||||
)
|
||||
schema = cursor.fetchone()
|
||||
cursor.execute(
|
||||
"SELECT Host, plugin, authentication_string FROM mysql.user "
|
||||
"WHERE User = %s",
|
||||
(name,),
|
||||
)
|
||||
if sha2:
|
||||
cursor.execute(
|
||||
"SELECT Host, plugin, HEX(authentication_string), "
|
||||
"authentication_string FROM mysql.user WHERE User = %s",
|
||||
(name,),
|
||||
)
|
||||
else:
|
||||
cursor.execute(
|
||||
"SELECT Host, plugin, authentication_string FROM mysql.user "
|
||||
"WHERE User = %s",
|
||||
(name,),
|
||||
)
|
||||
return schema, cursor.fetchall()
|
||||
|
||||
|
||||
@@ -126,11 +139,11 @@ def checked_credentials(
|
||||
pending_password=None,
|
||||
):
|
||||
name = database.name
|
||||
schema, users = read_resources(cursor, name)
|
||||
ready_path = record_path.with_suffix(".ready")
|
||||
with suppress(FileNotFoundError):
|
||||
require_root_directory(record_path.parent)
|
||||
if not os.path.lexists(record_path):
|
||||
schema, users = read_resources(cursor, name)
|
||||
if os.path.lexists(ready_path) or schema is not None or users:
|
||||
raise ValueError(
|
||||
"The database, login, or completion marker has no local "
|
||||
@@ -147,30 +160,46 @@ def checked_credentials(
|
||||
rotation_path(record_path)
|
||||
):
|
||||
raise ValueError(ROTATION_IN_PROGRESS)
|
||||
sha2 = uses_sha2(record)
|
||||
schema, users = read_resources(cursor, name, sha2=sha2)
|
||||
password = record["password"]
|
||||
if pending_password is not None and users == (
|
||||
(
|
||||
"localhost",
|
||||
"mysql_native_password",
|
||||
native_password_hash(pending_password),
|
||||
),
|
||||
):
|
||||
password = pending_password
|
||||
password_hash = native_password_hash(password)
|
||||
if sha2:
|
||||
verifier, server_value = sha2_login(users)
|
||||
if verifier != record.get("authentication_verifier"):
|
||||
if not pending_password or not can_sign_in(
|
||||
driver, record, pending_password
|
||||
):
|
||||
raise ValueError(
|
||||
"The MariaDB verifier differs from the registry."
|
||||
)
|
||||
password = pending_password
|
||||
user_details = ("localhost", SHA2_PASSWORD, verifier, server_value)
|
||||
authentication = (
|
||||
f"IDENTIFIED VIA {SHA2_PASSWORD} USING '{server_value}'"
|
||||
)
|
||||
else:
|
||||
if pending_password is not None and users == (
|
||||
(
|
||||
"localhost",
|
||||
NATIVE_PASSWORD,
|
||||
native_password_hash(pending_password),
|
||||
),
|
||||
):
|
||||
password = pending_password
|
||||
password_hash = native_password_hash(password)
|
||||
user_details = ("localhost", NATIVE_PASSWORD, password_hash)
|
||||
authentication = f"IDENTIFIED BY PASSWORD '{password_hash}'"
|
||||
check_resources(
|
||||
schema,
|
||||
users,
|
||||
MANAGED_COMMENT_PREFIX + record["ownership"],
|
||||
password_hash,
|
||||
user_details,
|
||||
require_complete=True,
|
||||
)
|
||||
cursor.execute("SHOW GRANTS FOR %s@'localhost'", (name,))
|
||||
grantee = f"`{name}`@`localhost`"
|
||||
expected_grants = {
|
||||
(
|
||||
f"GRANT USAGE ON *.* TO {grantee} "
|
||||
f"IDENTIFIED BY PASSWORD '{password_hash}'",
|
||||
),
|
||||
(f"GRANT USAGE ON *.* TO {grantee} {authentication}",),
|
||||
(f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",),
|
||||
}
|
||||
grants = {
|
||||
@@ -184,25 +213,71 @@ def checked_credentials(
|
||||
and login_is_locked(cursor, name)
|
||||
):
|
||||
return record
|
||||
if not can_sign_in(driver, record, password):
|
||||
raise ValueError(
|
||||
"The stored application credentials cannot open the managed "
|
||||
"database."
|
||||
)
|
||||
return record
|
||||
|
||||
|
||||
def can_sign_in(driver, record, password):
|
||||
try:
|
||||
with closing(
|
||||
driver.connect(
|
||||
host="localhost",
|
||||
user=name,
|
||||
user=record["user"],
|
||||
passwd=password,
|
||||
db=name,
|
||||
unix_socket=str(socket),
|
||||
db=record["database"],
|
||||
unix_socket=record["socket"],
|
||||
connect_timeout=5,
|
||||
charset="utf8mb4",
|
||||
)
|
||||
):
|
||||
pass
|
||||
return True
|
||||
except driver.Error:
|
||||
return False
|
||||
|
||||
|
||||
def uses_sha2(record):
|
||||
return record.get("authentication_plugin") == SHA2_PASSWORD
|
||||
|
||||
|
||||
def sha2_login(users):
|
||||
if len(users) != 1 or len(users[0]) != 4:
|
||||
raise ValueError("Expected one managed MariaDB SHA-2 login.")
|
||||
host, plugin, verifier, server_value = users[0]
|
||||
if (
|
||||
host != "localhost"
|
||||
or plugin != SHA2_PASSWORD
|
||||
or not isinstance(verifier, str)
|
||||
or not SHA2_VERIFIER.fullmatch(verifier)
|
||||
or not isinstance(server_value, str)
|
||||
or not server_value
|
||||
):
|
||||
raise ValueError("The existing MariaDB SHA-2 login is invalid.")
|
||||
return verifier, server_value
|
||||
|
||||
|
||||
def configured_authentication(cursor):
|
||||
try:
|
||||
policy = read_root_file(AUTHENTICATION_POLICY, mode=0o644).strip()
|
||||
except FileNotFoundError:
|
||||
return NATIVE_PASSWORD
|
||||
if policy == NATIVE_PASSWORD:
|
||||
return policy
|
||||
if policy != SHA2_PASSWORD:
|
||||
raise ValueError("Choose a supported MariaDB authentication plugin.")
|
||||
cursor.execute(
|
||||
"SELECT PLUGIN_STATUS FROM information_schema.PLUGINS "
|
||||
"WHERE PLUGIN_NAME = %s",
|
||||
(policy,),
|
||||
)
|
||||
if cursor.fetchone() != ("ACTIVE",):
|
||||
raise ValueError(
|
||||
"The stored application credentials cannot open the managed "
|
||||
"database."
|
||||
) from None
|
||||
return record
|
||||
"Enable the MariaDB caching_sha2_password plugin first."
|
||||
)
|
||||
return policy
|
||||
|
||||
|
||||
def check_restore_complete(record_path):
|
||||
@@ -212,7 +287,7 @@ def check_restore_complete(record_path):
|
||||
)
|
||||
|
||||
|
||||
def install_database(cursor, database, socket, record_path):
|
||||
def install_database(cursor, database, socket, record_path, *, driver=None):
|
||||
if os.path.lexists(record_path.with_suffix(".retired")):
|
||||
raise ValueError(
|
||||
"This database is retained for a retired hosting account."
|
||||
@@ -221,17 +296,44 @@ def install_database(cursor, database, socket, record_path):
|
||||
raise ValueError(ROTATION_IN_PROGRESS)
|
||||
check_restore_complete(record_path)
|
||||
name = database.name
|
||||
schema, users = read_resources(cursor, name)
|
||||
ready_path = record_path.with_suffix(".ready")
|
||||
record = reserve_credentials(
|
||||
database, socket, record_path, ready_path, schema, users
|
||||
existing = os.path.lexists(record_path)
|
||||
record = (
|
||||
load_credentials(database, socket, record_path) if existing else {}
|
||||
)
|
||||
comment = MANAGED_COMMENT_PREFIX + record["ownership"]
|
||||
password_hash = native_password_hash(record["password"])
|
||||
|
||||
plugin = (
|
||||
record.get("authentication_plugin", NATIVE_PASSWORD)
|
||||
if existing
|
||||
else configured_authentication(cursor)
|
||||
)
|
||||
sha2 = plugin == SHA2_PASSWORD
|
||||
schema, users = read_resources(cursor, name, sha2=sha2)
|
||||
ready_path = record_path.with_suffix(".ready")
|
||||
if not existing:
|
||||
record = reserve_credentials(
|
||||
database, socket, record_path, ready_path, schema, users, plugin
|
||||
)
|
||||
ready = check_completion_marker(ready_path, record)
|
||||
if ready and sha2:
|
||||
checked_credentials(driver, cursor, database, socket, record_path)
|
||||
return
|
||||
comment = MANAGED_COMMENT_PREFIX + record["ownership"]
|
||||
password = record["password"]
|
||||
if sha2:
|
||||
if users:
|
||||
verifier, server_value = sha2_login(users)
|
||||
expected_user = (
|
||||
"localhost",
|
||||
SHA2_PASSWORD,
|
||||
verifier,
|
||||
server_value,
|
||||
)
|
||||
else:
|
||||
expected_user = None
|
||||
else:
|
||||
password_hash = native_password_hash(password)
|
||||
expected_user = ("localhost", NATIVE_PASSWORD, password_hash)
|
||||
check_resources(
|
||||
schema, users, comment, password_hash, require_complete=ready
|
||||
schema, users, comment, expected_user, require_complete=ready
|
||||
)
|
||||
|
||||
if schema is None:
|
||||
@@ -241,24 +343,40 @@ def install_database(cursor, database, socket, record_path):
|
||||
(comment,),
|
||||
)
|
||||
if not users:
|
||||
cursor.execute(
|
||||
"CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password "
|
||||
"USING %s",
|
||||
(name, password_hash),
|
||||
)
|
||||
if sha2:
|
||||
cursor.execute(
|
||||
"CREATE USER %s@'localhost' IDENTIFIED VIA "
|
||||
"caching_sha2_password USING PASSWORD(%s)",
|
||||
(name, password),
|
||||
)
|
||||
else:
|
||||
cursor.execute(
|
||||
"CREATE USER %s@'localhost' IDENTIFIED VIA "
|
||||
"mysql_native_password USING %s",
|
||||
(name, password_hash),
|
||||
)
|
||||
|
||||
cursor.execute(
|
||||
f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO %s@'localhost'",
|
||||
(name,),
|
||||
)
|
||||
if sha2:
|
||||
_, users = read_resources(cursor, name, sha2=True)
|
||||
verifier, _ = sha2_login(users)
|
||||
if not can_sign_in(driver, record, password):
|
||||
raise ValueError(
|
||||
"The managed MariaDB SHA-2 login could not sign in."
|
||||
)
|
||||
save_credential_record(
|
||||
record_path, record | {"authentication_verifier": verifier}
|
||||
)
|
||||
if not ready:
|
||||
write_new_file(ready_path, record["ownership"] + "\n", mode=0o600)
|
||||
|
||||
|
||||
def reserve_credentials(database, socket, path, ready_path, schema, users):
|
||||
if os.path.lexists(path):
|
||||
return load_credentials(database, socket, path)
|
||||
|
||||
def reserve_credentials(
|
||||
database, socket, path, ready_path, schema, users, plugin
|
||||
):
|
||||
if os.path.lexists(ready_path) or schema is not None or users:
|
||||
raise ValueError(
|
||||
"The database name or login already exists outside Coulobre's "
|
||||
@@ -269,6 +387,8 @@ def reserve_credentials(database, socket, path, ready_path, schema, users):
|
||||
"password": secrets.token_urlsafe(32),
|
||||
"ownership": secrets.token_hex(16),
|
||||
}
|
||||
if plugin == SHA2_PASSWORD:
|
||||
record["authentication_plugin"] = plugin
|
||||
write_new_file(path, json.dumps(record, indent=2) + "\n", mode=0o600)
|
||||
return record
|
||||
|
||||
@@ -296,6 +416,8 @@ def load_credentials(database, socket, path):
|
||||
or not isinstance(record.get("password"), str)
|
||||
or not record["password"]
|
||||
or not record["password"].isascii()
|
||||
or record.get("authentication_plugin", NATIVE_PASSWORD)
|
||||
not in (NATIVE_PASSWORD, SHA2_PASSWORD)
|
||||
or not valid_generation(record.get("rotation_id"))
|
||||
or not isinstance(record.get("ownership"), str)
|
||||
or not record["ownership"]
|
||||
@@ -325,7 +447,7 @@ def check_completion_marker(path, record):
|
||||
|
||||
|
||||
def check_resources(
|
||||
schema, users, comment, password_hash, *, require_complete
|
||||
schema, users, comment, expected_user, *, require_complete
|
||||
):
|
||||
if require_complete and (schema is None or not users):
|
||||
raise ValueError(
|
||||
@@ -336,9 +458,7 @@ def check_resources(
|
||||
raise ValueError(
|
||||
"The existing database has a different ownership marker."
|
||||
)
|
||||
if users and users != (
|
||||
("localhost", "mysql_native_password", password_hash),
|
||||
):
|
||||
if users and users != (expected_user,):
|
||||
raise ValueError(
|
||||
"The existing MariaDB login differs from its managed credentials."
|
||||
)
|
||||
|
||||
@@ -37,11 +37,18 @@ def rotate_database_credentials(request, socket):
|
||||
pending = stage_rotation(path, request, generation)
|
||||
if generation != request.rotation_id:
|
||||
password = pending["password"]
|
||||
cursor.execute(
|
||||
"ALTER USER %s@'localhost' "
|
||||
"IDENTIFIED VIA mysql_native_password USING %s",
|
||||
(database.name, db.native_password_hash(password)),
|
||||
)
|
||||
if db.uses_sha2(record):
|
||||
cursor.execute(
|
||||
"ALTER USER %s@'localhost' IDENTIFIED VIA "
|
||||
"caching_sha2_password USING PASSWORD(%s)",
|
||||
(database.name, password),
|
||||
)
|
||||
else:
|
||||
cursor.execute(
|
||||
"ALTER USER %s@'localhost' "
|
||||
"IDENTIFIED VIA mysql_native_password USING %s",
|
||||
(database.name, db.native_password_hash(password)),
|
||||
)
|
||||
db.checked_credentials(
|
||||
driver,
|
||||
cursor,
|
||||
@@ -55,6 +62,10 @@ def rotate_database_credentials(request, socket):
|
||||
"password": password,
|
||||
"rotation_id": request.rotation_id,
|
||||
}
|
||||
if db.uses_sha2(record):
|
||||
_, users = db.read_resources(cursor, database.name, sha2=True)
|
||||
verifier, _ = db.sha2_login(users)
|
||||
record["authentication_verifier"] = verifier
|
||||
save_credential_record(path, record)
|
||||
finish_rotation(path)
|
||||
return record
|
||||
|
||||
@@ -0,0 +1,463 @@
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from smtplib import SMTPException
|
||||
|
||||
import django_otp
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth import update_session_auth_hash
|
||||
from django.contrib.auth.hashers import check_password
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.contrib.auth.password_validation import validate_password
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.core.mail import send_mail
|
||||
from django.db import transaction
|
||||
from django.shortcuts import redirect, render
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.crypto import constant_time_compare
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.debug import (
|
||||
sensitive_post_parameters,
|
||||
sensitive_variables,
|
||||
)
|
||||
from django.views.generic import FormView, TemplateView
|
||||
from django_otp.plugins.otp_email.models import EmailDevice
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
|
||||
from .models import PanelEmailChange, PanelSecurityEvent
|
||||
from .panel_factors import (
|
||||
DEVICE_NAME,
|
||||
DEVICE_TYPES,
|
||||
RECOVERY_SIGN_IN,
|
||||
confirmed_device,
|
||||
device_for_user,
|
||||
lock_user,
|
||||
replace_recovery_codes,
|
||||
secret_digest,
|
||||
send_factor_code,
|
||||
user_devices,
|
||||
)
|
||||
from .panel_sessions import (
|
||||
preserve_session,
|
||||
record_security_event,
|
||||
revoke_other_sessions,
|
||||
session_is_current,
|
||||
)
|
||||
from .sign_in import ConfirmFactorForm, authenticator_setup
|
||||
from .sign_in_limits import limit_attempt
|
||||
|
||||
Action = PanelSecurityEvent.Action
|
||||
ACCOUNT_URL = reverse_lazy("panel:account_security")
|
||||
FACTOR_SETUP = "coulobre_account_factor_setup"
|
||||
|
||||
|
||||
class AccountSecurityMixin(LoginRequiredMixin):
|
||||
@method_decorator(never_cache)
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if getattr(request, "impersonation", None):
|
||||
raise PermissionDenied
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
|
||||
class AccountSecurityView(AccountSecurityMixin, TemplateView):
|
||||
template_name = "hosting/account_security.html"
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
user = self.request.user
|
||||
device = confirmed_device(user)
|
||||
factor = "Authenticator app" if device else "Not set up"
|
||||
if isinstance(device, EmailDevice):
|
||||
factor = "Email code"
|
||||
return super().get_context_data(
|
||||
factor=factor,
|
||||
factor_enabled=device is not None,
|
||||
email_available=bool(settings.EMAIL_HOST),
|
||||
events=PanelSecurityEvent.objects.filter(user=user).order_by(
|
||||
"-id"
|
||||
)[:10],
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
class AuthorizeForm(forms.Form):
|
||||
password = forms.CharField(
|
||||
label="Current password",
|
||||
strip=False,
|
||||
max_length=4096,
|
||||
widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
|
||||
)
|
||||
code = ConfirmFactorForm.base_fields["code"]
|
||||
|
||||
|
||||
class PasswordForm(AuthorizeForm):
|
||||
new_password = forms.CharField(
|
||||
max_length=4096,
|
||||
strip=False,
|
||||
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
|
||||
)
|
||||
confirm_password = forms.CharField(
|
||||
max_length=4096,
|
||||
strip=False,
|
||||
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
cleaned = super().clean()
|
||||
if (
|
||||
"new_password" in cleaned
|
||||
and "confirm_password" in cleaned
|
||||
and cleaned["new_password"] != cleaned["confirm_password"]
|
||||
):
|
||||
self.add_error("confirm_password", "The passwords differ.")
|
||||
return cleaned
|
||||
|
||||
|
||||
class EmailForm(AuthorizeForm):
|
||||
email = forms.EmailField(label="New email address", max_length=254)
|
||||
|
||||
|
||||
class VerifyEmailForm(forms.Form):
|
||||
code = forms.RegexField(
|
||||
r"\A[0-9a-fA-F]{12}\Z",
|
||||
label="Email verification code",
|
||||
widget=forms.TextInput(attrs={"autocomplete": "one-time-code"}),
|
||||
)
|
||||
|
||||
|
||||
@method_decorator(sensitive_post_parameters(), name="dispatch")
|
||||
class SecurityFormView(AccountSecurityMixin, FormView):
|
||||
template_name = "hosting/account_security_form.html"
|
||||
success_url = ACCOUNT_URL
|
||||
instructions = ""
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(
|
||||
heading=self.heading, instructions=self.instructions, **kwargs
|
||||
)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
return limit_attempt(
|
||||
request,
|
||||
"account-security",
|
||||
str(request.user.pk),
|
||||
address_limit=30,
|
||||
identity_limit=10,
|
||||
) or super().post(request, *args, **kwargs)
|
||||
|
||||
def locked_user(self):
|
||||
user = lock_user(self.request.user.pk)
|
||||
if (
|
||||
not user.is_active
|
||||
or not session_is_current(self.request, user)
|
||||
or not constant_time_compare(
|
||||
user.get_session_auth_hash(),
|
||||
self.request.user.get_session_auth_hash(),
|
||||
)
|
||||
):
|
||||
raise PermissionDenied
|
||||
return user
|
||||
|
||||
def changed_access(self, user, action):
|
||||
version = revoke_other_sessions(user)
|
||||
record_security_event(user, action)
|
||||
self.request.session.pop(RECOVERY_SIGN_IN, None)
|
||||
self.request.session.pop(FACTOR_SETUP, None)
|
||||
preserve_session(self.request, version)
|
||||
|
||||
@sensitive_variables("codes")
|
||||
def show_recovery_codes(self, codes):
|
||||
return render(
|
||||
self.request,
|
||||
"hosting/factor_recovery_codes.html",
|
||||
{
|
||||
"recovery_codes": "\n".join(codes),
|
||||
"destination": self.success_url,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class AuthorizedSecurityChange(SecurityFormView):
|
||||
form_class = AuthorizeForm
|
||||
|
||||
def get_form(self, form_class=None):
|
||||
form = super().get_form(form_class)
|
||||
if confirmed_device(self.request.user) is None:
|
||||
del form.fields["code"]
|
||||
return form
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(
|
||||
can_send_code=isinstance(
|
||||
confirmed_device(self.request.user), EmailDevice
|
||||
),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
if "send_code" not in request.POST:
|
||||
return super().post(request, *args, **kwargs)
|
||||
device = confirmed_device(request.user)
|
||||
if not isinstance(device, EmailDevice):
|
||||
raise PermissionDenied
|
||||
messages.info(
|
||||
request,
|
||||
send_factor_code(
|
||||
request.user, device.persistent_id, confirmed=True
|
||||
),
|
||||
)
|
||||
return redirect(request.path)
|
||||
|
||||
@transaction.atomic
|
||||
@sensitive_variables("form")
|
||||
def form_valid(self, form):
|
||||
user = self.locked_user()
|
||||
if not check_password(form.cleaned_data["password"], user.password):
|
||||
form.add_error("password", "The current password is incorrect.")
|
||||
return self.form_invalid(form)
|
||||
|
||||
self.validate_change(user, form)
|
||||
if form.errors:
|
||||
return self.form_invalid(form)
|
||||
|
||||
if not self.verify_current_factor(user, form):
|
||||
form.add_error(
|
||||
"code", "Enter a valid code from your current factor."
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
return self.apply_change(user, form)
|
||||
|
||||
def verify_current_factor(self, user, form):
|
||||
device = confirmed_device(user)
|
||||
return device is None or device.verify_token(
|
||||
form.cleaned_data.get("code", "")
|
||||
)
|
||||
|
||||
def validate_change(self, user, form):
|
||||
pass
|
||||
|
||||
|
||||
class ChangePasswordView(AuthorizedSecurityChange):
|
||||
heading = "Change password"
|
||||
instructions = "Changing your password signs out your other sessions."
|
||||
form_class = PasswordForm
|
||||
|
||||
def validate_change(self, user, form):
|
||||
try:
|
||||
validate_password(form.cleaned_data["new_password"], user)
|
||||
except forms.ValidationError as error:
|
||||
form.add_error("new_password", error)
|
||||
|
||||
@sensitive_variables("form")
|
||||
def apply_change(self, user, form):
|
||||
user.set_password(form.cleaned_data["new_password"])
|
||||
user.save(update_fields=["password"])
|
||||
update_session_auth_hash(self.request, user)
|
||||
self.changed_access(user, Action.PASSWORD)
|
||||
messages.success(self.request, "Your password was changed.")
|
||||
return redirect(self.success_url)
|
||||
|
||||
|
||||
class ChangeEmailView(AuthorizedSecurityChange):
|
||||
heading = "Change email address"
|
||||
instructions = "We will send a verification code to your new address."
|
||||
form_class = EmailForm
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if not settings.EMAIL_HOST:
|
||||
raise PermissionDenied
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def validate_change(self, user, form):
|
||||
if form.cleaned_data["email"].casefold() == user.email.casefold():
|
||||
form.add_error("email", "Enter a different email address.")
|
||||
|
||||
@sensitive_variables("code")
|
||||
def apply_change(self, user, form):
|
||||
email = form.cleaned_data["email"]
|
||||
code = secrets.token_hex(6)
|
||||
try:
|
||||
sent = send_mail(
|
||||
"Verify your new Coulobre Panel email address",
|
||||
f"Enter {code} on the page where you requested the change. "
|
||||
"The code expires in 15 minutes.",
|
||||
None,
|
||||
[email],
|
||||
)
|
||||
except (OSError, SMTPException):
|
||||
sent = 0
|
||||
if sent != 1:
|
||||
form.add_error(None, "The verification email could not be sent.")
|
||||
return self.form_invalid(form)
|
||||
|
||||
PanelEmailChange.objects.update_or_create(
|
||||
user=user,
|
||||
defaults={
|
||||
"email": email,
|
||||
"digest": secret_digest("email-change", code),
|
||||
"session_digest": self.session_digest(),
|
||||
"expires_at": timezone.now() + timedelta(minutes=15),
|
||||
},
|
||||
)
|
||||
return redirect("panel:account_email_verify")
|
||||
|
||||
def session_digest(self):
|
||||
return secret_digest("email-session", self.request.session.session_key)
|
||||
|
||||
|
||||
def notify_old_address(email):
|
||||
send_mail(
|
||||
"Your Coulobre Panel email address changed",
|
||||
"The email address on your account was changed. Contact your hosting "
|
||||
"provider if you did not request this change.",
|
||||
None,
|
||||
[email],
|
||||
)
|
||||
|
||||
|
||||
class VerifyEmailView(SecurityFormView):
|
||||
heading = "Verify your new email address"
|
||||
form_class = VerifyEmailForm
|
||||
|
||||
@sensitive_variables("form")
|
||||
@transaction.atomic
|
||||
def form_valid(self, form):
|
||||
user = self.locked_user()
|
||||
pending = PanelEmailChange.objects.filter(user=user).first()
|
||||
session_digest = secret_digest(
|
||||
"email-session", self.request.session.session_key
|
||||
)
|
||||
code_digest = secret_digest(
|
||||
"email-change", form.cleaned_data["code"].lower()
|
||||
)
|
||||
if (
|
||||
pending is None
|
||||
or pending.expires_at <= timezone.now()
|
||||
or not constant_time_compare(
|
||||
pending.session_digest, session_digest
|
||||
)
|
||||
or not constant_time_compare(pending.digest, code_digest)
|
||||
):
|
||||
form.add_error(
|
||||
"code", "The verification code is invalid or expired."
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
|
||||
previous_email = user.email
|
||||
user.email = pending.email
|
||||
user.save(update_fields=["email"])
|
||||
user_devices(user, EmailDevice).update(
|
||||
email=user.email, token=None, valid_until=timezone.now()
|
||||
)
|
||||
self.changed_access(user, Action.EMAIL)
|
||||
if previous_email:
|
||||
transaction.on_commit(
|
||||
lambda: notify_old_address(previous_email), robust=True
|
||||
)
|
||||
messages.success(self.request, "Your email address was changed.")
|
||||
return redirect(self.success_url)
|
||||
|
||||
|
||||
class StartAuthenticatorView(AuthorizedSecurityChange):
|
||||
heading = "Set up an authenticator app"
|
||||
instructions = "Your current factor works until you verify the new app."
|
||||
|
||||
def recently_used_recovery_code(self, user):
|
||||
recovery = self.request.session.get(RECOVERY_SIGN_IN, {})
|
||||
if recovery.get("expires", 0) <= int(timezone.now().timestamp()):
|
||||
return False
|
||||
device = confirmed_device(user)
|
||||
return device is not None and recovery.get("device") == (
|
||||
device.persistent_id
|
||||
)
|
||||
|
||||
def get_form(self, form_class=None):
|
||||
form = super().get_form(form_class)
|
||||
if self.recently_used_recovery_code(self.request.user):
|
||||
form.fields.pop("code", None)
|
||||
return form
|
||||
|
||||
def verify_current_factor(self, user, form):
|
||||
return self.recently_used_recovery_code(
|
||||
user
|
||||
) or super().verify_current_factor(user, form)
|
||||
|
||||
def apply_change(self, user, form):
|
||||
self.request.session.pop(RECOVERY_SIGN_IN, None)
|
||||
for device_type in DEVICE_TYPES.values():
|
||||
user_devices(user, device_type).filter(confirmed=False).delete()
|
||||
pending = TOTPDevice.objects.create(
|
||||
user=user, name=DEVICE_NAME, confirmed=False
|
||||
)
|
||||
self.request.session[FACTOR_SETUP] = {
|
||||
"device": pending.persistent_id,
|
||||
"expires": int(timezone.now().timestamp()) + 600,
|
||||
}
|
||||
return redirect("panel:account_authenticator_confirm")
|
||||
|
||||
|
||||
class ConfirmAuthenticatorView(SecurityFormView):
|
||||
heading = "Verify your authenticator app"
|
||||
form_class = ConfirmFactorForm
|
||||
|
||||
def pending_device(self, user):
|
||||
setup = self.request.session.get(FACTOR_SETUP, {})
|
||||
if setup.get("expires", 0) <= int(timezone.now().timestamp()):
|
||||
return None
|
||||
return device_for_user(user, setup.get("device"), confirmed=False)
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
if self.pending_device(request.user) is None:
|
||||
return redirect("panel:account_authenticator")
|
||||
return super().get(request, *args, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
pending = self.pending_device(self.request.user)
|
||||
context = authenticator_setup(pending) if pending else {}
|
||||
return super().get_context_data(**context, **kwargs)
|
||||
|
||||
@sensitive_variables("form")
|
||||
@transaction.atomic
|
||||
def form_valid(self, form):
|
||||
user = self.locked_user()
|
||||
pending = self.pending_device(user)
|
||||
if pending is None or not pending.verify_token(
|
||||
form.cleaned_data["code"]
|
||||
):
|
||||
form.add_error(
|
||||
"code", "The verification code is invalid or expired."
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
for device_type in DEVICE_TYPES.values():
|
||||
user_devices(user, device_type).filter(confirmed=True).delete()
|
||||
pending.confirmed = True
|
||||
pending.save(update_fields=["confirmed"])
|
||||
django_otp.login(self.request, pending)
|
||||
self.request.session.pop(FACTOR_SETUP, None)
|
||||
self.changed_access(user, Action.FACTOR)
|
||||
return self.show_recovery_codes(replace_recovery_codes(user))
|
||||
|
||||
|
||||
class ReplaceRecoveryCodesView(AuthorizedSecurityChange):
|
||||
heading = "Generate new recovery codes"
|
||||
instructions = "Generating new codes invalidates all your existing codes."
|
||||
|
||||
def validate_change(self, user, form):
|
||||
if confirmed_device(user) is None:
|
||||
form.add_error(None, "Set up a second factor first.")
|
||||
|
||||
def apply_change(self, user, form):
|
||||
self.changed_access(user, Action.RECOVERY)
|
||||
return self.show_recovery_codes(replace_recovery_codes(user))
|
||||
|
||||
|
||||
class SignOutOtherSessionsView(AuthorizedSecurityChange):
|
||||
heading = "Sign out other sessions"
|
||||
instructions = "This browser stays signed in."
|
||||
|
||||
def apply_change(self, user, form):
|
||||
self.changed_access(user, Action.SESSIONS)
|
||||
messages.success(self.request, "Your other sessions were signed out.")
|
||||
return redirect(self.success_url)
|
||||
@@ -8,6 +8,8 @@ from django.utils import timezone
|
||||
from coulobre.dns_node import AddressRecord
|
||||
from coulobre.web_node import WebSite
|
||||
|
||||
from .dns_defaults import zone_defaults
|
||||
from .dns_forms import normalize_record_rows
|
||||
from .dns_publication import queue_zone_snapshot
|
||||
from .mail_dns_setup import mail_dns_proposal
|
||||
from .models import (
|
||||
@@ -21,7 +23,9 @@ from .models import (
|
||||
from .php_settings import plan_php_settings
|
||||
|
||||
|
||||
def website_records(domain, *, www=True, wildcard=True):
|
||||
def website_records(domain, *, www=True, wildcard=True, addresses=None):
|
||||
if addresses is None:
|
||||
addresses = settings.HOSTING_PUBLIC_ADDRESSES
|
||||
owners = [domain]
|
||||
if www and len(domain) <= 249:
|
||||
owners.append(f"www.{domain}")
|
||||
@@ -30,7 +34,7 @@ def website_records(domain, *, www=True, wildcard=True):
|
||||
return [
|
||||
AddressRecord(owner, address)
|
||||
for owner in owners
|
||||
for address in settings.HOSTING_PUBLIC_ADDRESSES
|
||||
for address in addresses
|
||||
]
|
||||
|
||||
|
||||
@@ -65,11 +69,16 @@ def setup_new_account(account, options):
|
||||
wait_for_website=True,
|
||||
)
|
||||
if managed_dns:
|
||||
existing_managed_mail = (
|
||||
settings.LOCAL_MAILBOX_PROVISIONING
|
||||
and settings.MANAGE_MAIL_DNS
|
||||
and account.mail_domains.filter(domain=domain).exists()
|
||||
)
|
||||
create_default_dns_zone(
|
||||
account,
|
||||
www=add_www,
|
||||
wildcard=add_wildcard,
|
||||
managed_mail=options.get("setup_email"),
|
||||
managed_mail=options.get("setup_email") or existing_managed_mail,
|
||||
)
|
||||
if options.get("setup_email"):
|
||||
_, created = HostingMailDomain.objects.get_or_create(
|
||||
@@ -79,33 +88,71 @@ def setup_new_account(account, options):
|
||||
raise ValidationError("This domain already has email configured.")
|
||||
|
||||
|
||||
def create_default_dns_zone(account, *, www, wildcard, managed_mail):
|
||||
def default_dns_zone(account, *, www=None, wildcard=None, managed_mail=False):
|
||||
domain = account.primary_domain
|
||||
addresses = website_records(domain, www=www, wildcard=wildcard)
|
||||
defaults = zone_defaults()
|
||||
if not defaults.nameservers or not defaults.addresses:
|
||||
return None
|
||||
addresses = website_records(
|
||||
domain,
|
||||
www=defaults.include_www if www is None else www,
|
||||
wildcard=defaults.include_wildcard if wildcard is None else wildcard,
|
||||
addresses=defaults.addresses,
|
||||
)
|
||||
extra = normalize_record_rows(defaults.records, domain)
|
||||
mx = txt = ()
|
||||
if managed_mail:
|
||||
mail_addresses, mx, txt = mail_dns_proposal(domain, None)
|
||||
public_key = (
|
||||
account.mail_domains.filter(domain=domain)
|
||||
.values_list("dkim_record", flat=True)
|
||||
.first()
|
||||
if account.pk
|
||||
else None
|
||||
)
|
||||
mail_addresses, mx, txt = mail_dns_proposal(domain, public_key)
|
||||
addresses.extend(
|
||||
record
|
||||
for record in mail_addresses
|
||||
if record.name == domain or record.name.endswith(f".{domain}")
|
||||
)
|
||||
zone = HostingDnsZone(
|
||||
return HostingDnsZone(
|
||||
account=account,
|
||||
domain=domain,
|
||||
nameservers=list(settings.HOSTING_NAMESERVERS),
|
||||
responsible_name=f"hostmaster.{settings.HOSTING_NAMESERVERS[0]}",
|
||||
addresses=[asdict(record) for record in dict.fromkeys(addresses)],
|
||||
mx_records=[asdict(record) for record in mx],
|
||||
txt_records=[asdict(record) for record in txt],
|
||||
nameservers=list(defaults.nameservers),
|
||||
responsible_name=f"hostmaster.{defaults.nameservers[0]}",
|
||||
addresses=[
|
||||
asdict(record)
|
||||
for record in dict.fromkeys((*addresses, *extra["addresses"]))
|
||||
],
|
||||
mx_records=[
|
||||
asdict(record)
|
||||
for record in dict.fromkeys((*mx, *extra["mx_records"]))
|
||||
],
|
||||
txt_records=[
|
||||
asdict(record)
|
||||
for record in dict.fromkeys((*txt, *extra["txt_records"]))
|
||||
],
|
||||
extra_records=[asdict(record) for record in extra["extra_records"]],
|
||||
manage_mail_dns=bool(managed_mail),
|
||||
)
|
||||
|
||||
|
||||
def create_default_dns_zone(account, *, www, wildcard, managed_mail):
|
||||
try:
|
||||
zone = default_dns_zone(
|
||||
account, www=www, wildcard=wildcard, managed_mail=managed_mail
|
||||
)
|
||||
if zone is None:
|
||||
raise ValidationError(
|
||||
"Configure DNS defaults before creating a zone."
|
||||
)
|
||||
with transaction.atomic():
|
||||
zone.save()
|
||||
queue_zone_snapshot(zone)
|
||||
except IntegrityError:
|
||||
if not HostingDnsZone.objects.filter(domain=domain).exists():
|
||||
if not HostingDnsZone.objects.filter(
|
||||
domain=account.primary_domain
|
||||
).exists():
|
||||
raise
|
||||
raise ValidationError("This domain already has a DNS zone.") from None
|
||||
except ValueError as error:
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
from django.conf import settings
|
||||
|
||||
from .models import DnsZoneDefaults
|
||||
|
||||
|
||||
def zone_defaults():
|
||||
saved = DnsZoneDefaults.objects.filter(pk=1).first() or DnsZoneDefaults()
|
||||
saved.nameservers = saved.nameservers or settings.HOSTING_NAMESERVERS
|
||||
saved.addresses = saved.addresses or settings.HOSTING_PUBLIC_ADDRESSES
|
||||
return saved
|
||||
@@ -0,0 +1,121 @@
|
||||
from ipaddress import ip_address
|
||||
|
||||
from django import forms
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.mixins import UserPassesTestMixin
|
||||
from django.urls import reverse_lazy
|
||||
from django.views.generic import FormView
|
||||
|
||||
from coulobre.dns_node import dns_name
|
||||
|
||||
from .dns_defaults import zone_defaults
|
||||
from .dns_forms import normalize_record_rows
|
||||
from .models import DnsZoneDefaults
|
||||
|
||||
|
||||
class DnsDefaultsForm(forms.Form):
|
||||
nameservers = forms.CharField(
|
||||
required=False,
|
||||
help_text=(
|
||||
"Separate hostnames with spaces. "
|
||||
"Leave blank to use the installation settings."
|
||||
),
|
||||
)
|
||||
addresses = forms.CharField(
|
||||
label="Hosting IP addresses",
|
||||
required=False,
|
||||
help_text=(
|
||||
"Separate IPv4 or IPv6 addresses with spaces. "
|
||||
"Leave blank to use the installation settings."
|
||||
),
|
||||
)
|
||||
include_www = forms.BooleanField(label="Include www", required=False)
|
||||
include_wildcard = forms.BooleanField(
|
||||
label="Include a wildcard (*)", required=False
|
||||
)
|
||||
records = forms.CharField(
|
||||
label="Additional records",
|
||||
required=False,
|
||||
widget=forms.Textarea(attrs={"rows": 4}),
|
||||
help_text=(
|
||||
"Enter one record per line, for example _verification TXT abc123. "
|
||||
"Use @ for the new zone name. "
|
||||
"Enter fully qualified hostnames for record targets."
|
||||
),
|
||||
)
|
||||
|
||||
def clean_nameservers(self):
|
||||
try:
|
||||
return list(
|
||||
dict.fromkeys(
|
||||
dns_name(name)
|
||||
for name in self.cleaned_data["nameservers"].split()
|
||||
)
|
||||
)
|
||||
except ValueError as error:
|
||||
raise forms.ValidationError(str(error)) from error
|
||||
|
||||
def clean_addresses(self):
|
||||
try:
|
||||
addresses = list(
|
||||
dict.fromkeys(
|
||||
str(ip_address(address))
|
||||
for address in self.cleaned_data["addresses"].split()
|
||||
)
|
||||
)
|
||||
if any("%" in address for address in addresses):
|
||||
raise ValueError
|
||||
except ValueError as error:
|
||||
raise forms.ValidationError(
|
||||
"Enter IPv4 or IPv6 addresses without scope identifiers."
|
||||
) from error
|
||||
return addresses
|
||||
|
||||
def clean_records(self):
|
||||
rows = []
|
||||
for line in self.cleaned_data["records"].splitlines():
|
||||
parts = line.split(maxsplit=2)
|
||||
if not parts:
|
||||
continue
|
||||
if len(parts) != 3 or parts[0].endswith("."):
|
||||
raise forms.ValidationError(
|
||||
"Enter a relative name, a record type and a value."
|
||||
)
|
||||
name, kind, value = parts
|
||||
rows.append({"name": name, "type": kind.upper(), "value": value})
|
||||
normalize_record_rows(rows, "preview.example")
|
||||
return rows
|
||||
|
||||
|
||||
class DnsDefaultsView(UserPassesTestMixin, FormView):
|
||||
form_class = DnsDefaultsForm
|
||||
template_name = "hosting/dns_defaults_form.html"
|
||||
success_url = reverse_lazy("panel:dns_defaults")
|
||||
|
||||
def test_func(self):
|
||||
return self.request.user.is_superuser
|
||||
|
||||
def get_initial(self):
|
||||
saved = (
|
||||
DnsZoneDefaults.objects.filter(pk=1).first() or DnsZoneDefaults()
|
||||
)
|
||||
return {
|
||||
"nameservers": " ".join(saved.nameservers),
|
||||
"addresses": " ".join(saved.addresses),
|
||||
"include_www": saved.include_www,
|
||||
"include_wildcard": saved.include_wildcard,
|
||||
"records": "\n".join(
|
||||
f"{row['name']} {row['type']} {row['value']}"
|
||||
for row in saved.records
|
||||
),
|
||||
}
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(effective=zone_defaults(), **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
DnsZoneDefaults.objects.update_or_create(
|
||||
pk=1, defaults=form.cleaned_data
|
||||
)
|
||||
messages.success(self.request, "DNS defaults saved for new zones.")
|
||||
return super().form_valid(form)
|
||||
@@ -11,6 +11,120 @@ from coulobre.dns_node import (
|
||||
TxtRecord,
|
||||
)
|
||||
|
||||
RECORD_TYPES = ("A", "AAAA", "MX", "TXT", "CNAME", "SRV", "CAA")
|
||||
RECORD_FIELDS = ("addresses", "mx_records", "txt_records", "extra_records")
|
||||
|
||||
|
||||
def record_rows(spec):
|
||||
return [
|
||||
*(
|
||||
{
|
||||
"name": item.name,
|
||||
"type": item.record_type,
|
||||
"value": item.address,
|
||||
}
|
||||
for item in spec.addresses
|
||||
),
|
||||
*(
|
||||
{
|
||||
"name": item.name,
|
||||
"type": "MX",
|
||||
"value": f"{item.priority} {item.exchange}",
|
||||
}
|
||||
for item in spec.mx_records
|
||||
),
|
||||
*(
|
||||
{"name": item.name, "type": "TXT", "value": item.text}
|
||||
for item in spec.txt_records
|
||||
),
|
||||
*(
|
||||
{"name": item.name, "type": item.record_type, "value": item.value}
|
||||
for item in spec.extra_records
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def zone_record_rows(spec):
|
||||
return [
|
||||
*(
|
||||
{"name": spec.domain, "type": "NS", "value": host}
|
||||
for host in spec.nameservers
|
||||
),
|
||||
*record_rows(spec),
|
||||
]
|
||||
|
||||
|
||||
def zone_form_initial(zone):
|
||||
return {
|
||||
"serial": zone.serial,
|
||||
"manage_mail_dns": zone.manage_mail_dns,
|
||||
"delegate_dns": zone.delegate_dns,
|
||||
"nameservers": "\n".join(zone.nameservers),
|
||||
"responsible_name": zone.responsible_name,
|
||||
"addresses": "\n".join(
|
||||
f"{row['name']} {row['address']}" for row in zone.addresses
|
||||
),
|
||||
"mx_records": "\n".join(
|
||||
f"{row['name']} {row['priority']} {row['exchange']}"
|
||||
for row in zone.mx_records
|
||||
),
|
||||
"txt_records": "\n".join(
|
||||
format_txt_record(row) for row in zone.txt_records
|
||||
),
|
||||
"extra_records": "\n".join(
|
||||
f"{row['name']} {row['record_type']} {row['value']}"
|
||||
for row in zone.extra_records
|
||||
),
|
||||
"record_rows": json.dumps(record_rows(zone.spec)),
|
||||
}
|
||||
|
||||
|
||||
def parse_record_rows(raw):
|
||||
rows = json.loads(raw)
|
||||
if not isinstance(rows, list) or any(
|
||||
not isinstance(row, dict)
|
||||
or row.keys() != {"name", "type", "value"}
|
||||
or not all(isinstance(value, str) for value in row.values())
|
||||
for row in rows
|
||||
):
|
||||
raise ValueError("Enter records with a name, type and value.")
|
||||
return rows
|
||||
|
||||
|
||||
def normalize_record_rows(rows, domain):
|
||||
result = {field: [] for field in RECORD_FIELDS}
|
||||
for number, row in enumerate(rows, 1):
|
||||
name, kind = row["name"].strip(), row["type"]
|
||||
if name == "@":
|
||||
name = domain
|
||||
elif name.endswith("."):
|
||||
name = name[:-1]
|
||||
elif name != domain and not name.endswith(f".{domain}"):
|
||||
name = f"{name}.{domain}" if name else ""
|
||||
value = row["value"]
|
||||
try:
|
||||
if kind in {"A", "AAAA"}:
|
||||
record = AddressRecord(name, value.strip())
|
||||
if record.record_type != kind:
|
||||
raise ValueError(
|
||||
f"Enter an IP address for a {kind} record."
|
||||
)
|
||||
result["addresses"].append(record)
|
||||
elif kind == "MX":
|
||||
priority, target = value.split()
|
||||
result["mx_records"].append(
|
||||
MxRecord(name, int(priority), target)
|
||||
)
|
||||
elif kind == "TXT":
|
||||
result["txt_records"].append(TxtRecord(name, value))
|
||||
elif kind in {"CNAME", "SRV", "CAA"}:
|
||||
result["extra_records"].append(ExtraRecord(name, kind, value))
|
||||
else:
|
||||
raise ValueError("Select a supported record type.")
|
||||
except ValueError as error:
|
||||
raise forms.ValidationError(f"Record {number}. {error}") from error
|
||||
return {key: tuple(value) for key, value in result.items()}
|
||||
|
||||
|
||||
def format_txt_record(record):
|
||||
text = record["text"]
|
||||
@@ -25,6 +139,12 @@ def format_txt_record(record):
|
||||
|
||||
|
||||
class DnsZoneForm(forms.Form):
|
||||
record_rows = forms.CharField(
|
||||
required=False,
|
||||
max_length=524288,
|
||||
widget=forms.HiddenInput,
|
||||
strip=False,
|
||||
)
|
||||
nameservers = forms.CharField(
|
||||
widget=forms.Textarea(attrs={"rows": 3, "spellcheck": "false"}),
|
||||
help_text="Enter one hostname per line. The first is the SOA primary.",
|
||||
@@ -85,10 +205,26 @@ class DnsZoneForm(forms.Form):
|
||||
required=False,
|
||||
)
|
||||
|
||||
def __init__(self, *args, domain, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
def __init__(self, data=None, *args, domain, **kwargs):
|
||||
initial = dict(kwargs.get("initial") or {})
|
||||
self.initial_rows = initial.pop("record_rows", "[]")
|
||||
kwargs["initial"] = initial
|
||||
if data and data.get("record_rows"):
|
||||
data = data.copy()
|
||||
for field in RECORD_FIELDS:
|
||||
data[field] = ""
|
||||
super().__init__(data, *args, **kwargs)
|
||||
self.domain = domain
|
||||
|
||||
@property
|
||||
def editor_rows(self):
|
||||
try:
|
||||
return parse_record_rows(
|
||||
self["record_rows"].value() or self.initial_rows
|
||||
)
|
||||
except (ValueError, RecursionError):
|
||||
return []
|
||||
|
||||
def clean_addresses(self):
|
||||
records = []
|
||||
for number, line in enumerate(
|
||||
@@ -172,6 +308,16 @@ class DnsZoneForm(forms.Form):
|
||||
data = super().clean()
|
||||
if self.errors:
|
||||
return data
|
||||
rows = data.pop("record_rows", "")
|
||||
if rows:
|
||||
try:
|
||||
data.update(
|
||||
normalize_record_rows(parse_record_rows(rows), self.domain)
|
||||
)
|
||||
except (ValueError, RecursionError) as error:
|
||||
raise forms.ValidationError(
|
||||
"Enter valid DNS records."
|
||||
) from error
|
||||
try:
|
||||
spec = DnsZone(
|
||||
domain=self.domain,
|
||||
|
||||
@@ -7,6 +7,7 @@ from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
from .access import OperatorOnlyMixin
|
||||
from .dns_defaults import zone_defaults
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
@@ -22,6 +23,7 @@ class InstallationView(
|
||||
except PackageNotFoundError:
|
||||
installed_version = "Unavailable"
|
||||
|
||||
dns_defaults = zone_defaults()
|
||||
features = (
|
||||
("Local website provisioning", settings.LOCAL_WEB_ACTIVATION),
|
||||
("Managed website certificates", settings.LOCAL_WEB_HTTPS),
|
||||
@@ -31,8 +33,8 @@ class InstallationView(
|
||||
(
|
||||
"Default managed DNS zones for new accounts",
|
||||
settings.LOCAL_DNS_PUBLISHING
|
||||
and settings.HOSTING_NAMESERVERS
|
||||
and settings.HOSTING_PUBLIC_ADDRESSES,
|
||||
and dns_defaults.nameservers
|
||||
and dns_defaults.addresses,
|
||||
),
|
||||
(
|
||||
"Local mailbox provisioning",
|
||||
|
||||
@@ -24,6 +24,7 @@ from django.views.generic import FormView
|
||||
from kombu.exceptions import OperationalError
|
||||
|
||||
from .access import customer_for_user, is_tenant, reseller_for_user
|
||||
from .account_setup import website_records
|
||||
from .models import Customer, HostingAccount, PanelInvitation, Reseller
|
||||
from .panel_factors import lock_user
|
||||
from .password_reset import reset_enabled
|
||||
@@ -168,6 +169,11 @@ def deliver_invitation(invitation_id, revision):
|
||||
.order_by("pk")
|
||||
.first()
|
||||
)
|
||||
zone = (
|
||||
account.dns_zones.filter(domain=account.primary_domain).first()
|
||||
if account
|
||||
else None
|
||||
)
|
||||
message = render_to_string(
|
||||
"hosting/panel_invitation.txt",
|
||||
{
|
||||
@@ -175,6 +181,20 @@ def deliver_invitation(invitation_id, revision):
|
||||
"setup_url": origin + path,
|
||||
"panel_url": origin + "/",
|
||||
"account": account,
|
||||
"nameservers": zone.nameservers if zone else (),
|
||||
"website_records": (
|
||||
website_records(account.primary_domain, wildcard=False)
|
||||
if account and zone is None
|
||||
else ()
|
||||
),
|
||||
"imap_host": settings.MAIL_IMAP_HOST,
|
||||
"submission_host": settings.MAIL_SUBMISSION_HOST,
|
||||
"mail_configured": bool(
|
||||
account
|
||||
and account.mail_domains.filter(
|
||||
domain=account.primary_domain
|
||||
).exists()
|
||||
),
|
||||
},
|
||||
)
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-22 21:38
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0055_hosting_setup_defaults"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="DnsZoneDefaults",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("nameservers", models.JSONField(blank=True, default=list)),
|
||||
("addresses", models.JSONField(blank=True, default=list)),
|
||||
("include_www", models.BooleanField(default=True)),
|
||||
("include_wildcard", models.BooleanField(default=True)),
|
||||
("records", models.JSONField(blank=True, default=list)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-22 23:08
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0056_dns_zone_defaults"),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="PanelAccountSecurity",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("session_version", models.PositiveBigIntegerField(default=0)),
|
||||
(
|
||||
"user",
|
||||
models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="PanelEmailChange",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("email", models.EmailField(max_length=254)),
|
||||
("digest", models.CharField(max_length=64)),
|
||||
("session_digest", models.CharField(max_length=64)),
|
||||
("expires_at", models.DateTimeField()),
|
||||
(
|
||||
"user",
|
||||
models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="PanelSecurityEvent",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("username", models.CharField(max_length=150)),
|
||||
(
|
||||
"action",
|
||||
models.CharField(
|
||||
choices=[
|
||||
("password", "Password changed"),
|
||||
("email", "Email address changed"),
|
||||
("factor", "Authenticator updated"),
|
||||
("recovery", "Recovery codes replaced"),
|
||||
("reset", "Operator-issued factor recovery"),
|
||||
("sessions", "Other sessions signed out"),
|
||||
],
|
||||
max_length=12,
|
||||
),
|
||||
),
|
||||
("created_at", models.DateTimeField(auto_now_add=True)),
|
||||
(
|
||||
"user",
|
||||
models.ForeignKey(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"indexes": [
|
||||
models.Index(
|
||||
fields=["user", "-id"],
|
||||
name="hosting_pan_user_id_9e9e3e_idx",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -607,6 +607,14 @@ class DirectAdminImport(models.Model):
|
||||
fingerprint = models.CharField(max_length=64, unique=True)
|
||||
|
||||
|
||||
class DnsZoneDefaults(models.Model):
|
||||
nameservers = models.JSONField(default=list, blank=True)
|
||||
addresses = models.JSONField(default=list, blank=True)
|
||||
include_www = models.BooleanField(default=True)
|
||||
include_wildcard = models.BooleanField(default=True)
|
||||
records = models.JSONField(default=list, blank=True)
|
||||
|
||||
|
||||
class HostingDnsZone(models.Model):
|
||||
account = models.ForeignKey(
|
||||
HostingAccount, on_delete=models.PROTECT, related_name="dns_zones"
|
||||
@@ -1346,3 +1354,40 @@ class PanelRecoveryCode(models.Model):
|
||||
name="hosting_unique_panel_recovery_code",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class PanelAccountSecurity(models.Model):
|
||||
user = models.OneToOneField(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
|
||||
)
|
||||
session_version = models.PositiveBigIntegerField(default=0)
|
||||
|
||||
|
||||
class PanelEmailChange(models.Model):
|
||||
user = models.OneToOneField(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
|
||||
)
|
||||
email = models.EmailField()
|
||||
digest = models.CharField(max_length=64)
|
||||
session_digest = models.CharField(max_length=64)
|
||||
expires_at = models.DateTimeField()
|
||||
|
||||
|
||||
class PanelSecurityEvent(models.Model):
|
||||
class Action(models.TextChoices):
|
||||
PASSWORD = "password", "Password changed"
|
||||
EMAIL = "email", "Email address changed"
|
||||
FACTOR = "factor", "Authenticator updated"
|
||||
RECOVERY = "recovery", "Recovery codes replaced"
|
||||
RESET = "reset", "Operator-issued factor recovery"
|
||||
SESSIONS = "sessions", "Other sessions signed out"
|
||||
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
|
||||
)
|
||||
username = models.CharField(max_length=150)
|
||||
action = models.CharField(max_length=12, choices=Action.choices)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
indexes = [models.Index(fields=["user", "-id"])]
|
||||
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
import socket
|
||||
from importlib.metadata import version
|
||||
|
||||
from django.views.decorators.debug import sensitive_variables
|
||||
|
||||
@@ -11,8 +12,10 @@ from coulobre.account_restore_request import (
|
||||
RESTORE_SOCKET,
|
||||
RESTORE_TIMEOUT_SECONDS,
|
||||
)
|
||||
from coulobre.linked_updates import ROLES, UNIT_DIR, read_probe
|
||||
from coulobre.mail_dns import dkim_key
|
||||
from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest
|
||||
from coulobre.node_probe import PROBE_BYTES, parse_status_probe
|
||||
from coulobre.php_pool_settings import PhpPoolSettings
|
||||
from coulobre.php_runtime import validate_php_version
|
||||
from coulobre.web_node import (
|
||||
@@ -250,6 +253,7 @@ def encode_manifest(manifest):
|
||||
def apply_on_local_node(
|
||||
spec, socket_path, node, resource, *, identity=None, timeout=195
|
||||
):
|
||||
require_matching_receiver(socket_path)
|
||||
manifest = spec.manifest()
|
||||
expected = manifest if identity is None else identity
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
|
||||
@@ -284,3 +288,23 @@ def apply_on_local_node(
|
||||
if state == "failed" and isinstance(problem, str) and problem.strip():
|
||||
raise ValueError(problem.strip()[:2000])
|
||||
raise NodeReplyError(invalid_response)
|
||||
|
||||
|
||||
def require_matching_receiver(socket_path):
|
||||
for role in ROLES:
|
||||
unit = f"coulobre-{role}-apply"
|
||||
if str(socket_path) != f"/run/{unit}.sock":
|
||||
continue
|
||||
if not (UNIT_DIR / f"{unit}@.service.d/remote.conf").exists():
|
||||
return
|
||||
try:
|
||||
report = parse_status_probe(read_probe(role, PROBE_BYTES), role)
|
||||
if report["state"] == "configured" and report[
|
||||
"release"
|
||||
] == version("coulobre-panel"):
|
||||
return
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
raise NodeReplyError(
|
||||
f"The linked {role} receiver is not ready for this release."
|
||||
)
|
||||
@@ -17,7 +17,17 @@ from django_otp.models import Device
|
||||
from django_otp.plugins.otp_email.models import EmailDevice
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
|
||||
from .models import PanelFactorEnrollment, PanelRecoveryCode
|
||||
from .models import (
|
||||
PanelFactorEnrollment,
|
||||
PanelRecoveryCode,
|
||||
PanelSecurityEvent,
|
||||
)
|
||||
from .panel_sessions import (
|
||||
SESSION_VERSION,
|
||||
record_security_event,
|
||||
revoke_other_sessions,
|
||||
session_version,
|
||||
)
|
||||
|
||||
DEVICE_NAME = "Coulobre Panel"
|
||||
DEVICE_TYPES = {"authenticator": TOTPDevice, "email": EmailDevice}
|
||||
@@ -25,6 +35,7 @@ CHALLENGE_SESSION = "coulobre_panel_challenge"
|
||||
SETUP_SESSION = "coulobre_panel_factor_device"
|
||||
SETUP_EXPIRES = "coulobre_panel_factor_expiry"
|
||||
SETUP_DESTINATION = "coulobre_panel_factor_destination"
|
||||
RECOVERY_SIGN_IN = "coulobre_panel_recovery_sign_in"
|
||||
CHALLENGE_SECONDS = 300
|
||||
ENROLLMENT_MINUTES = 20
|
||||
|
||||
@@ -39,7 +50,12 @@ def privileged_user(user):
|
||||
|
||||
|
||||
def requires_panel_factor(user):
|
||||
return settings.REQUIRE_PRIVILEGED_MFA and privileged_user(user)
|
||||
return user.is_authenticated and (
|
||||
settings.REQUIRE_PRIVILEGED_MFA
|
||||
and privileged_user(user)
|
||||
or confirmed_device(user) is not None
|
||||
or recovery_required(user)
|
||||
)
|
||||
|
||||
|
||||
def lock_user(user_id):
|
||||
@@ -111,6 +127,8 @@ def issue_recovery_enrollment(user):
|
||||
+ timedelta(minutes=ENROLLMENT_MINUTES),
|
||||
},
|
||||
)
|
||||
revoke_other_sessions(user)
|
||||
record_security_event(user, PanelSecurityEvent.Action.RESET)
|
||||
return code
|
||||
|
||||
|
||||
@@ -162,10 +180,12 @@ def start_challenge(request, user, destination):
|
||||
request.session.cycle_key()
|
||||
rotate_token(request)
|
||||
request.session.pop(SETUP_SESSION, None)
|
||||
request.session.pop(RECOVERY_SIGN_IN, None)
|
||||
request.session[CHALLENGE_SESSION] = {
|
||||
"user": user.pk,
|
||||
"backend": user.backend,
|
||||
"auth_hash": user.get_session_auth_hash(),
|
||||
"session_version": session_version(user),
|
||||
"expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS,
|
||||
"next": destination,
|
||||
}
|
||||
@@ -184,6 +204,7 @@ def pending_user(request):
|
||||
data["expires"] > int(timezone.now().timestamp())
|
||||
and user is not None
|
||||
and requires_panel_factor(user)
|
||||
and data.get("session_version", 0) == session_version(user)
|
||||
and constant_time_compare(
|
||||
data["auth_hash"], user.get_session_auth_hash()
|
||||
)
|
||||
@@ -204,6 +225,7 @@ def complete_challenge(request, user, device):
|
||||
else:
|
||||
data = request.session.pop(CHALLENGE_SESSION)
|
||||
login(request, user, backend=data["backend"])
|
||||
request.session[SESSION_VERSION] = data.get("session_version", 0)
|
||||
destination = data["next"]
|
||||
django_otp.login(request, device)
|
||||
return destination
|
||||
@@ -223,6 +245,12 @@ def confirm_enrollment(user, device_id, token):
|
||||
device.confirmed = True
|
||||
device.save(update_fields=["confirmed"])
|
||||
PanelFactorEnrollment.objects.filter(user=user).delete()
|
||||
return device, replace_recovery_codes(user)
|
||||
|
||||
|
||||
@sensitive_variables("codes")
|
||||
def replace_recovery_codes(user):
|
||||
PanelRecoveryCode.objects.filter(user=user).delete()
|
||||
codes = [secrets.token_hex(10) for _ in range(10)]
|
||||
PanelRecoveryCode.objects.bulk_create(
|
||||
[
|
||||
@@ -232,7 +260,7 @@ def confirm_enrollment(user, device_id, token):
|
||||
for code in codes
|
||||
]
|
||||
)
|
||||
return device, codes
|
||||
return codes
|
||||
|
||||
|
||||
@sensitive_variables("code")
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
from django.contrib.auth import logout
|
||||
from django.contrib.auth.views import redirect_to_login
|
||||
from django.db.models import F
|
||||
from django.middleware.csrf import rotate_token
|
||||
|
||||
from .models import (
|
||||
PanelAccountSecurity,
|
||||
PanelEmailChange,
|
||||
PanelSecurityEvent,
|
||||
PhpMyAdminGrant,
|
||||
RoundcubeGrant,
|
||||
)
|
||||
|
||||
SESSION_VERSION = "coulobre_account_session_version"
|
||||
|
||||
|
||||
def session_version(user):
|
||||
return (
|
||||
PanelAccountSecurity.objects.filter(user=user)
|
||||
.values_list("session_version", flat=True)
|
||||
.first()
|
||||
or 0
|
||||
)
|
||||
|
||||
|
||||
def session_is_current(request, user):
|
||||
return request.session.get(SESSION_VERSION, 0) == session_version(user)
|
||||
|
||||
|
||||
def revoke_other_sessions(user):
|
||||
state, _ = PanelAccountSecurity.objects.get_or_create(user=user)
|
||||
PanelAccountSecurity.objects.filter(pk=state.pk).update(
|
||||
session_version=F("session_version") + 1
|
||||
)
|
||||
PanelEmailChange.objects.filter(user=user).delete()
|
||||
for grants in (PhpMyAdminGrant, RoundcubeGrant):
|
||||
grants.objects.filter(actor=user, redeemed_at__isnull=True).delete()
|
||||
return session_version(user)
|
||||
|
||||
|
||||
def preserve_session(request, new_version):
|
||||
request.session.cycle_key()
|
||||
request.session[SESSION_VERSION] = new_version
|
||||
rotate_token(request)
|
||||
|
||||
|
||||
def record_security_event(user, action):
|
||||
PanelSecurityEvent.objects.create(
|
||||
user=user, username=user.get_username(), action=action
|
||||
)
|
||||
|
||||
|
||||
class PanelSessionMiddleware:
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
return self.get_response(request)
|
||||
|
||||
def process_view(self, request, view_func, view_args, view_kwargs):
|
||||
if request.user.is_authenticated and not session_is_current(
|
||||
request, request.user
|
||||
):
|
||||
logout(request)
|
||||
if request.resolver_match.view_name == "panel:logout":
|
||||
return None
|
||||
destination = (
|
||||
request.get_full_path()
|
||||
if request.method in {"GET", "HEAD"}
|
||||
else "/"
|
||||
)
|
||||
return redirect_to_login(destination)
|
||||
return None
|
||||
@@ -85,6 +85,10 @@ def request_reseller_resource(access, account_id, create, values):
|
||||
)
|
||||
resource = create(account.pk, **values)
|
||||
record_resource_event(reseller, account, Action.RESOURCE_REQUEST, resource)
|
||||
if getattr(resource, "provisioning", None) is not None:
|
||||
record_resource_event(
|
||||
reseller, account, Action.RESOURCE_PROVISION, resource
|
||||
)
|
||||
return resource
|
||||
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@ def lock_hosting_account(account_id, customer_id):
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def create_database_request(account_id, suffix, *, customer_id=None):
|
||||
def create_database_request(
|
||||
account_id, suffix, *, customer_id=None, auto_provision=False
|
||||
):
|
||||
account = lock_hosting_account(account_id, customer_id)
|
||||
require_open_account(account)
|
||||
databases = account.databases
|
||||
@@ -45,11 +47,17 @@ def create_database_request(account_id, suffix, *, customer_id=None):
|
||||
raise ValidationError(
|
||||
"This hosting account has reached its database limit."
|
||||
)
|
||||
return databases.create(suffix=suffix)
|
||||
database = databases.create(suffix=suffix)
|
||||
if auto_provision:
|
||||
require_active_services(account)
|
||||
DatabaseProvisioning.objects.queue(database=database)
|
||||
return database
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def create_mailbox_request(account_id, local_part, *, customer_id=None):
|
||||
def create_mailbox_request(
|
||||
account_id, local_part, *, customer_id=None, auto_provision=False
|
||||
):
|
||||
account = lock_hosting_account(account_id, customer_id)
|
||||
require_open_account(account)
|
||||
try:
|
||||
@@ -83,10 +91,14 @@ def create_mailbox_request(account_id, local_part, *, customer_id=None):
|
||||
raise ValidationError(
|
||||
"This hosting account has reached its mailbox limit."
|
||||
)
|
||||
return mail_domain.mailboxes.create(
|
||||
mailbox = mail_domain.mailboxes.create(
|
||||
local_part=spec.local_part,
|
||||
quota_mib=plan.mailbox_quota_mib if plan is not None else None,
|
||||
)
|
||||
if auto_provision:
|
||||
require_active_services(account)
|
||||
MailboxProvisioning.objects.queue(mailbox=mailbox)
|
||||
return mailbox
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 import timezone
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.debug import (
|
||||
@@ -17,6 +18,8 @@ from django_otp.plugins.otp_email.models import EmailDevice
|
||||
from qrcode.image.svg import SvgPathFillImage
|
||||
|
||||
from .panel_factors import (
|
||||
CHALLENGE_SECONDS,
|
||||
RECOVERY_SIGN_IN,
|
||||
SETUP_SESSION,
|
||||
begin_enrollment,
|
||||
complete_challenge,
|
||||
@@ -33,10 +36,24 @@ from .panel_factors import (
|
||||
start_initial_setup,
|
||||
verify_factor,
|
||||
)
|
||||
from .panel_sessions import SESSION_VERSION, session_version
|
||||
from .password_reset import reset_enabled
|
||||
from .sign_in_limits import limit_attempt
|
||||
|
||||
|
||||
@sensitive_variables("configuration_url")
|
||||
def authenticator_setup(device):
|
||||
configuration_url = device.config_url
|
||||
qr = qrcode.make(
|
||||
configuration_url, image_factory=SvgPathFillImage
|
||||
).to_string(encoding="utf-8")
|
||||
return {
|
||||
"setup_key": base64.b32encode(device.bin_key).decode(),
|
||||
"configuration_url": configuration_url,
|
||||
"qr_image": base64.b64encode(qr).decode("ascii"),
|
||||
}
|
||||
|
||||
|
||||
class PrivilegedFactorMiddleware:
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
@@ -88,13 +105,17 @@ class PanelLoginView(LoginView):
|
||||
|
||||
def form_valid(self, form):
|
||||
user = form.get_user()
|
||||
current_version = session_version(user)
|
||||
if not requires_panel_factor(user):
|
||||
return super().form_valid(form)
|
||||
response = super().form_valid(form)
|
||||
self.request.session[SESSION_VERSION] = current_version
|
||||
return response
|
||||
destination = self.get_success_url()
|
||||
if confirmed_device(user) or recovery_required(user):
|
||||
start_challenge(self.request, user, destination)
|
||||
return redirect("panel:factor_verify")
|
||||
super().form_valid(form)
|
||||
self.request.session[SESSION_VERSION] = current_version
|
||||
start_initial_setup(self.request, destination)
|
||||
if not email_factor_available(user):
|
||||
device = begin_enrollment(user, "authenticator")
|
||||
@@ -234,12 +255,19 @@ class VerifyFactorView(FactorView):
|
||||
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"])
|
||||
code = form.cleaned_data["code"]
|
||||
verified = verify_factor(self.user, code)
|
||||
if verified is None:
|
||||
return self.rejected(
|
||||
form, "Invalid or unavailable code. Try again."
|
||||
)
|
||||
return redirect(complete_challenge(self.request, self.user, verified))
|
||||
destination = complete_challenge(self.request, self.user, verified)
|
||||
if len(code) == 20:
|
||||
self.request.session[RECOVERY_SIGN_IN] = {
|
||||
"device": verified.persistent_id,
|
||||
"expires": int(timezone.now().timestamp()) + CHALLENGE_SECONDS,
|
||||
}
|
||||
return redirect(destination)
|
||||
|
||||
|
||||
class EnrollFactorView(FactorView):
|
||||
@@ -309,15 +337,7 @@ class ConfirmFactorView(FactorView):
|
||||
if isinstance(device, EmailDevice):
|
||||
context["email_factor"] = True
|
||||
elif device:
|
||||
configuration_url = device.config_url
|
||||
qr = qrcode.make(
|
||||
configuration_url, image_factory=SvgPathFillImage
|
||||
).to_string(encoding="utf-8")
|
||||
context = {
|
||||
"setup_key": base64.b32encode(device.bin_key).decode(),
|
||||
"configuration_url": configuration_url,
|
||||
"qr_image": base64.b64encode(qr).decode("ascii"),
|
||||
}
|
||||
context = authenticator_setup(device)
|
||||
return super().get_context_data(**context, **kwargs)
|
||||
|
||||
@sensitive_variables("codes")
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-12 -12 312 312">
|
||||
<style>
|
||||
path { fill: #15392f; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
path { fill: #c7e8ca; }
|
||||
}
|
||||
</style>
|
||||
<path d="M0 199 V132 C0 104 27 89 61 78 L217 36
|
||||
C245 28 263 19 263 0 C272 1 279 11 279 21 V73
|
||||
C279 91 267 101 244 108 L48 169 C24 177 8 186 0 199 Z"/>
|
||||
<path d="M208 124 C246 136 288 151 288 178 V239
|
||||
C277 221 246 211 208 202 Z"/>
|
||||
<path d="M46 175 L218 211 C259 220 280 233 286 246
|
||||
C294 266 269 288 228 288 C217 288 207 287 195 284
|
||||
L45 249 C16 242 0 227 0 212 C0 197 18 185 46 175 Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 684 B |
@@ -0,0 +1,79 @@
|
||||
const editor = document.querySelector("[data-dns-editor]");
|
||||
const rows = editor.querySelector("[data-dns-rows]");
|
||||
const add = editor.querySelector("[data-add-dns-record]");
|
||||
const form = editor.closest("form");
|
||||
const data = form.querySelector("[name=record_rows]");
|
||||
const valueLabels = {
|
||||
A: "IPv4 address", AAAA: "IPv6 address", CNAME: "Target hostname",
|
||||
MX: "Mail server hostname", TXT: "Text", SRV: "Priority, weight, port and target",
|
||||
CAA: "Flags, tag and value",
|
||||
};
|
||||
|
||||
function numberRows() {
|
||||
Array.from(rows.children).forEach((row, index) => {
|
||||
row.querySelector("legend").textContent = `Record ${index + 1}`;
|
||||
});
|
||||
}
|
||||
|
||||
function appendRecord(record) {
|
||||
const row = editor.querySelector("template").content.firstElementChild.cloneNode(true);
|
||||
const name = row.querySelector("[data-record-name]");
|
||||
const type = row.querySelector("[data-record-type]");
|
||||
const value = row.querySelector("[data-record-value]");
|
||||
const priority = row.querySelector("[data-record-priority]");
|
||||
const priorityLabel = row.querySelector("[data-priority-label]");
|
||||
const valueLabel = row.querySelector("[data-record-value-label]");
|
||||
name.value = record.name;
|
||||
type.value = record.type;
|
||||
value.value = record.value;
|
||||
if (record.type === "MX") {
|
||||
const [mxPriority, target] = record.value.split(/\s+/, 2);
|
||||
priority.value = mxPriority;
|
||||
value.value = target || "";
|
||||
}
|
||||
row.dataset.initialValue = value.value;
|
||||
row.dataset.initialRecord = record.type === "TXT" ? record.value : value.value;
|
||||
const updateFields = () => {
|
||||
const usesPriority = type.value === "MX";
|
||||
priorityLabel.hidden = !usesPriority;
|
||||
priority.required = usesPriority;
|
||||
priority.disabled = !usesPriority;
|
||||
value.required = type.value !== "TXT";
|
||||
valueLabel.textContent = valueLabels[type.value];
|
||||
};
|
||||
type.addEventListener("change", updateFields);
|
||||
row.querySelector("[data-remove-record]").addEventListener("click", () => {
|
||||
const nextFocus = row.nextElementSibling?.querySelector("input") || add;
|
||||
row.remove();
|
||||
numberRows();
|
||||
nextFocus.focus();
|
||||
});
|
||||
updateFields();
|
||||
rows.append(row);
|
||||
return name;
|
||||
}
|
||||
|
||||
for (const record of JSON.parse(document.getElementById("dns-record-data").textContent)) {
|
||||
appendRecord(record);
|
||||
}
|
||||
numberRows();
|
||||
editor.hidden = false;
|
||||
form.querySelector("[data-dns-text-fields]").hidden = true;
|
||||
form.querySelectorAll("[data-dns-text-fields] textarea").forEach((field) => {
|
||||
field.disabled = true;
|
||||
});
|
||||
add.addEventListener("click", () => {
|
||||
const field = appendRecord({name: "", type: "A", value: ""});
|
||||
numberRows();
|
||||
field.focus();
|
||||
});
|
||||
form.addEventListener("submit", () => {
|
||||
data.value = JSON.stringify(Array.from(rows.children, (row) => {
|
||||
const name = row.querySelector("[data-record-name]").value;
|
||||
const type = row.querySelector("[data-record-type]").value;
|
||||
const value = row.querySelector("[data-record-value]").value;
|
||||
const priority = row.querySelector("[data-record-priority]").value;
|
||||
const text = value === row.dataset.initialValue ? row.dataset.initialRecord : value;
|
||||
return {name, type, value: type === "MX" ? `${priority} ${value}` : type === "TXT" ? text : value};
|
||||
}));
|
||||
});
|
||||
@@ -168,9 +168,21 @@ button, input, select, textarea {
|
||||
place-items: center;
|
||||
border-radius: 0.55rem;
|
||||
background: var(--brand-bg);
|
||||
color: var(--brand-ink);
|
||||
font-size: 1.12rem;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.brand-mark::before {
|
||||
content: "";
|
||||
width: 66%;
|
||||
height: 66%;
|
||||
background: var(--brand-ink);
|
||||
mask: url("coulobre-mark.svg") center / contain no-repeat;
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
.brand-mark::before {
|
||||
forced-color-adjust: none;
|
||||
background: CanvasText;
|
||||
}
|
||||
}
|
||||
|
||||
.brand-product {
|
||||
@@ -314,6 +326,11 @@ button, input, select, textarea {
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.sidebar-account a {
|
||||
color: inherit;
|
||||
text-underline-offset: 0.2em;
|
||||
}
|
||||
|
||||
.sidebar-account button {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
@@ -778,6 +795,36 @@ dd {
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.dns-surface {
|
||||
margin-inline: 0;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.dns-editor-rows {
|
||||
display: grid;
|
||||
gap: 0.6rem;
|
||||
margin-block: 0.75rem;
|
||||
}
|
||||
|
||||
.dns-edit-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: end;
|
||||
gap: 0.5rem;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0.65rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dns-edit-row label { flex: 1 1 8rem; margin: 0; }
|
||||
.dns-edit-row label[hidden] { display: none; }
|
||||
.dns-edit-row label:has(select, input[type="number"]) { flex: 0 1 6rem; }
|
||||
.dns-edit-row label:has(textarea) { flex: 2 1 12rem; }
|
||||
.dns-edit-row textarea { display: block; min-height: 2.45rem; resize: vertical; }
|
||||
.dns-record-table code { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
|
||||
.reseller-editor fieldset {
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
|
||||
@@ -49,6 +49,12 @@
|
||||
{% if can_change_hosting_services or service_change or can_retire_account or is_operator and perms.hosting.change_hostingaccount %}<a href="#account-management">Account management</a>{% endif %}
|
||||
</nav>
|
||||
<section class="surface account-overview account-content" id="overview" data-account-section tabindex="-1" aria-label="Account overview">
|
||||
{% if offer_account_setup %}
|
||||
<div class="section-heading">
|
||||
<p>Some services still need setup.</p>
|
||||
<a class="button primary" href="{% url 'panel:account_setup' account.pk %}">Complete hosting setup</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
<dl class="account-readiness">
|
||||
{% if show_website %}<div><dt>Website</dt><dd><a href="#websites">{{ website_readiness }}</a></dd></div>{% endif %}
|
||||
{% if show_website %}<div><dt>HTTPS</dt><dd><a href="#websites">{{ https_readiness }}</a></dd></div>{% endif %}
|
||||
@@ -127,7 +133,7 @@
|
||||
<section id="databases" data-account-section tabindex="-1" class="surface" aria-labelledby="databases-heading">
|
||||
<header class="section-heading">
|
||||
<div>
|
||||
<h2 id="databases-heading" tabindex="-1">MariaDB database requests</h2>
|
||||
<h2 id="databases-heading" tabindex="-1">MariaDB databases</h2>
|
||||
{% if is_tenant or perms.hosting.view_hostingplan %}
|
||||
{% if account.hosting_plan and account.hosting_plan.database_limit is not None %}
|
||||
<p class="heading-meta">{{ databases|length }} of {{ account.hosting_plan.database_limit }} databases requested</p>
|
||||
@@ -135,51 +141,50 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
{% 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>
|
||||
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">{% if automatic_database_provisioning %}Add{% else %}Request{% endif %} database</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if databases %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Database</th>{% if is_operator or manage_database_provisioning %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
|
||||
<thead><tr><th scope="col">Database</th><th scope="col">Status and actions</th></tr></thead>
|
||||
<tbody>
|
||||
{% for database in databases %}
|
||||
<tr>
|
||||
<td class="domain">
|
||||
{{ database }}
|
||||
{% if show_database_credentials %}
|
||||
<div><a class="record-link" href="{% url 'panel:database_credentials' database.pk %}" aria-label="Connection details for {{ database }}">Connection details</a></div>
|
||||
{% endif %}
|
||||
{% if show_phpmyadmin %}
|
||||
<form method="post" action="{% url 'panel:phpmyadmin_launch' database.pk %}">
|
||||
{% csrf_token %}
|
||||
<button class="button secondary" type="submit">Open phpMyAdmin</button>
|
||||
</form>
|
||||
<th scope="row" class="domain">{{ database }}</th>
|
||||
<td>
|
||||
<div class="table-actions">
|
||||
{% 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" %}
|
||||
{% else %}
|
||||
{% include "hosting/resource_provisioning.html" with provisioning=database.provisioning enabled=False %}
|
||||
{% endif %}
|
||||
{% if not database.provisioning %}<span class="status pending">Requested</span>{% endif %}
|
||||
{% if show_database_credentials %}
|
||||
<a class="record-link" href="{% url 'panel:database_credentials' database.pk %}" aria-label="Connection details for {{ database }}">Connection details</a>
|
||||
{% endif %}
|
||||
{% if show_phpmyadmin %}
|
||||
<form method="post" action="{% url 'panel:phpmyadmin_launch' database.pk %}">
|
||||
{% csrf_token %}
|
||||
<button class="button secondary" type="submit">Open phpMyAdmin</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% if is_operator %}
|
||||
<a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if is_operator and manage_database_provisioning and database.provisioning.problem %}
|
||||
<p class="heading-meta">{{ database.provisioning.problem }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% if is_operator or manage_database_provisioning %}
|
||||
<td>
|
||||
<div class="form-actions">
|
||||
{% 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 is_operator and manage_database_provisioning and database.provisioning.problem %}
|
||||
<p class="heading-meta">{{ database.provisioning.problem }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty">No databases requested yet.</p>
|
||||
<p class="empty">No databases yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
@@ -239,6 +244,15 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% for zone, records in dns_zone_records %}
|
||||
<header class="section-heading"><h3>Records for {{ zone.domain }}</h3></header>
|
||||
{% include "hosting/dns_record_table.html" %}
|
||||
{% endfor %}
|
||||
{% elif default_zone_records %}
|
||||
<header class="section-heading"><h3>Proposed DNS zone</h3><span class="muted">Preview</span></header>
|
||||
{% include "hosting/dns_record_table.html" with records=default_zone_records %}
|
||||
{% elif default_zone_problem %}
|
||||
<p class="section-text">Check the DNS zone template. {{ default_zone_problem }}</p>
|
||||
{% else %}
|
||||
<p class="empty">No DNS zones configured.</p>
|
||||
{% endif %}
|
||||
@@ -284,7 +298,7 @@
|
||||
<section class="surface" aria-labelledby="mailboxes-heading">
|
||||
<header class="section-heading">
|
||||
<div>
|
||||
<h2 id="mailboxes-heading" tabindex="-1">Mailbox requests</h2>
|
||||
<h2 id="mailboxes-heading" tabindex="-1">Mailboxes</h2>
|
||||
{% if is_tenant or perms.hosting.view_hostingplan %}
|
||||
{% if account.hosting_plan and account.hosting_plan.mailbox_limit is not None %}
|
||||
<p class="heading-meta">{{ mailboxes|length }} of {{ account.hosting_plan.mailbox_limit }} mailboxes requested</p>
|
||||
@@ -292,7 +306,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
{% 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>
|
||||
<a class="button primary" href="{% url 'panel:mailbox_create' account.pk %}">{% if automatic_mailbox_provisioning %}Add{% else %}Request{% endif %} mailbox</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if mailboxes %}
|
||||
@@ -302,14 +316,23 @@
|
||||
<tr>
|
||||
<th scope="col">Email address</th>
|
||||
<th scope="col">Storage limit</th>
|
||||
{% if is_operator or manage_mailbox_provisioning %}<th scope="col">Deployment</th>{% endif %}
|
||||
<th scope="col">Status and actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for mailbox in mailboxes %}
|
||||
<tr>
|
||||
<td class="domain">
|
||||
{{ mailbox }}
|
||||
<th scope="row" class="domain">{{ mailbox }}</th>
|
||||
<td>{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
|
||||
<td>
|
||||
<div class="table-actions">
|
||||
{% if manage_mailbox_provisioning %}
|
||||
{% url 'panel:mailbox_provision' mailbox.pk as provision_url %}
|
||||
{% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=local_mailbox_enabled action=provision_url resource=mailbox provision_label="Provision mailbox" %}
|
||||
{% else %}
|
||||
{% include "hosting/resource_provisioning.html" with provisioning=mailbox.provisioning enabled=False %}
|
||||
{% endif %}
|
||||
{% if not mailbox.provisioning %}<span class="status pending">Requested</span>{% endif %}
|
||||
{% if mailbox.pk in webmail_mailbox_ids %}
|
||||
<form method="post" action="{% url 'panel:roundcube_launch' mailbox.pk %}">
|
||||
{% csrf_token %}
|
||||
@@ -317,39 +340,29 @@
|
||||
</form>
|
||||
{% endif %}
|
||||
{% if manage_mail_vacation %}
|
||||
<div><a class="record-link" href="{% url 'panel:mail_vacation' mailbox.pk %}" aria-label="Automatic replies for {{ mailbox }}">Automatic replies</a></div>
|
||||
<a class="record-link" href="{% url 'panel:mail_vacation' mailbox.pk %}" aria-label="Automatic replies for {{ mailbox }}">Automatic replies</a>
|
||||
{% endif %}
|
||||
{% if show_mailbox_credentials %}
|
||||
<div><a class="record-link" href="{% url 'panel:mailbox_credentials' mailbox.pk %}" aria-label="Connection details for {{ mailbox }}">Connection details</a></div>
|
||||
<a class="record-link" href="{% url 'panel:mailbox_credentials' mailbox.pk %}" aria-label="Connection details for {{ mailbox }}">Connection details</a>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{% if mailbox.quota_mib is not None %}{{ mailbox.quota_mib }} MiB{% else %}Unlimited{% endif %}</td>
|
||||
{% if is_operator or manage_mailbox_provisioning %}
|
||||
<td>
|
||||
<div class="form-actions">
|
||||
{% 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 %}
|
||||
{% if manage_mailbox_provisioning %}
|
||||
{% url 'panel:mailbox_provision' mailbox.pk as provision_url %}
|
||||
{% 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 is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %}
|
||||
<p class="heading-meta">{{ mailbox.provisioning.problem }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if is_operator and manage_mailbox_provisioning and mailbox.provisioning.problem %}
|
||||
<p class="heading-meta">{{ mailbox.provisioning.problem }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty">No mailboxes requested yet.</p>
|
||||
<p class="empty">No mailboxes yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
</section>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Hosting accounts · Coulobre Panel{% endblock %}
|
||||
{% block title %}{% if is_customer %}My hosting{% else %}Hosting accounts{% endif %} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Hosting accounts</h1>
|
||||
<p class="heading-meta">Manage domains and their hosting services. Link a customer to give them access.</p>
|
||||
<h1>{% if is_customer %}My hosting{% elif is_reseller %}Customer hosting{% else %}Hosting accounts{% endif %}</h1>
|
||||
{% if is_operator %}<p class="heading-meta">Manage domains and their hosting services. Link a customer to give them access.</p>{% endif %}
|
||||
<p class="heading-meta">{{ paginator.count }} account{{ paginator.count|pluralize }}{% if search %} matching your search{% endif %}</p>
|
||||
{% if account_allowance %}<p class="heading-meta">{{ account_allowance.used }} of {{ account_allowance.limit }} accounts allocated</p>{% endif %}
|
||||
</div>
|
||||
@@ -12,6 +12,17 @@
|
||||
<a class="button primary" href="{% url 'panel:account_create' %}">Add hosting account</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if health_summary %}
|
||||
<section class="surface section-heading" aria-label="Server status">
|
||||
<p>{% if not health_summary.configured %}Service checks need setup.{% elif health_summary.needs_attention %}{{ health_summary.needs_attention }} of {{ health_summary.configured }} service checks need attention.{% else %}All {{ health_summary.configured }} service checks are healthy.{% endif %}</p>
|
||||
<a class="button secondary" href="{% url 'panel:service_health' %}">Service health</a>
|
||||
</section>
|
||||
{% elif is_reseller %}
|
||||
<section class="surface section-heading" aria-label="Customer access">
|
||||
<p>Manage the logins for your assigned customers.</p>
|
||||
<a class="button secondary" href="{% url 'panel:customers' %}">My customers</a>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="surface" aria-label="Hosting account list">
|
||||
<div class="toolbar account-toolbar">
|
||||
<form class="form-actions" method="get" action="{% url 'panel:accounts' %}" role="search">
|
||||
@@ -42,6 +53,13 @@
|
||||
<td>
|
||||
<a class="record-link" href="{{ account.get_absolute_url }}">{{ account.name }}</a>
|
||||
<div class="domain muted account-domain">{{ account.primary_domain }}</div>
|
||||
{% if is_customer %}
|
||||
<div class="table-actions">
|
||||
{% if show_customer_website_link %}<a href="{{ account.get_absolute_url }}#websites">Websites</a>{% endif %}
|
||||
<a href="{{ account.get_absolute_url }}#domains-dns">Domains and DNS</a>
|
||||
<a href="{{ account.get_absolute_url }}#email">Email</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{% include "hosting/account_status.html" %}</td>
|
||||
{% if is_operator and perms.hosting.view_customer %}<td>{{ account.customer|default_if_none:"No customer linked" }}</td>{% endif %}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
<div><dt>DNS zones</dt><dd>{% for zone in inventory.zones %}{{ zone.domain }}{% if zone.published is not None %} (published serial {{ zone.published }}){% endif %}{% if not forloop.last %}, {% endif %}{% empty %}None{% endfor %}</dd></div>
|
||||
<div><dt>Existing backups</dt><dd>{{ inventory.backups }}</dd></div>
|
||||
{% if inventory.customer %}<div><dt>Customer</dt><dd>{{ inventory.customer }}</dd></div>{% endif %}
|
||||
{% if inventory.reseller %}<div><dt>Reseller</dt><dd>{{ inventory.reseller }}</dd></div>{% endif %}
|
||||
{% if inventory.reseller %}<div><dt>Customer manager</dt><dd>{{ inventory.reseller }}</dd></div>{% endif %}
|
||||
</dl>
|
||||
</section>
|
||||
{% if retirement %}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}My account · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading"><h1>My account</h1></header>
|
||||
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||
<section class="surface" aria-labelledby="account-sign-in">
|
||||
<header class="section-heading"><h2 id="account-sign-in">Sign-in and security</h2></header>
|
||||
<dl class="section-text">
|
||||
<dt>Username</dt><dd>{{ request.user.get_username }}</dd>
|
||||
<dt>Email address</dt><dd>{{ request.user.email|default:"No email address" }}</dd>
|
||||
<dt>Two-factor authentication</dt><dd>{{ factor }}</dd>
|
||||
</dl>
|
||||
{% if not email_available %}<p class="section-text muted">Email changes require configured panel email delivery.</p>{% endif %}
|
||||
<div class="section-text form-actions">
|
||||
<a class="button secondary" href="{% url 'panel:account_password' %}">Change password</a>
|
||||
{% if email_available %}<a class="button secondary" href="{% url 'panel:account_email' %}">Change email address</a>{% endif %}
|
||||
<a class="button secondary" href="{% url 'panel:account_authenticator' %}">{% if factor_enabled %}Change{% else %}Set up{% endif %} authenticator app</a>
|
||||
{% if factor_enabled %}<a class="button secondary" href="{% url 'panel:account_recovery_codes' %}">Generate recovery codes</a>{% endif %}
|
||||
<a class="button secondary" href="{% url 'panel:account_other_sessions' %}">Sign out other sessions</a>
|
||||
</div>
|
||||
</section>
|
||||
{% if events %}
|
||||
<section class="surface" aria-labelledby="security-activity">
|
||||
<header class="section-heading"><h2 id="security-activity">Recent security activity</h2></header>
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Action</th><th scope="col">Time (UTC)</th></tr></thead>
|
||||
<tbody>
|
||||
{% for event in events %}<tr><td>{{ event.get_action_display }}</td><td>{{ event.created_at|date:"j M Y, H:i" }}</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}{{ heading }} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{% url 'panel:account_security' %}">← My account</a>
|
||||
<header class="page-heading"><h1>{{ heading }}</h1></header>
|
||||
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||
<section class="surface editor-surface">
|
||||
{% if instructions %}<p>{{ instructions }}</p>{% endif %}
|
||||
{% include "hosting/authenticator_setup.html" %}
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Continue</button>
|
||||
{% if can_send_code %}
|
||||
<button class="button secondary" type="submit" name="send_code" value="1" formnovalidate>Send email code</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,24 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Complete hosting setup · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading"><div><h1>Complete hosting setup</h1><p class="domain">{{ account.primary_domain }}</p></div></header>
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
<p>Choose which missing services to set up for this domain. Set up HTTPS once the domain resolves.</p>
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
{% if form.fields %}<button class="button primary" type="submit">Set up selected services</button>{% endif %}
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Back to account</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% if preview_records or preview_problem %}
|
||||
<section class="surface" aria-label="Proposed DNS records">
|
||||
<header class="section-heading"><h2>Proposed DNS records</h2></header>
|
||||
{% include "hosting/dns_record_table.html" with records=preview_records %}
|
||||
{% if preview_problem %}<p class="section-text">{{ preview_problem }}</p>{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -4,8 +4,7 @@
|
||||
<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>
|
||||
{% include "hosting/brand.html" %}
|
||||
</div>
|
||||
<section class="sign-in-card">
|
||||
{% block authentication_content %}{% include "hosting/authentication_card.html" %}{% endblock %}
|
||||
|
||||
@@ -1,23 +1,7 @@
|
||||
{% load static %}
|
||||
<h1>{{ heading }}</h1>
|
||||
{% if instructions %}<p>{{ instructions }}</p>{% endif %}
|
||||
{% if code_notice %}<p role="status">{{ code_notice }}</p>{% endif %}
|
||||
{% if configuration_url %}
|
||||
<div class="authenticator-setup">
|
||||
<p>Scan this QR code with your authenticator app.</p>
|
||||
<img class="authenticator-qr" src="data:image/svg+xml;base64,{{ qr_image }}" width="192" height="192" alt="Authenticator setup QR code">
|
||||
<p><a href="{{ configuration_url }}" rel="noreferrer">Open in an authenticator app</a></p>
|
||||
<details>
|
||||
<summary>Enter the setup key manually</summary>
|
||||
<div class="form-actions">
|
||||
<input id="setup-key" type="text" readonly autocomplete="off" spellcheck="false" aria-label="Setup key" value="{{ setup_key }}" data-secret>
|
||||
<button class="button secondary" type="button" hidden data-copy-field="setup-key">Copy setup key</button>
|
||||
</div>
|
||||
<p id="copy-field-status" role="status"></p>
|
||||
</details>
|
||||
</div>
|
||||
<script src="{% static 'hosting/copy-field.js' %}" defer></script>
|
||||
{% endif %}
|
||||
{% include "hosting/authenticator_setup.html" %}
|
||||
{% if form %}
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{% load static %}
|
||||
{% if configuration_url %}
|
||||
<div class="authenticator-setup">
|
||||
<p>Scan this QR code with your authenticator app.</p>
|
||||
<img class="authenticator-qr" src="data:image/svg+xml;base64,{{ qr_image }}" width="192" height="192" alt="Authenticator setup QR code">
|
||||
<p><a href="{{ configuration_url }}" rel="noreferrer">Open in an authenticator app</a></p>
|
||||
<details>
|
||||
<summary>Enter the setup key manually</summary>
|
||||
<div class="form-actions">
|
||||
<input id="setup-key" type="text" readonly autocomplete="off" spellcheck="false" aria-label="Setup key" value="{{ setup_key }}" data-secret>
|
||||
<button class="button secondary" type="button" hidden data-copy-field="setup-key">Copy setup key</button>
|
||||
</div>
|
||||
<p id="copy-field-status" role="status"></p>
|
||||
</details>
|
||||
</div>
|
||||
<script src="{% static 'hosting/copy-field.js' %}" defer></script>
|
||||
{% endif %}
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{% block title %}Coulobre Panel{% endblock %}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="{% static 'hosting/coulobre-mark.svg' %}">
|
||||
<link rel="stylesheet" href="{% static 'hosting/panel.css' %}">
|
||||
{% if custom_panel_theme %}<link rel="stylesheet" href="{% url 'panel:theme_stylesheet' %}">{% endif %}
|
||||
<script src="{% static 'hosting/panel-appearance.js' %}"></script>
|
||||
@@ -14,8 +15,7 @@
|
||||
<div class="panel">
|
||||
<aside class="sidebar">
|
||||
<a class="brand" href="{% url 'panel:accounts' %}">
|
||||
<span class="brand-mark" aria-hidden="true">C</span>
|
||||
<span>Coulobre <span class="brand-product">Panel</span></span>
|
||||
{% include "hosting/brand.html" %}
|
||||
</a>
|
||||
<button class="menu-toggle" type="button" aria-controls="panel-navigation" aria-expanded="true" hidden>
|
||||
<span class="menu-icon" aria-hidden="true"></span>
|
||||
@@ -30,13 +30,13 @@
|
||||
{% if is_tenant or perms.hosting.view_hostingaccount %}
|
||||
<a href="{% url 'panel:accounts' %}"{% if panel_section == 'accounts' %} aria-current="{% if current == 'accounts' %}page{% else %}location{% endif %}"{% endif %}>
|
||||
<span class="nav-icon nav-icon-accounts" aria-hidden="true"></span>
|
||||
Hosting accounts
|
||||
{% if is_customer %}My hosting{% else %}Hosting accounts{% endif %}
|
||||
</a>
|
||||
{% endif %}
|
||||
{% 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
|
||||
{% if is_reseller %}My customers{% else %}Customers{% endif %}
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if is_operator and perms.hosting.view_reseller %}
|
||||
@@ -53,7 +53,7 @@
|
||||
{% endif %}
|
||||
{% if group_customer_navigation %}</details>{% endif %}
|
||||
{% if is_operator and perms.hosting.view_servicehealth %}
|
||||
<details class="sidebar-group"{% if panel_section == 'plans' or panel_section == 'service_health' or panel_section == 'installation' %} open{% endif %}>
|
||||
<details class="sidebar-group"{% if panel_section == 'plans' or panel_section == 'service_health' or panel_section == 'installation' or panel_section == 'dns_defaults' or panel_section == 'updates' %} open{% endif %}>
|
||||
<summary>Server and services</summary>
|
||||
{% endif %}
|
||||
{% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
|
||||
@@ -71,12 +71,26 @@
|
||||
<span class="nav-icon nav-icon-information" aria-hidden="true">i</span>
|
||||
About Coulobre
|
||||
</a>
|
||||
{% if request.user.is_superuser %}
|
||||
<a href="{% url 'panel:updates' %}"{% if current == 'updates' %} aria-current="page"{% endif %}>
|
||||
<span class="nav-icon nav-icon-plans" aria-hidden="true"></span>
|
||||
Updates
|
||||
</a>
|
||||
<a href="{% url 'panel:dns_defaults' %}"{% if current == 'dns_defaults' %} aria-current="page"{% endif %}>
|
||||
<span class="nav-icon nav-icon-plans" aria-hidden="true"></span>
|
||||
DNS zone template
|
||||
</a>
|
||||
{% endif %}
|
||||
</details>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
</nav>
|
||||
<div class="sidebar-account">
|
||||
<span class="operator">{{ request.user.get_username }}</span>
|
||||
{% if request.impersonation %}
|
||||
<span class="operator">{{ request.user.get_username }}</span>
|
||||
{% else %}
|
||||
<a class="operator" href="{% url 'panel:account_security' %}" aria-label="My account for {{ request.user.get_username }}">{{ request.user.get_username }}</a>
|
||||
{% endif %}
|
||||
<form method="post" action="{% url 'panel:logout' %}">
|
||||
{% csrf_token %}
|
||||
<button type="submit">Sign out</button>
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
<span class="brand-mark" aria-hidden="true"></span>
|
||||
<span>Coulobre <span class="brand-product">Panel</span></span>
|
||||
@@ -1,9 +1,9 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Customers · Coulobre Panel{% endblock %}
|
||||
{% block title %}{% if is_reseller %}My customers{% else %}Customers{% endif %} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Customers</h1>
|
||||
<h1>{% if is_reseller %}My customers{% else %}Customers{% endif %}</h1>
|
||||
<p class="heading-meta">Manage the logins people use to access their assigned hosting.</p>
|
||||
</div>
|
||||
{% if is_operator and perms.hosting.add_customer %}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Request MariaDB database · Coulobre Panel{% endblock %}
|
||||
{% block title %}{% if auto_provision %}Add{% else %}Request{% endif %} MariaDB database · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading"><h1>Request MariaDB database</h1></header>
|
||||
<header class="page-heading"><h1>{% if auto_provision %}Add{% else %}Request{% endif %} MariaDB database</h1></header>
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% include "hosting/customer_action_fields.html" %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
{% if can_request_resource %}
|
||||
<button class="button primary" type="submit">Request database</button>
|
||||
<button class="button primary" type="submit">{% if auto_provision %}Add{% else %}Request{% endif %} database</button>
|
||||
{% endif %}
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}DNS zone template · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading">
|
||||
<div><h1>DNS zone template</h1><p class="heading-meta">These settings apply when you create a managed DNS zone.</p></div>
|
||||
</header>
|
||||
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<button class="button primary" type="submit">Save template</button>
|
||||
</form>
|
||||
</section>
|
||||
<section class="surface" aria-label="Template preview">
|
||||
<header class="section-heading"><h2>Current template</h2></header>
|
||||
<dl class="details">
|
||||
<div><dt>Nameservers</dt><dd>{{ effective.nameservers|join:", "|default:"Not configured" }}</dd></div>
|
||||
<div><dt>Hosting IP addresses</dt><dd>{{ effective.addresses|join:", "|default:"Not configured" }}</dd></div>
|
||||
<div><dt>Website records</dt><dd>@{% if effective.include_www %}, www{% endif %}{% if effective.include_wildcard %}, *{% endif %}</dd></div>
|
||||
</dl>
|
||||
{% include "hosting/dns_record_table.html" with records=effective.records %}
|
||||
<p class="section-text">Coulobre adds mail records for domains you choose to manage. A DKIM record needs a provisioned signing key.</p>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,19 @@
|
||||
{{ form.editor_rows|json_script:"dns-record-data" }}
|
||||
<div data-dns-editor hidden>
|
||||
<h2>DNS records</h2>
|
||||
<p class="heading-meta">Use @ for the zone name, or enter a name such as www.</p>
|
||||
<div class="dns-editor-rows" data-dns-rows></div>
|
||||
<button class="button secondary" type="button" data-add-dns-record>Add record</button>
|
||||
<template data-dns-row>
|
||||
<fieldset class="dns-edit-row">
|
||||
<legend class="visually-hidden"></legend>
|
||||
<label>Name<input data-record-name placeholder="@" required></label>
|
||||
<label>Type<select data-record-type>
|
||||
<option>A</option><option>AAAA</option><option>CNAME</option><option>MX</option><option>TXT</option><option>SRV</option><option>CAA</option>
|
||||
</select></label>
|
||||
<label data-priority-label hidden>Priority<input data-record-priority type="number" min="0" max="65535" inputmode="numeric"></label>
|
||||
<label><span data-record-value-label>Value</span><textarea rows="1" data-record-value required></textarea></label>
|
||||
<button class="button secondary" type="button" data-remove-record>Remove</button>
|
||||
</fieldset>
|
||||
</template>
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
{% if records %}
|
||||
<div class="table-scroll">
|
||||
<table class="dns-record-table">
|
||||
<thead><tr><th scope="col">Name</th><th scope="col">Type</th><th scope="col">Value</th></tr></thead>
|
||||
<tbody>
|
||||
{% for record in records %}
|
||||
<tr><th scope="row" class="domain">{{ record.name }}</th><td>{{ record.type }}</td><td><code>{{ record.value }}</code></td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -1,4 +1,5 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% load static %}
|
||||
{% block title %}{{ page_title }} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
@@ -8,12 +9,35 @@
|
||||
<p class="heading-meta domain">{{ domain }}</p>
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface editor-surface">
|
||||
<section class="surface section-text dns-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
{{ form.non_field_errors }}
|
||||
{% for hidden in form.hidden_fields %}
|
||||
{{ hidden.errors }}
|
||||
{% if hidden.name == 'record_rows' %}<input type="hidden" name="record_rows" value="">{% else %}{{ hidden }}{% endif %}
|
||||
{% endfor %}
|
||||
{% if not form.nameservers.is_hidden %}
|
||||
<details{% if form.nameservers.errors or form.responsible_name.errors or not form.nameservers.value %} open{% endif %}>
|
||||
<summary>Zone settings</summary>
|
||||
{{ form.nameservers.as_field_group }}
|
||||
{{ form.responsible_name.as_field_group }}
|
||||
{{ form.delegate_dns.as_field_group }}
|
||||
{{ form.manage_mail_dns.as_field_group }}
|
||||
</details>
|
||||
{% endif %}
|
||||
<div data-dns-text-fields>
|
||||
{{ form.addresses.as_field_group }}
|
||||
{{ form.mx_records.as_field_group }}
|
||||
{{ form.txt_records.as_field_group }}
|
||||
{{ form.extra_records.as_field_group }}
|
||||
</div>
|
||||
{% if not form.is_bound or form.record_rows.value %}
|
||||
{% include "hosting/dns_record_editor.html" %}
|
||||
<script src="{% static 'hosting/dns-record-editor.js' %}" defer></script>
|
||||
{% endif %}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Save zone</button>
|
||||
<button class="button primary" type="submit">{% if publish_on_create %}Save and publish zone{% else %}Save zone{% endif %}</button>
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -25,7 +25,14 @@
|
||||
{% for name, enabled in features %}
|
||||
<tr>
|
||||
<th scope="row">{{ name }}</th>
|
||||
<td>{% if enabled %}<span class="status active">Enabled</span>{% else %}Disabled{% endif %}</td>
|
||||
<td>
|
||||
<div class="table-actions">
|
||||
{% if enabled %}<span class="status active">Enabled</span>{% else %}<span>Disabled</span>{% endif %}
|
||||
{% if request.user.is_superuser and name == 'Default managed DNS zones for new accounts' %}
|
||||
<a class="record-link" href="{% url 'panel:dns_defaults' %}">Configure DNS defaults</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
<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>
|
||||
{% include "hosting/brand.html" %}
|
||||
</div>
|
||||
<section class="sign-in-card">
|
||||
<h1>Sign in</h1>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Request mailbox · Coulobre Panel{% endblock %}
|
||||
{% block title %}{% if auto_provision %}Add{% else %}Request{% endif %} mailbox · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Request mailbox</h1>
|
||||
<h1>{% if auto_provision %}Add{% else %}Request{% endif %} mailbox</h1>
|
||||
<p class="heading-meta domain">{{ account.primary_domain }}</p>
|
||||
</div>
|
||||
</header>
|
||||
@@ -14,7 +14,7 @@
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
{% if can_request_resource %}
|
||||
<button class="button primary" type="submit">Request mailbox</button>
|
||||
<button class="button primary" type="submit">{% if auto_provision %}Add{% else %}Request{% endif %} mailbox</button>
|
||||
{% endif %}
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
|
||||
@@ -8,7 +8,23 @@ Set your password by opening this link within 48 hours:
|
||||
|
||||
{% if account %}Your hosting account is {{ account.primary_domain }}.{% if account.hosting_plan %}
|
||||
Hosting plan: {{ account.hosting_plan.name }}
|
||||
Website limit: {{ account.hosting_plan.website_limit }}{% endif %}
|
||||
Website limit: {{ account.hosting_plan.website_limit }}
|
||||
Scheduled tasks per account: {{ account.hosting_plan.website_job_limit }}
|
||||
Database limit: {{ account.hosting_plan.database_limit|default_if_none:"Unlimited" }}
|
||||
Mailbox limit: {{ account.hosting_plan.mailbox_limit|default_if_none:"Unlimited" }}{% if account.hosting_plan.mailbox_quota_mib %}
|
||||
Storage per new mailbox: {{ account.hosting_plan.mailbox_quota_mib }} MiB{% endif %}{% if account.hosting_plan.website_storage_limit_mib %}
|
||||
Default website storage limit: {{ account.hosting_plan.website_storage_limit_mib }} MiB{% endif %}{% endif %}
|
||||
{% if nameservers %}
|
||||
To use Coulobre DNS, set these nameservers at your registrar:
|
||||
{% for server in nameservers %}{{ server }}
|
||||
{% endfor %}{% elif website_records %}
|
||||
If your DNS is hosted elsewhere, add these website records at your DNS provider:
|
||||
{% for record in website_records %}{{ record.name }} {{ record.record_type }} {{ record.address }}
|
||||
{% endfor %}{% endif %}{% if mail_configured %}{% if imap_host or submission_host %}
|
||||
Use the full mailbox email address as your mail client username.{% if imap_host %}
|
||||
Incoming mail (IMAP over TLS): {{ imap_host }}, port 993{% endif %}{% if submission_host %}
|
||||
Outgoing mail (SMTP with STARTTLS): {{ submission_host }}, port 587{% endif %}
|
||||
{% endif %}{% endif %}
|
||||
|
||||
After signing in, open the hosting account for website status, DNS settings,
|
||||
and instructions for configuring email.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<h1>{{ reseller }}</h1>
|
||||
{% if perms.hosting.change_reseller %}
|
||||
<a class="button secondary" href="{% url 'panel:manage_invitation' 'manager' reseller.pk %}">Contact and invitation</a>
|
||||
<a class="button secondary" href="{% url 'panel:reseller_edit' reseller.pk %}">Edit reseller</a>
|
||||
<a class="button secondary" href="{% url 'panel:reseller_edit' reseller.pk %}">Edit customer manager</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
<dl class="details surface">
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface" aria-label="Reseller list">
|
||||
<section class="surface" aria-label="Customer manager list">
|
||||
<form class="toolbar" method="get" action="{% url 'panel:resellers' %}" role="search">
|
||||
<label class="visually-hidden" for="reseller-search">Search by username</label>
|
||||
<input type="search" id="reseller-search" name="q" placeholder="Username" value="{{ search }}">
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Updates · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading">
|
||||
<div><h1>Updates</h1><p class="heading-meta">Installed version {{ installed_version|default:"unknown" }}</p></div>
|
||||
<a class="button secondary" href="{% url 'panel:updates' %}?refresh=1">Refresh status</a>
|
||||
</header>
|
||||
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||
{% if form.errors %}<div class="notice">{{ form.errors }}</div>{% endif %}
|
||||
{% if update_status %}
|
||||
<section class="surface" aria-labelledby="update-status">
|
||||
<header class="section-heading"><h2 id="update-status">Latest update</h2><span>{{ update_status.target_version }}</span></header>
|
||||
<p class="section-text">{{ update_status.message }}</p>
|
||||
<p class="section-text muted">Requested by {{ update_status.actor }} · {{ update_status.updated_at }}</p>
|
||||
{% if update_status.state == "recovery_required" %}
|
||||
<p class="section-text">Review the updater journal and recovery files in <code>/var/lib/coulobre-update/</code> before starting another upgrade.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if not updater_enabled %}
|
||||
<section class="surface"><p class="empty">Enable the local updater socket on an installer-managed panel to use web updates.</p></section>
|
||||
{% elif catalog_problem %}
|
||||
<section class="surface"><p class="empty">{{ catalog_problem }}</p></section>
|
||||
{% else %}
|
||||
{% if preflight_problem %}
|
||||
<section class="surface"><p class="empty">{{ preflight_problem }}</p></section>
|
||||
{% endif %}
|
||||
{% if linked_nodes %}
|
||||
<section class="surface" aria-labelledby="linked-updates">
|
||||
<header class="section-heading"><h2 id="linked-updates">Linked receivers</h2></header>
|
||||
<p class="section-text">Account for every panel using a shared receiver. Stage receivers at the target release in maintenance mode, then upgrade the panels. Resume the receivers when all panels are verified.</p>
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Role</th><th scope="col">Host</th><th scope="col">Release</th><th scope="col">Probe protocol</th><th scope="col">Status</th><th scope="col">Staged target</th></tr></thead>
|
||||
<tbody>
|
||||
{% for node in linked_nodes %}
|
||||
<tr><td>{{ node.role|upper }}</td><td>{{ node.host }}</td><td>{{ node.release|default:"Unknown" }}</td><td>{{ node.protocol|default:"Unknown" }}</td><td>{{ node.state|capfirst }}</td><td>{{ node.upgrade_target|default:"—" }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="surface" aria-labelledby="available-updates">
|
||||
<header class="section-heading"><h2 id="available-updates">Compatible releases</h2></header>
|
||||
{% for release in releases %}
|
||||
<details class="section-text">
|
||||
<summary>{{ release.version }}{% if release.prerelease %} · Prerelease{% endif %}</summary>
|
||||
{{ release.notes|linebreaks }}
|
||||
{% if may_apply and release.version in applyable_versions and update_status.state != "running" and update_status.state != "recovery_required" %}
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="version" value="{{ release.version }}">
|
||||
<input type="hidden" name="sha256" value="{{ release.sha256 }}">
|
||||
<label><input type="checkbox" name="confirm" required> I reviewed this release and want to update this server.</label>
|
||||
<p class="heading-meta">The panel goes offline while the updater creates a recovery backup and installs the release.</p>
|
||||
<button class="button primary" type="submit">Install {{ release.version }}</button>
|
||||
</form>
|
||||
{% elif linked_nodes and release.version not in applyable_versions %}
|
||||
<p>Stage all linked receivers for this release before installing it.</p>
|
||||
{% endif %}
|
||||
</details>
|
||||
{% empty %}
|
||||
<p class="empty">No compatible web updates are published.</p>
|
||||
{% endfor %}
|
||||
{% if releases and not may_apply %}<p class="section-text">Sign in with two-factor authentication to install an update.</p>{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,256 @@
|
||||
import re
|
||||
from datetime import timedelta
|
||||
from secrets import token_urlsafe
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core import mail
|
||||
from django.test import Client, TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from django_otp.oath import totp
|
||||
from django_otp.plugins.otp_email.models import EmailDevice
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
|
||||
from .impersonation import SESSION_DURATION, SESSION_KEY
|
||||
from .models import (
|
||||
Customer,
|
||||
CustomerImpersonation,
|
||||
PanelEmailChange,
|
||||
PanelRecoveryCode,
|
||||
PanelSecurityEvent,
|
||||
)
|
||||
from .panel_factors import DEVICE_NAME, secret_digest
|
||||
|
||||
PASSWORD = token_urlsafe(24)
|
||||
NEW_PASSWORD = token_urlsafe(24)
|
||||
|
||||
|
||||
@override_settings(
|
||||
EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
|
||||
EMAIL_HOST="mail.example.test",
|
||||
REQUIRE_PRIVILEGED_MFA=False,
|
||||
)
|
||||
class AccountSecurityTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
cls.user = get_user_model().objects.create_user(
|
||||
"customer", email="old@example.test", password=PASSWORD
|
||||
)
|
||||
cls.customer = Customer.objects.create(user=cls.user)
|
||||
cls.operator = get_user_model().objects.create_superuser(
|
||||
"operator", password=PASSWORD
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.profile = reverse("panel:account_security")
|
||||
self.client.force_login(self.user)
|
||||
|
||||
def authorize_factor(self, device):
|
||||
session = self.client.session
|
||||
session["otp_device_id"] = device.persistent_id
|
||||
session.save()
|
||||
|
||||
def test_profile_is_private_and_reachable_for_both_roles(self):
|
||||
response = self.client.get(self.profile)
|
||||
self.assertContains(response, "old@example.test")
|
||||
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||
operator = Client()
|
||||
operator.force_login(self.operator)
|
||||
self.assertContains(operator.get(self.profile), "My account")
|
||||
self.assertRedirects(
|
||||
Client().get(self.profile),
|
||||
f"{reverse('panel:login')}?next={self.profile}",
|
||||
fetch_redirect_response=False,
|
||||
)
|
||||
|
||||
def test_password_change_keeps_current_session_and_revokes_others(self):
|
||||
other = Client()
|
||||
other.force_login(self.user)
|
||||
path = reverse("panel:account_password")
|
||||
data = {
|
||||
"password": PASSWORD,
|
||||
"new_password": NEW_PASSWORD,
|
||||
"confirm_password": NEW_PASSWORD,
|
||||
}
|
||||
self.assertRedirects(self.client.post(path, data), self.profile)
|
||||
self.user.refresh_from_db()
|
||||
self.assertTrue(self.user.check_password(NEW_PASSWORD))
|
||||
self.assertEqual(other.get(self.profile).status_code, 302)
|
||||
self.assertContains(self.client.get(self.profile), "Password changed")
|
||||
event = PanelSecurityEvent.objects.get(user=self.user)
|
||||
self.assertEqual(event.action, PanelSecurityEvent.Action.PASSWORD)
|
||||
|
||||
def test_other_session_sign_out_checks_credentials_and_csrf(self):
|
||||
other = Client()
|
||||
other.force_login(self.user)
|
||||
path = reverse("panel:account_other_sessions")
|
||||
self.assertContains(
|
||||
self.client.post(path, {"password": "incorrect"}),
|
||||
"The current password is incorrect.",
|
||||
)
|
||||
self.assertEqual(other.get(self.profile).status_code, 200)
|
||||
browser = Client(enforce_csrf_checks=True)
|
||||
browser.force_login(self.user)
|
||||
self.assertEqual(
|
||||
browser.post(path, {"password": PASSWORD}).status_code, 403
|
||||
)
|
||||
self.assertRedirects(
|
||||
self.client.post(path, {"password": PASSWORD}), self.profile
|
||||
)
|
||||
self.assertEqual(other.get(self.profile).status_code, 302)
|
||||
self.assertEqual(self.client.get(self.profile).status_code, 200)
|
||||
|
||||
def test_email_verification_is_bound_to_requesting_session(self):
|
||||
device = EmailDevice.objects.create(
|
||||
user=self.user,
|
||||
name=DEVICE_NAME,
|
||||
email=self.user.email,
|
||||
token="510280",
|
||||
valid_until=timezone.now() + timedelta(minutes=5),
|
||||
)
|
||||
self.authorize_factor(device)
|
||||
other = Client()
|
||||
other.force_login(self.user)
|
||||
session = other.session
|
||||
session["otp_device_id"] = device.persistent_id
|
||||
session.save()
|
||||
|
||||
start = reverse("panel:account_email")
|
||||
verify = reverse("panel:account_email_verify")
|
||||
response = self.client.post(
|
||||
start,
|
||||
{
|
||||
"password": PASSWORD,
|
||||
"email": "new@example.test",
|
||||
"code": "510280",
|
||||
},
|
||||
)
|
||||
self.assertRedirects(response, verify)
|
||||
self.user.refresh_from_db()
|
||||
self.assertEqual(self.user.email, "old@example.test")
|
||||
self.assertEqual(mail.outbox[0].to, ["new@example.test"])
|
||||
code = re.search(r"\b[0-9a-f]{12}\b", mail.outbox[0].body)[0]
|
||||
self.assertNotEqual(PanelEmailChange.objects.get().digest, code)
|
||||
self.assertContains(
|
||||
other.post(verify, {"code": code}), "invalid or expired"
|
||||
)
|
||||
with self.captureOnCommitCallbacks(execute=True):
|
||||
self.assertRedirects(
|
||||
self.client.post(verify, {"code": code}), self.profile
|
||||
)
|
||||
self.user.refresh_from_db()
|
||||
device.refresh_from_db()
|
||||
self.assertEqual(self.user.email, "new@example.test")
|
||||
self.assertEqual(device.email, self.user.email)
|
||||
self.assertIsNone(device.token)
|
||||
self.assertFalse(PanelEmailChange.objects.exists())
|
||||
self.assertEqual(mail.outbox[1].to, ["old@example.test"])
|
||||
self.assertEqual(other.get(self.profile).status_code, 302)
|
||||
|
||||
def test_optional_authenticator_becomes_required_after_enrollment(self):
|
||||
start = reverse("panel:account_authenticator")
|
||||
confirm = reverse("panel:account_authenticator_confirm")
|
||||
self.assertRedirects(
|
||||
self.client.post(start, {"password": PASSWORD}), confirm
|
||||
)
|
||||
device = TOTPDevice.objects.get(user=self.user)
|
||||
token = f"{totp(device.bin_key):06d}"
|
||||
self.assertContains(
|
||||
self.client.post(confirm, {"code": token}),
|
||||
"Save your recovery codes",
|
||||
)
|
||||
device.refresh_from_db()
|
||||
self.assertTrue(device.confirmed)
|
||||
self.assertEqual(
|
||||
PanelRecoveryCode.objects.filter(user=self.user).count(), 10
|
||||
)
|
||||
|
||||
fresh = Client()
|
||||
self.assertRedirects(
|
||||
fresh.post(
|
||||
reverse("panel:login"),
|
||||
{"username": "customer", "password": PASSWORD},
|
||||
),
|
||||
reverse("panel:factor_verify"),
|
||||
)
|
||||
self.assertNotIn("_auth_user_id", fresh.session)
|
||||
|
||||
def test_last_recovery_code_can_authorize_authenticator_replacement(self):
|
||||
original = TOTPDevice.objects.create(user=self.user, name=DEVICE_NAME)
|
||||
code = "b" * 20
|
||||
PanelRecoveryCode.objects.create(
|
||||
user=self.user, digest=secret_digest("recovery", code)
|
||||
)
|
||||
self.client.logout()
|
||||
self.client.post(
|
||||
reverse("panel:login"),
|
||||
{"username": "customer", "password": PASSWORD},
|
||||
)
|
||||
self.client.post(reverse("panel:factor_verify"), {"code": code})
|
||||
self.assertFalse(
|
||||
PanelRecoveryCode.objects.filter(user=self.user).exists()
|
||||
)
|
||||
|
||||
start = reverse("panel:account_authenticator")
|
||||
confirm = reverse("panel:account_authenticator_confirm")
|
||||
self.assertRedirects(
|
||||
self.client.post(start, {"password": PASSWORD}), confirm
|
||||
)
|
||||
self.assertTrue(TOTPDevice.objects.filter(pk=original.pk).exists())
|
||||
pending = TOTPDevice.objects.get(user=self.user, confirmed=False)
|
||||
token = f"{totp(pending.bin_key):06d}"
|
||||
self.assertContains(
|
||||
self.client.post(confirm, {"code": token}),
|
||||
"Save your recovery codes",
|
||||
)
|
||||
self.assertFalse(TOTPDevice.objects.filter(pk=original.pk).exists())
|
||||
self.assertEqual(
|
||||
PanelRecoveryCode.objects.filter(user=self.user).count(), 10
|
||||
)
|
||||
self.assertContains(
|
||||
self.client.get(self.profile), "Authenticator updated"
|
||||
)
|
||||
|
||||
def test_impersonation_cannot_open_account_settings(self):
|
||||
self.client.force_login(self.operator)
|
||||
started = timezone.now()
|
||||
impersonation = CustomerImpersonation.objects.create(
|
||||
operator=self.operator,
|
||||
customer=self.customer,
|
||||
operator_username=self.operator.username,
|
||||
customer_username=self.user.username,
|
||||
write_enabled=True,
|
||||
started_at=started,
|
||||
expires_at=started + SESSION_DURATION,
|
||||
)
|
||||
session = self.client.session
|
||||
session[SESSION_KEY] = impersonation.pk
|
||||
session.save()
|
||||
self.assertEqual(self.client.get(self.profile).status_code, 403)
|
||||
self.assertEqual(
|
||||
self.client.post(
|
||||
reverse("panel:account_other_sessions"), {"password": PASSWORD}
|
||||
).status_code,
|
||||
403,
|
||||
)
|
||||
self.assertFalse(PanelSecurityEvent.objects.exists())
|
||||
|
||||
def test_new_recovery_codes_invalidate_previous_codes(self):
|
||||
device = TOTPDevice.objects.create(user=self.user, name=DEVICE_NAME)
|
||||
self.authorize_factor(device)
|
||||
previous = PanelRecoveryCode.objects.create(
|
||||
user=self.user, digest=secret_digest("recovery", "b" * 20)
|
||||
)
|
||||
|
||||
response = self.client.post(
|
||||
reverse("panel:account_recovery_codes"),
|
||||
{"password": PASSWORD, "code": f"{totp(device.bin_key):06d}"},
|
||||
)
|
||||
self.assertContains(response, "Save your recovery codes")
|
||||
self.assertFalse(
|
||||
PanelRecoveryCode.objects.filter(pk=previous.pk).exists()
|
||||
)
|
||||
self.assertEqual(
|
||||
PanelRecoveryCode.objects.filter(user=self.user).count(), 10
|
||||
)
|
||||
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||
@@ -64,3 +64,41 @@ class HostingAccountSetupTests(TestCase):
|
||||
response = self.client.get(self.old_account.get_absolute_url())
|
||||
self.assertContains(response, "Copy website DNS records")
|
||||
self.assertContains(response, "existing.example.test A 192.0.2.21")
|
||||
|
||||
def test_guided_setup_applies_template_and_preserves_existing_zone(self):
|
||||
self.client.force_login(self.operator)
|
||||
template_url = reverse("panel:dns_defaults")
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
template_url,
|
||||
{
|
||||
"include_www": "on",
|
||||
"records": "_setup TXT check me",
|
||||
},
|
||||
),
|
||||
template_url,
|
||||
)
|
||||
account = self.old_account
|
||||
page = self.client.get(account.get_absolute_url())
|
||||
self.assertContains(page, "Proposed DNS zone")
|
||||
self.assertContains(page, "_setup.existing.example.test")
|
||||
setup = reverse("panel:account_setup", args=[account.pk])
|
||||
choices = {
|
||||
"setup_website": "on",
|
||||
"setup_dns": "on",
|
||||
"setup_email": "on",
|
||||
}
|
||||
for _ in range(2):
|
||||
self.assertRedirects(
|
||||
self.client.post(setup, choices), account.get_absolute_url()
|
||||
)
|
||||
self.assertEqual(account.webprovisioningplan_set.count(), 1)
|
||||
zone = account.dns_zones.get()
|
||||
self.assertEqual(zone.publication.state, "queued")
|
||||
self.assertNotIn(
|
||||
"*.existing.example.test",
|
||||
{record.name for record in zone.spec.addresses},
|
||||
)
|
||||
self.assertIn(
|
||||
"check me", {record.text for record in zone.spec.txt_records}
|
||||
)
|
||||
@@ -87,6 +87,34 @@ class DatabaseProvisioningTests(TestCase):
|
||||
self.assertEqual(self.client.post(self.url).status_code, 403)
|
||||
self.assertFalse(DatabaseProvisioning.objects.exists())
|
||||
|
||||
def test_customer_creation_queues_a_database_and_shows_its_status(self):
|
||||
self.client.force_login(self.user)
|
||||
url = reverse("panel:database_create", args=[self.account.pk])
|
||||
self.assertContains(self.client.get(url), "Add database")
|
||||
self.assertRedirects(
|
||||
self.client.post(url, {"suffix": "new"}), self.detail
|
||||
)
|
||||
job = DatabaseProvisioning.objects.get(database__suffix="new")
|
||||
self.assertEqual(job.state, "queued")
|
||||
self.assertContains(self.client.get(self.detail), "Queued")
|
||||
|
||||
def test_operator_without_provisioning_permission_creates_a_request(self):
|
||||
requester = get_user_model().objects.create_user("requester")
|
||||
requester.user_permissions.add(
|
||||
*self.permissions.exclude(codename="add_databaseprovisioning"),
|
||||
Permission.objects.get(codename="add_hostingdatabase"),
|
||||
)
|
||||
self.client.force_login(requester)
|
||||
url = reverse("panel:database_create", args=[self.account.pk])
|
||||
self.assertContains(self.client.get(url), "Request database")
|
||||
self.assertRedirects(
|
||||
self.client.post(url, {"suffix": "request"}), self.detail
|
||||
)
|
||||
self.assertTrue(
|
||||
self.account.databases.filter(suffix="request").exists()
|
||||
)
|
||||
self.assertFalse(DatabaseProvisioning.objects.exists())
|
||||
|
||||
@override_settings(LOCAL_DATABASE_PROVISIONING=False)
|
||||
def test_disabled_provisioning_preserves_existing_manifest_download(self):
|
||||
detail = self.client.get(self.detail)
|
||||
|
||||
@@ -42,6 +42,31 @@ class DnsPublicationTests(TestCase):
|
||||
self.url = reverse("panel:dns_zone_publish", args=[self.zone.pk])
|
||||
self.detail = self.account.get_absolute_url()
|
||||
|
||||
def test_creating_a_managed_zone_queues_its_first_snapshot(self):
|
||||
account = HostingAccount.objects.create(
|
||||
name="Example DNS", primary_domain="new.example"
|
||||
)
|
||||
url = reverse("panel:dns_zone_create", args=[account.pk])
|
||||
self.assertContains(self.client.get(url), "Save and publish zone")
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
url,
|
||||
{
|
||||
"nameservers": "ns.provider.example",
|
||||
"responsible_name": "hostmaster.new.example",
|
||||
"addresses": "new.example 192.0.2.20",
|
||||
},
|
||||
),
|
||||
account.get_absolute_url(),
|
||||
)
|
||||
zone = account.dns_zones.get()
|
||||
self.assertEqual(
|
||||
(zone.publication.state, zone.publication.serial), ("queued", 1)
|
||||
)
|
||||
self.assertEqual(
|
||||
DnsZone.from_manifest(zone.publication.manifest), zone.spec
|
||||
)
|
||||
|
||||
def test_queued_snapshot_survives_edits_and_next_revision_can_publish(
|
||||
self,
|
||||
):
|
||||
|
||||
@@ -167,6 +167,30 @@ class DnsZonePanelTests(TestCase):
|
||||
self.assertNotIn("mx_records", manifest)
|
||||
self.assertNotIn("txt_records", manifest)
|
||||
|
||||
def test_record_editor_validates_types_and_updates_the_zone(self):
|
||||
zone = self.create_zone()
|
||||
url = reverse("panel:dns_zone_edit", args=[zone.pk])
|
||||
base = self.client.get(url).context["form"].initial
|
||||
records = [{"name": "ns1", "type": "A", "value": "192.0.2.20"}]
|
||||
extra = {"name": "www", "type": "AAAA", "value": "192.0.2.21"}
|
||||
response = self.client.post(
|
||||
url, base | {"record_rows": json.dumps(records + [extra])}
|
||||
)
|
||||
self.assertContains(response, "Enter an IP address for a AAAA record")
|
||||
extra["value"] = "2001:db8::21"
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
url, base | {"record_rows": json.dumps(records + [extra])}
|
||||
),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
zone.refresh_from_db()
|
||||
self.assertEqual(zone.serial, 2)
|
||||
self.assertEqual(zone.spec.addresses[1].name, "www.account-a.example")
|
||||
self.assertContains(
|
||||
self.client.get(self.account.get_absolute_url()), "2001:db8::21"
|
||||
)
|
||||
|
||||
def test_invalid_mail_records_leave_existing_zone_unchanged(self):
|
||||
zone = self.create_zone()
|
||||
edit = reverse("panel:dns_zone_edit", args=[zone.pk])
|
||||
|
||||
@@ -196,7 +196,11 @@ class ResellerOnboardingTests(TestCase):
|
||||
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(resource.provisioning.state, "queued")
|
||||
self.assertContains(self.client.get(detail), "Queued")
|
||||
self.assertNotContains(
|
||||
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)
|
||||
@@ -208,7 +212,7 @@ class ResellerOnboardingTests(TestCase):
|
||||
"action", flat=True
|
||||
)
|
||||
),
|
||||
[Action.RESOURCE_REQUEST] * 2 + [Action.RESOURCE_PROVISION] * 2,
|
||||
[Action.RESOURCE_REQUEST, Action.RESOURCE_PROVISION] * 2,
|
||||
)
|
||||
DatabaseProvisioning.objects.update(
|
||||
finished_at=timezone.now(), problem="Failed"
|
||||
|
||||
@@ -20,7 +20,7 @@ from coulobre.service_health import (
|
||||
main,
|
||||
)
|
||||
|
||||
from .models import Customer, Reseller, ServiceHealth
|
||||
from .models import Customer, DnsZoneDefaults, Reseller, ServiceHealth
|
||||
|
||||
TARGETS = (
|
||||
HealthTarget("panel-01", "local", ("mariadb", "apache")),
|
||||
@@ -196,6 +196,24 @@ class ServiceHealthPanelTests(TestCase):
|
||||
self.assertNotContains(response, "test-only-bridge-key")
|
||||
self.assertNotContains(response, "https://webmail.example.net")
|
||||
|
||||
@override_settings(
|
||||
LOCAL_DNS_PUBLISHING=True,
|
||||
HOSTING_NAMESERVERS=(),
|
||||
HOSTING_PUBLIC_ADDRESSES=(),
|
||||
)
|
||||
def test_installation_reports_dns_defaults_saved_in_the_panel(self):
|
||||
DnsZoneDefaults.objects.create(
|
||||
pk=1, nameservers=["ns.example.net"], addresses=["192.0.2.20"]
|
||||
)
|
||||
self.client.force_login(self.admin)
|
||||
response = self.client.get(reverse("panel:installation"))
|
||||
self.assertTrue(
|
||||
dict(response.context["features"])[
|
||||
"Default managed DNS zones for new accounts"
|
||||
]
|
||||
)
|
||||
self.assertContains(response, "Configure DNS defaults")
|
||||
|
||||
def test_view_marks_missing_and_old_observations_distinctly(self):
|
||||
now = timezone.now()
|
||||
for node, service, result, observed_at in (
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import json
|
||||
import socket
|
||||
from importlib.metadata import PackageNotFoundError, version
|
||||
|
||||
from django import forms
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.mixins import UserPassesTestMixin
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import FormView
|
||||
|
||||
from coulobre.linked_updates import staged_for_release
|
||||
from coulobre.local_update import SOCKET
|
||||
from coulobre.release_updates import (
|
||||
UpdateError,
|
||||
available_releases,
|
||||
version_key,
|
||||
)
|
||||
|
||||
|
||||
class UpdateForm(forms.Form):
|
||||
version = forms.CharField(max_length=32, widget=forms.HiddenInput)
|
||||
sha256 = forms.RegexField(
|
||||
regex=r"\A[0-9a-f]{64}\Z", widget=forms.HiddenInput
|
||||
)
|
||||
confirm = forms.BooleanField(
|
||||
label="I reviewed this release and want to update this server."
|
||||
)
|
||||
|
||||
|
||||
def request_updater(payload, *, timeout=6):
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(timeout)
|
||||
peer.connect(str(SOCKET))
|
||||
peer.sendall(json.dumps(payload).encode() + b"\n")
|
||||
with peer.makefile("rb") as reply:
|
||||
result = json.loads(reply.readline(4096))
|
||||
if not isinstance(result, dict) or result.get("accepted") is not True:
|
||||
message = result.get("message") if isinstance(result, dict) else None
|
||||
raise UpdateError(message or "The local updater could not be reached.")
|
||||
return result
|
||||
|
||||
|
||||
def inspect_linked_nodes():
|
||||
try:
|
||||
return request_updater({"action": "linked-nodes"}, timeout=10)
|
||||
except (OSError, ValueError, UpdateError) as error:
|
||||
return {
|
||||
"problem": str(error)
|
||||
if isinstance(error, UpdateError)
|
||||
else "The linked node preflight is unavailable."
|
||||
}
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class UpdateView(UserPassesTestMixin, FormView):
|
||||
form_class = UpdateForm
|
||||
template_name = "hosting/updates.html"
|
||||
success_url = reverse_lazy("panel:updates")
|
||||
|
||||
def test_func(self):
|
||||
return self.request.user.is_superuser
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context["updater_enabled"] = SOCKET.is_socket()
|
||||
context["may_apply"] = self.request.user.is_verified()
|
||||
try:
|
||||
installed = version("coulobre-panel")
|
||||
except PackageNotFoundError:
|
||||
context["catalog_problem"] = (
|
||||
"The installed release version is unavailable."
|
||||
)
|
||||
return context
|
||||
context["installed_version"] = installed
|
||||
if context["updater_enabled"]:
|
||||
if self.request.GET.get("refresh") == "1":
|
||||
cache.delete(f"coulobre-updates:{installed}")
|
||||
cache.delete("coulobre-update-linked-nodes")
|
||||
topology = cache.get_or_set(
|
||||
"coulobre-update-linked-nodes",
|
||||
inspect_linked_nodes,
|
||||
timeout=30,
|
||||
)
|
||||
nodes = topology.get("nodes", [])
|
||||
context["update_status"] = topology.get("status", {})
|
||||
context["linked_nodes"] = nodes
|
||||
context["preflight_problem"] = topology.get("problem")
|
||||
try:
|
||||
context["releases"] = cache.get_or_set(
|
||||
f"coulobre-updates:{installed}",
|
||||
lambda: available_releases(installed),
|
||||
timeout=300,
|
||||
)
|
||||
if not context["preflight_problem"]:
|
||||
context["applyable_versions"] = {
|
||||
release.version
|
||||
for release in context["releases"]
|
||||
if all(
|
||||
staged_for_release(node, release.version)
|
||||
for node in nodes
|
||||
)
|
||||
}
|
||||
except UpdateError as error:
|
||||
context["catalog_problem"] = str(error)
|
||||
return context
|
||||
|
||||
def form_valid(self, form):
|
||||
if not self.request.user.is_verified():
|
||||
raise PermissionDenied
|
||||
payload = {
|
||||
"version": form.cleaned_data["version"],
|
||||
"sha256": form.cleaned_data["sha256"],
|
||||
"actor": self.request.user.get_username(),
|
||||
}
|
||||
try:
|
||||
version_key(payload["version"])
|
||||
request_updater(payload, timeout=10)
|
||||
cache.delete("coulobre-update-linked-nodes")
|
||||
except (OSError, ValueError):
|
||||
form.add_error(
|
||||
None,
|
||||
"The local updater could not be reached. "
|
||||
"Check its socket and service logs.",
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
except UpdateError as error:
|
||||
form.add_error(None, str(error))
|
||||
return self.form_invalid(form)
|
||||
messages.success(
|
||||
self.request,
|
||||
"Update accepted. Check this page again after the panel restarts.",
|
||||
)
|
||||
return super().form_valid(form)
|
||||
@@ -2,8 +2,19 @@ from django.contrib.auth.views import LogoutView
|
||||
from django.urls import path
|
||||
|
||||
from . import themes, views
|
||||
from .account_security import (
|
||||
AccountSecurityView,
|
||||
ChangeEmailView,
|
||||
ChangePasswordView,
|
||||
ConfirmAuthenticatorView,
|
||||
ReplaceRecoveryCodesView,
|
||||
SignOutOtherSessionsView,
|
||||
StartAuthenticatorView,
|
||||
VerifyEmailView,
|
||||
)
|
||||
from .backup_restores import RestoreKind
|
||||
from .credential_views import DatabaseCredentialView, MailboxCredentialView
|
||||
from .dns_defaults_views import DnsDefaultsView
|
||||
from .dns_replica_views import DnsReplicaView
|
||||
from .health_views import ServiceHealthView
|
||||
from .independent_website_views import (
|
||||
@@ -46,6 +57,7 @@ from .sign_in import (
|
||||
PanelLoginView,
|
||||
VerifyFactorView,
|
||||
)
|
||||
from .update_views import UpdateView
|
||||
from .website_file_views import WebsiteFilesView
|
||||
from .website_job_views import WebsiteJobEditor, WebsiteJobList
|
||||
from .website_usage_views import WebsiteUsageView
|
||||
@@ -54,6 +66,13 @@ app_name = "panel"
|
||||
|
||||
urlpatterns = [
|
||||
path("panel-theme.css", themes.stylesheet, name="theme_stylesheet"),
|
||||
path("updates/", UpdateView.as_view(), name="updates"),
|
||||
path("dns-template/", DnsDefaultsView.as_view(), name="dns_defaults"),
|
||||
path(
|
||||
"accounts/<int:pk>/setup/",
|
||||
views.ExistingAccountSetup.as_view(),
|
||||
name="account_setup",
|
||||
),
|
||||
path(
|
||||
"dns-zones/<int:pk>/replication/",
|
||||
DnsReplicaView.as_view(),
|
||||
@@ -106,6 +125,40 @@ urlpatterns = [
|
||||
name="password_reset_complete",
|
||||
),
|
||||
path("sign-out/", LogoutView.as_view(), name="logout"),
|
||||
path(
|
||||
"my-account/", AccountSecurityView.as_view(), name="account_security"
|
||||
),
|
||||
path(
|
||||
"my-account/password/",
|
||||
ChangePasswordView.as_view(),
|
||||
name="account_password",
|
||||
),
|
||||
path("my-account/email/", ChangeEmailView.as_view(), name="account_email"),
|
||||
path(
|
||||
"my-account/email/verify/",
|
||||
VerifyEmailView.as_view(),
|
||||
name="account_email_verify",
|
||||
),
|
||||
path(
|
||||
"my-account/authenticator/",
|
||||
StartAuthenticatorView.as_view(),
|
||||
name="account_authenticator",
|
||||
),
|
||||
path(
|
||||
"my-account/authenticator/verify/",
|
||||
ConfirmAuthenticatorView.as_view(),
|
||||
name="account_authenticator_confirm",
|
||||
),
|
||||
path(
|
||||
"my-account/recovery-codes/",
|
||||
ReplaceRecoveryCodesView.as_view(),
|
||||
name="account_recovery_codes",
|
||||
),
|
||||
path(
|
||||
"my-account/sessions/",
|
||||
SignOutOtherSessionsView.as_view(),
|
||||
name="account_other_sessions",
|
||||
),
|
||||
path(
|
||||
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
|
||||
),
|
||||
|
||||
+288
-35
@@ -15,6 +15,7 @@ from django.http import (
|
||||
)
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.urls import reverse, reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.functional import cached_property
|
||||
from django.views import View
|
||||
from django.views.generic import (
|
||||
@@ -27,8 +28,10 @@ from django.views.generic import (
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL
|
||||
from coulobre.mail_dns import MANAGED_DKIM_SELECTOR, matches_version
|
||||
from coulobre.mail_node import INVALID_LOCAL_PART
|
||||
from coulobre.php_runtime import available_php_versions
|
||||
from coulobre.service_health import HealthResult
|
||||
from coulobre.sftp_keys import public_key_fingerprint
|
||||
|
||||
from .access import (
|
||||
@@ -53,7 +56,7 @@ from .account_backups import (
|
||||
queue_account_backup,
|
||||
save_backup_schedule,
|
||||
)
|
||||
from .account_setup import setup_new_account, website_records
|
||||
from .account_setup import default_dns_zone, setup_new_account, website_records
|
||||
from .backup_restores import (
|
||||
RestoreKind,
|
||||
available_restore_resources,
|
||||
@@ -66,8 +69,15 @@ from .backup_restores import (
|
||||
retry_remote_mail_restore,
|
||||
)
|
||||
from .backup_retention import change_backup_retention, protect_backup
|
||||
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
|
||||
from .dns_defaults import zone_defaults
|
||||
from .dns_forms import (
|
||||
DnsZoneEditForm,
|
||||
DnsZoneForm,
|
||||
zone_form_initial,
|
||||
zone_record_rows,
|
||||
)
|
||||
from .dns_publication import queue_dns_publication
|
||||
from .health_views import STALE_AFTER
|
||||
from .impersonation import (
|
||||
CUSTOMER_WRITE_PERMISSIONS,
|
||||
EndReason,
|
||||
@@ -97,6 +107,7 @@ from .models import (
|
||||
HostingMailbox,
|
||||
HostingPlan,
|
||||
Reseller,
|
||||
ServiceHealth,
|
||||
WebProvisioningPlan,
|
||||
WebsiteAlias,
|
||||
WebsiteDomain,
|
||||
@@ -135,6 +146,7 @@ from .resource_requests import (
|
||||
queue_site_storage_limit,
|
||||
queue_site_storage_measurement,
|
||||
queue_web_https,
|
||||
require_active_services,
|
||||
require_open_account,
|
||||
)
|
||||
from .retirement_views import RETIRE_ACCOUNTS
|
||||
@@ -226,6 +238,121 @@ PROVISION_MAILBOX = (
|
||||
CHANGE_MAILBOX_QUOTA = (*PROVISION_MAILBOX, "hosting.change_hostingmailbox")
|
||||
|
||||
|
||||
def automatic_resource_provisioning(user, enabled, permissions):
|
||||
return enabled and (is_tenant(user) or user.has_perms(permissions))
|
||||
|
||||
|
||||
def missing_account_setup(account, actor):
|
||||
if is_tenant(actor) or account.services_suspended:
|
||||
return ()
|
||||
domain = account.primary_domain
|
||||
defaults = zone_defaults()
|
||||
options = []
|
||||
if (
|
||||
settings.LOCAL_WEB_ACTIVATION
|
||||
and actor.has_perms(ACTIVATE_WEB)
|
||||
and not account.webprovisioningplan_set.filter(
|
||||
primary_domain=domain, activation__isnull=False
|
||||
).exists()
|
||||
):
|
||||
options.append(("setup_website", "Set up the primary website"))
|
||||
if (
|
||||
settings.LOCAL_DNS_PUBLISHING
|
||||
and defaults.nameservers
|
||||
and defaults.addresses
|
||||
and actor.has_perms((*PUBLISH_DNS, "hosting.add_hostingdnszone"))
|
||||
and not HostingDnsZone.objects.filter(domain=domain).exists()
|
||||
):
|
||||
options.append(("setup_dns", "Publish a Coulobre DNS zone"))
|
||||
if (
|
||||
settings.LOCAL_MAILBOX_PROVISIONING
|
||||
and settings.MANAGE_MAIL_DNS
|
||||
and actor.has_perms(PROVISION_MAILBOX)
|
||||
and not account.mail_domains.filter(domain=domain).exists()
|
||||
):
|
||||
options.append(("setup_email", "Set up the managed mail domain"))
|
||||
return options
|
||||
|
||||
|
||||
class ExistingAccountSetup(
|
||||
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
||||
):
|
||||
permission_required = (VIEW_ACCOUNTS, CHANGE_ACCOUNTS)
|
||||
template_name = "hosting/account_setup.html"
|
||||
form_class = forms.Form
|
||||
|
||||
@cached_property
|
||||
def account(self):
|
||||
return get_object_or_404(
|
||||
HostingAccount, pk=self.kwargs["pk"], retired_at__isnull=True
|
||||
)
|
||||
|
||||
def get_form(self, form_class=None):
|
||||
form = super().get_form(form_class)
|
||||
options = missing_account_setup(self.account, self.request.user)
|
||||
for name, label in options:
|
||||
form.fields[name] = forms.BooleanField(
|
||||
label=label, initial=True, required=False
|
||||
)
|
||||
if "setup_website" in form.fields:
|
||||
form.fields["setup_landing_page"] = forms.BooleanField(
|
||||
label="Add a starter page if the web root is empty",
|
||||
required=False,
|
||||
)
|
||||
return form
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(account=self.account, **kwargs)
|
||||
form = context["form"]
|
||||
if "setup_dns" in form.fields:
|
||||
try:
|
||||
draft = default_dns_zone(
|
||||
self.account,
|
||||
managed_mail=(
|
||||
"setup_email" in form.fields
|
||||
and bool(form["setup_email"].value())
|
||||
)
|
||||
or (
|
||||
settings.MANAGE_MAIL_DNS
|
||||
and self.account.mail_domains.filter(
|
||||
domain=self.account.primary_domain
|
||||
).exists()
|
||||
),
|
||||
)
|
||||
if draft is not None:
|
||||
context["preview_records"] = zone_record_rows(draft.spec)
|
||||
except (ValidationError, ValueError) as error:
|
||||
context["preview_problem"] = str(error)
|
||||
return context
|
||||
|
||||
def form_valid(self, form):
|
||||
try:
|
||||
with transaction.atomic():
|
||||
account = lock_hosting_account(
|
||||
self.account.pk, customer_id=None
|
||||
)
|
||||
require_active_services(account)
|
||||
available = dict(
|
||||
missing_account_setup(account, self.request.user)
|
||||
)
|
||||
options = {
|
||||
name: selected
|
||||
for name, selected in form.cleaned_data.items()
|
||||
if name in available or name == "setup_landing_page"
|
||||
}
|
||||
if any(options.get(name) for name in available):
|
||||
defaults = zone_defaults()
|
||||
options.update(
|
||||
setup_www=defaults.include_www,
|
||||
setup_wildcard=defaults.include_wildcard,
|
||||
)
|
||||
setup_new_account(account, options)
|
||||
except ValidationError as error:
|
||||
form.add_error(None, error)
|
||||
return self.form_invalid(form)
|
||||
return redirect(self.account)
|
||||
|
||||
|
||||
class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
|
||||
queryset = (
|
||||
HostingAccount.objects.filter(retired_at__isnull=True)
|
||||
@@ -261,6 +388,7 @@ class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(search=self.search, **kwargs)
|
||||
context["show_customer_website_link"] = settings.WEBSITE_USAGE
|
||||
reseller = reseller_for_user(self.request.user)
|
||||
if reseller is not None:
|
||||
context["account_allowance"] = {
|
||||
@@ -268,6 +396,28 @@ class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
|
||||
"limit": reseller.account_limit,
|
||||
"may_create": reseller.may_create_accounts(),
|
||||
}
|
||||
elif (
|
||||
not self.request.GET
|
||||
and not is_tenant(self.request.user)
|
||||
and self.request.user.has_perm("hosting.view_servicehealth")
|
||||
):
|
||||
targets = settings.SERVICE_HEALTH_TARGETS
|
||||
checks = {
|
||||
(node.node, service)
|
||||
for node in targets
|
||||
for service in node.services
|
||||
}
|
||||
healthy = set(
|
||||
ServiceHealth.objects.filter(
|
||||
node__in={node.node for node in targets},
|
||||
result=HealthResult.ACTIVE,
|
||||
observed_at__gt=timezone.now() - STALE_AFTER,
|
||||
).values_list("node", "service")
|
||||
)
|
||||
context["health_summary"] = {
|
||||
"configured": len(checks),
|
||||
"needs_attention": len(checks - healthy),
|
||||
}
|
||||
return context
|
||||
|
||||
|
||||
@@ -306,6 +456,8 @@ class AccountEditor:
|
||||
field.queryset = field.queryset.select_related(
|
||||
"user"
|
||||
).order_by("user__username")
|
||||
if "reseller" in form.fields:
|
||||
form.fields["reseller"].label = "Customer manager"
|
||||
return form
|
||||
|
||||
|
||||
@@ -328,13 +480,14 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
|
||||
form = super().get_form(form_class)
|
||||
actor = self.request.user
|
||||
reseller = reseller_for_user(actor) is not None
|
||||
defaults = zone_defaults()
|
||||
web = settings.LOCAL_WEB_ACTIVATION and (
|
||||
reseller or actor.has_perms(ACTIVATE_WEB)
|
||||
)
|
||||
dns = (
|
||||
settings.LOCAL_DNS_PUBLISHING
|
||||
and settings.HOSTING_NAMESERVERS
|
||||
and settings.HOSTING_PUBLIC_ADDRESSES
|
||||
and defaults.nameservers
|
||||
and defaults.addresses
|
||||
and (
|
||||
reseller
|
||||
or actor.has_perms(
|
||||
@@ -361,7 +514,12 @@ class AccountCreate(PermissionRequiredMixin, AccountEditor, CreateView):
|
||||
for name, (available, label) in choices.items():
|
||||
if available:
|
||||
form.fields[name] = forms.BooleanField(
|
||||
label=label, initial=True, required=False
|
||||
label=label,
|
||||
initial={
|
||||
"setup_www": defaults.include_www,
|
||||
"setup_wildcard": defaults.include_wildcard,
|
||||
}.get(name, True),
|
||||
required=False,
|
||||
)
|
||||
return form
|
||||
|
||||
@@ -449,6 +607,11 @@ 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
|
||||
context["offer_account_setup"] = (
|
||||
not tenant
|
||||
and user.has_perm(CHANGE_ACCOUNTS)
|
||||
and bool(missing_account_setup(self.object, user))
|
||||
)
|
||||
context["show_website_usage"] = settings.WEBSITE_USAGE and (
|
||||
tenant or user.has_perm("hosting.view_websiteusage")
|
||||
)
|
||||
@@ -665,11 +828,17 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
"show_mailbox_credentials"
|
||||
] and roundcube_available(self.request)
|
||||
if tenant or user.has_perm(VIEW_DATABASES):
|
||||
databases = self.object.databases.all()
|
||||
context["automatic_database_provisioning"] = (
|
||||
automatic_resource_provisioning(
|
||||
user,
|
||||
settings.LOCAL_DATABASE_PROVISIONING,
|
||||
PROVISION_DATABASE,
|
||||
)
|
||||
)
|
||||
databases = self.object.databases.select_related("provisioning")
|
||||
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"] = (
|
||||
settings.LOCAL_DATABASE_PROVISIONING
|
||||
@@ -693,6 +862,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
context["local_dns_enabled"] = settings.LOCAL_DNS_PUBLISHING
|
||||
zones = list(zone_list)
|
||||
context["dns_zones"] = zones
|
||||
context["dns_zone_records"] = [
|
||||
(zone, zone_record_rows(zone.spec)) for zone in zones
|
||||
]
|
||||
primary_zone = next(
|
||||
(
|
||||
zone
|
||||
@@ -704,6 +876,21 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
context["has_primary_zone"] = primary_zone is not None
|
||||
if primary_zone is None:
|
||||
context["dns_readiness"] = "No managed zone"
|
||||
if not tenant and settings.LOCAL_DNS_PUBLISHING:
|
||||
try:
|
||||
draft = default_dns_zone(
|
||||
self.object,
|
||||
managed_mail=settings.MANAGE_MAIL_DNS
|
||||
and self.object.mail_domains.filter(
|
||||
domain=self.object.primary_domain
|
||||
).exists(),
|
||||
)
|
||||
if draft is not None:
|
||||
context["default_zone_records"] = zone_record_rows(
|
||||
draft.spec
|
||||
)
|
||||
except (ValidationError, ValueError) as error:
|
||||
context["default_zone_problem"] = str(error)
|
||||
context["external_website_dns"] = "\n".join(
|
||||
f"{record.name} {record.record_type} {record.address}"
|
||||
for record in website_records(self.object.primary_domain)
|
||||
@@ -714,6 +901,13 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
publication, "Ready to publish", "Published"
|
||||
)
|
||||
if tenant or user.has_perm(VIEW_MAILBOXES):
|
||||
context["automatic_mailbox_provisioning"] = (
|
||||
automatic_resource_provisioning(
|
||||
user,
|
||||
settings.LOCAL_MAILBOX_PROVISIONING,
|
||||
PROVISION_MAILBOX,
|
||||
)
|
||||
)
|
||||
context["manage_mail_routing"] = mail_policy_enabled(
|
||||
self.request, "routing"
|
||||
)
|
||||
@@ -730,11 +924,10 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
)
|
||||
mailboxes = HostingMailbox.objects.filter(
|
||||
mail_domain__account=self.object
|
||||
).select_related("mail_domain")
|
||||
).select_related("mail_domain", "provisioning")
|
||||
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
|
||||
@@ -1747,6 +1940,8 @@ def provisioning_conflict(error):
|
||||
|
||||
class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
|
||||
audit_operation = None
|
||||
provisioning_setting = None
|
||||
provisioning_permissions = ()
|
||||
|
||||
@cached_property
|
||||
def customer(self):
|
||||
@@ -1774,9 +1969,23 @@ class ResourceRequestCreate(PermissionRequiredMixin, CreateView):
|
||||
return super().get_context_data(
|
||||
account=self.account,
|
||||
can_request_resource=can_edit_customer_resource(self.request),
|
||||
auto_provision=self.auto_provision,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@cached_property
|
||||
def auto_provision(self):
|
||||
return automatic_resource_provisioning(
|
||||
self.request.user,
|
||||
getattr(settings, self.provisioning_setting),
|
||||
self.provisioning_permissions,
|
||||
)
|
||||
|
||||
def create_request(self, account_id, **values):
|
||||
return self.create_resource(
|
||||
account_id, auto_provision=self.auto_provision, **values
|
||||
)
|
||||
|
||||
def get_form(self, form_class=None):
|
||||
form = super().get_form(form_class)
|
||||
if not can_edit_customer_resource(self.request):
|
||||
@@ -1823,7 +2032,9 @@ class DatabaseCreate(ResourceRequestCreate):
|
||||
template_name = "hosting/database_form.html"
|
||||
permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:database_create"]
|
||||
audit_operation = CustomerImpersonationAction.Operation.DATABASE
|
||||
create_request = staticmethod(create_database_request)
|
||||
provisioning_setting = "LOCAL_DATABASE_PROVISIONING"
|
||||
provisioning_permissions = PROVISION_DATABASE
|
||||
create_resource = staticmethod(create_database_request)
|
||||
|
||||
|
||||
class DownloadDatabaseManifest(
|
||||
@@ -1927,7 +2138,33 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
|
||||
return self.account.primary_domain
|
||||
|
||||
def get_initial(self):
|
||||
return {"responsible_name": f"hostmaster.{self.domain}"}
|
||||
try:
|
||||
draft = default_dns_zone(
|
||||
self.account,
|
||||
managed_mail=settings.MANAGE_MAIL_DNS
|
||||
and self.account.mail_domains.filter(
|
||||
domain=self.domain
|
||||
).exists(),
|
||||
)
|
||||
if draft is not None:
|
||||
return zone_form_initial(draft)
|
||||
except (ValidationError, ValueError):
|
||||
pass # The operator can still enter a manual zone.
|
||||
return {
|
||||
"responsible_name": f"hostmaster.{self.domain}",
|
||||
"record_rows": "[]",
|
||||
}
|
||||
|
||||
@cached_property
|
||||
def publish_on_create(self):
|
||||
return settings.LOCAL_DNS_PUBLISHING and self.request.user.has_perms(
|
||||
PUBLISH_DNS
|
||||
)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(
|
||||
publish_on_create=self.publish_on_create, **kwargs
|
||||
)
|
||||
|
||||
def form_valid(self, form):
|
||||
try:
|
||||
@@ -1936,12 +2173,14 @@ class DnsZoneCreate(OperatorOnlyMixin, DnsZoneEditor):
|
||||
self.account.pk, customer_id=None
|
||||
)
|
||||
require_open_account(account)
|
||||
HostingDnsZone.objects.create(
|
||||
zone = HostingDnsZone.objects.create(
|
||||
account=account,
|
||||
domain=account.primary_domain,
|
||||
**form.cleaned_data,
|
||||
)
|
||||
except ValidationError as error:
|
||||
if self.publish_on_create:
|
||||
queue_dns_publication(zone.pk, str(zone.serial))
|
||||
except (ValidationError, ValueError) as error:
|
||||
form.add_error(None, error)
|
||||
return self.form_invalid(form)
|
||||
except IntegrityError:
|
||||
@@ -1998,28 +2237,38 @@ class DnsZoneEdit(DnsZoneEditor):
|
||||
return self.zone.domain
|
||||
|
||||
def get_initial(self):
|
||||
return {
|
||||
"serial": self.zone.serial,
|
||||
"manage_mail_dns": self.zone.manage_mail_dns,
|
||||
"delegate_dns": self.zone.delegate_dns,
|
||||
"nameservers": "\n".join(self.zone.nameservers),
|
||||
"responsible_name": self.zone.responsible_name,
|
||||
"addresses": "\n".join(
|
||||
f"{record['name']} {record['address']}"
|
||||
for record in self.zone.addresses
|
||||
),
|
||||
"mx_records": "\n".join(
|
||||
f"{record['name']} {record['priority']} {record['exchange']}"
|
||||
for record in self.zone.mx_records
|
||||
),
|
||||
"txt_records": "\n".join(
|
||||
format_txt_record(record) for record in self.zone.txt_records
|
||||
),
|
||||
"extra_records": "\n".join(
|
||||
f"{record['name']} {record['record_type']} {record['value']}"
|
||||
for record in self.zone.extra_records
|
||||
),
|
||||
return zone_form_initial(self.zone)
|
||||
|
||||
def check_managed_mail_records(self, values):
|
||||
if not (self.zone.manage_mail_dns and values["manage_mail_dns"]):
|
||||
return
|
||||
domains = set(
|
||||
self.account.mail_domains.values_list("domain", flat=True)
|
||||
)
|
||||
dmarc = {f"_dmarc.{domain}" for domain in domains}
|
||||
dkim = {
|
||||
f"{MANAGED_DKIM_SELECTOR}._domainkey.{domain}"
|
||||
for domain in domains
|
||||
}
|
||||
managed_txt = [
|
||||
txt
|
||||
for txt in self.zone.txt_records
|
||||
if txt["name"] in dkim
|
||||
or txt["name"] in dmarc
|
||||
and matches_version(txt["text"], "v=DMARC1")
|
||||
or txt["name"] in domains
|
||||
and matches_version(txt["text"], "v=spf1")
|
||||
]
|
||||
managed_mx = [
|
||||
mx for mx in self.zone.mx_records if mx["name"] in domains
|
||||
]
|
||||
if any(txt not in values["txt_records"] for txt in managed_txt) or any(
|
||||
mx not in values["mx_records"] for mx in managed_mx
|
||||
):
|
||||
raise ValidationError(
|
||||
"Keep the managed mail records or disable automatic mail DNS "
|
||||
"in Zone settings first."
|
||||
)
|
||||
|
||||
def form_valid(self, form):
|
||||
values = form.cleaned_data
|
||||
@@ -2037,6 +2286,7 @@ class DnsZoneEdit(DnsZoneEditor):
|
||||
self.account.pk, customer_id=None
|
||||
)
|
||||
require_open_account(account)
|
||||
self.check_managed_mail_records(values)
|
||||
zones = HostingDnsZone.objects.filter(
|
||||
pk=self.zone.pk, serial=serial
|
||||
)
|
||||
@@ -2120,7 +2370,10 @@ class MailboxCreate(ResourceRequestCreate):
|
||||
template_name = "hosting/mailbox_form.html"
|
||||
permission_required = CUSTOMER_WRITE_PERMISSIONS["panel:mailbox_create"]
|
||||
audit_operation = CustomerImpersonationAction.Operation.MAILBOX
|
||||
create_request = staticmethod(create_mailbox_request)
|
||||
|
||||
provisioning_setting = "LOCAL_MAILBOX_PROVISIONING"
|
||||
provisioning_permissions = PROVISION_MAILBOX
|
||||
create_resource = staticmethod(create_mailbox_request)
|
||||
|
||||
def get_form(self, form_class=None):
|
||||
form = super().get_form(form_class)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
from .node_files import read_root_file, require_root_directory
|
||||
from .node_probe import (
|
||||
PROBE_BYTES,
|
||||
PROBE_LIMIT,
|
||||
STATUS_PROBE_BYTES,
|
||||
parse_status_probe,
|
||||
)
|
||||
|
||||
ROLES = ("dns", "mail")
|
||||
LOCAL_MODES = {"local", "off"}
|
||||
REMOTE_MODES = {"remote", "remote-install"}
|
||||
RELAY_DIR = Path("/etc/coulobre-remote")
|
||||
UNIT_DIR = Path("/etc/systemd/system")
|
||||
|
||||
|
||||
def relay_is_installed(role):
|
||||
drop_in = UNIT_DIR / f"coulobre-{role}-apply@.service.d/remote.conf"
|
||||
require_root_directory(drop_in.parent)
|
||||
read_root_file(drop_in, mode=0o644)
|
||||
directory = RELAY_DIR / role
|
||||
require_root_directory(directory)
|
||||
for name in ("known_hosts", "ssh_config"):
|
||||
read_root_file(directory / name, mode=0o640)
|
||||
|
||||
|
||||
def read_probe(role, payload):
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(3)
|
||||
peer.connect(f"/run/coulobre-{role}-apply.sock")
|
||||
peer.sendall(payload)
|
||||
peer.shutdown(socket.SHUT_WR)
|
||||
with peer.makefile("rb") as stream:
|
||||
return stream.read(PROBE_LIMIT + 1)
|
||||
|
||||
|
||||
def receiver_status(role, host):
|
||||
status = {
|
||||
"role": role,
|
||||
"host": host,
|
||||
"release": None,
|
||||
"protocol": None,
|
||||
"state": "unavailable",
|
||||
"upgrade_target": None,
|
||||
}
|
||||
try:
|
||||
relay_is_installed(role)
|
||||
body = read_probe(role, STATUS_PROBE_BYTES)
|
||||
try:
|
||||
report = parse_status_probe(body, role)
|
||||
except ValueError:
|
||||
report = parse_status_probe(read_probe(role, PROBE_BYTES), role)
|
||||
except (ValueError, OSError):
|
||||
return status
|
||||
return status | report
|
||||
|
||||
|
||||
def linked_roles(plan):
|
||||
roles = []
|
||||
for role in ROLES:
|
||||
config = plan[role]
|
||||
mode = config["mode"]
|
||||
installed = (
|
||||
UNIT_DIR / f"coulobre-{role}-apply@.service.d/remote.conf"
|
||||
).exists()
|
||||
if mode in REMOTE_MODES:
|
||||
roles.append((role, config["host"]))
|
||||
elif (
|
||||
mode not in LOCAL_MODES or installed or (RELAY_DIR / role).exists()
|
||||
):
|
||||
raise ValueError("Check manually configured linked receivers.")
|
||||
if RELAY_DIR.exists() and any(
|
||||
child.name not in ROLES for child in RELAY_DIR.iterdir()
|
||||
):
|
||||
raise ValueError(
|
||||
"Use the manual procedure for additional remote mail services."
|
||||
)
|
||||
return roles
|
||||
|
||||
|
||||
def staged_for_release(node, target):
|
||||
return (
|
||||
node["protocol"] == 2
|
||||
and node["state"] == "maintenance"
|
||||
and node["release"] == target == node["upgrade_target"]
|
||||
)
|
||||
@@ -0,0 +1,551 @@
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from datetime import UTC, datetime
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
from pwd import getpwnam
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from .linked_updates import linked_roles, receiver_status, staged_for_release
|
||||
from .release_updates import (
|
||||
SHA256,
|
||||
UpdateError,
|
||||
download_wheel,
|
||||
selected_release,
|
||||
version_key,
|
||||
)
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SOCKET = Path("/run/coulobre-update.sock")
|
||||
STATE = Path("/var/lib/coulobre-update")
|
||||
STATUS = STATE / "status.json"
|
||||
LOCK = STATE / "update.lock"
|
||||
PANEL = "coulobre-panel.service"
|
||||
BEAT = "coulobre-beat.service"
|
||||
WORKER = "coulobre-worker.service"
|
||||
MANAGED_UNITS = frozenset(
|
||||
{
|
||||
PANEL,
|
||||
BEAT,
|
||||
WORKER,
|
||||
"coulobre-health.timer",
|
||||
"coulobre-account-backup.socket",
|
||||
"coulobre-account-offsite.socket",
|
||||
"coulobre-account-restore.socket",
|
||||
"coulobre-backup-worker.service",
|
||||
"coulobre-database-apply.socket",
|
||||
"coulobre-database-provisioner.service",
|
||||
"coulobre-dns-apply.socket",
|
||||
"coulobre-dns-publisher.service",
|
||||
"coulobre-https-apply.socket",
|
||||
"coulobre-https-provisioner.service",
|
||||
"coulobre-mail-apply.socket",
|
||||
"coulobre-mail-archive-backup.socket",
|
||||
"coulobre-mail-archive-restore.socket",
|
||||
"coulobre-mail-credentials.socket",
|
||||
"coulobre-mailbox-provisioner.service",
|
||||
"coulobre-offsite-worker.service",
|
||||
"coulobre-provisioner.service",
|
||||
"coulobre-service-credentials.socket",
|
||||
"coulobre-sftp-apply.socket",
|
||||
"coulobre-sftp-provisioner.service",
|
||||
"coulobre-web-apply.socket",
|
||||
"coulobre-website-files.socket",
|
||||
"coulobre-website-job-worker.service",
|
||||
"coulobre-website-jobs.socket",
|
||||
"coulobre-website-usage.socket",
|
||||
}
|
||||
)
|
||||
VENV = Path("/opt/coulobre")
|
||||
PYTHON = VENV / "bin/python"
|
||||
CONFIG = Path("/etc/coulobre/panel.env")
|
||||
INSTALLATION = Path("/var/lib/coulobre-installer/installation.json")
|
||||
ROOT_COMMAND_ENV = {
|
||||
"PATH": "/usr/sbin:/usr/bin:/sbin:/bin",
|
||||
"LC_ALL": "C.UTF-8",
|
||||
}
|
||||
|
||||
|
||||
def read_status():
|
||||
try:
|
||||
payload = json.loads(STATUS.read_text())
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def publish_status(status, state, message):
|
||||
status.update(
|
||||
state=state, message=message, updated_at=datetime.now(UTC).isoformat()
|
||||
)
|
||||
staged = STATUS.with_suffix(".new")
|
||||
with staged.open("w", encoding="utf-8") as stream:
|
||||
json.dump(status, stream)
|
||||
stream.write("\n")
|
||||
os.fchmod(stream.fileno(), 0o600)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
staged.replace(STATUS)
|
||||
directory = os.open(STATUS.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
if state != "running":
|
||||
LOGGER.info(
|
||||
"Update %s for %s requested by %s. %s",
|
||||
state,
|
||||
status.get("target_version"),
|
||||
status.get("actor"),
|
||||
message,
|
||||
)
|
||||
|
||||
|
||||
def display_status():
|
||||
status = read_status()
|
||||
if status.get("state") == "running":
|
||||
try:
|
||||
with LOCK.open("rb") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
status = read_status()
|
||||
if status.get("state") == "running":
|
||||
status.update(
|
||||
state="recovery_required",
|
||||
message=(
|
||||
"The update was interrupted. "
|
||||
"Review the recovery files."
|
||||
),
|
||||
)
|
||||
except OSError:
|
||||
pass # The worker holds the lock, or the updater is unavailable.
|
||||
return status
|
||||
|
||||
|
||||
def root_controlled(path):
|
||||
info = path.lstat()
|
||||
return (
|
||||
info.st_uid == 0
|
||||
and not info.st_mode & 0o022
|
||||
and not stat.S_ISLNK(info.st_mode)
|
||||
)
|
||||
|
||||
|
||||
def installation_plan():
|
||||
try:
|
||||
if not all(
|
||||
root_controlled(path) for path in (VENV, CONFIG, INSTALLATION)
|
||||
):
|
||||
raise ValueError
|
||||
installation = json.loads(INSTALLATION.read_text())
|
||||
if (
|
||||
installation.get("complete") is not True
|
||||
or os.environ.get("COULOBRE_DB_NAME") != "coulobre_panel"
|
||||
or os.environ.get("COULOBRE_DB_HOST") != "/run/mysqld/mysqld.sock"
|
||||
):
|
||||
raise ValueError
|
||||
return installation["plan"]
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
raise UpdateError(
|
||||
"Web updates require a complete installer-managed panel "
|
||||
"with a local MariaDB database."
|
||||
) from error
|
||||
|
||||
|
||||
def linked_status(plan):
|
||||
try:
|
||||
roles = linked_roles(plan)
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
raise UpdateError(
|
||||
"Use the manual upgrade procedure for this remote configuration."
|
||||
) from error
|
||||
return [receiver_status(role, host) for role, host in roles]
|
||||
|
||||
|
||||
def check_installation(target):
|
||||
plan = installation_plan()
|
||||
if not all(
|
||||
staged_for_release(node, target) for node in linked_status(plan)
|
||||
):
|
||||
raise UpdateError(
|
||||
"Stage every linked receiver at the selected release before "
|
||||
"upgrading the panel."
|
||||
)
|
||||
return plan["hostname"]
|
||||
|
||||
|
||||
def run(*args, log, timeout=900, stdout=None, umask=-1):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
check=True,
|
||||
timeout=timeout,
|
||||
env=ROOT_COMMAND_ENV,
|
||||
stdout=stdout if stdout is not None else subprocess.PIPE,
|
||||
stderr=log,
|
||||
stdin=subprocess.DEVNULL,
|
||||
umask=umask,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise UpdateError(
|
||||
f"{Path(args[0]).name} failed. Check the private update log."
|
||||
) from error
|
||||
return (result.stdout or b"").decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def active_units(log):
|
||||
listing = run(
|
||||
"/usr/bin/systemctl",
|
||||
"list-units",
|
||||
"--state=active,activating",
|
||||
"--plain",
|
||||
"--no-legend",
|
||||
"--full",
|
||||
"coulobre-*",
|
||||
log=log,
|
||||
)
|
||||
return [
|
||||
unit
|
||||
for line in listing.splitlines()
|
||||
if line.strip()
|
||||
if (unit := line.split()[0]) in MANAGED_UNITS
|
||||
]
|
||||
|
||||
|
||||
def systemctl(action, units, log):
|
||||
if units:
|
||||
run("/usr/bin/systemctl", action, *units, log=log)
|
||||
|
||||
|
||||
def manage(*args, log):
|
||||
run(
|
||||
"/usr/bin/systemd-run",
|
||||
"--wait",
|
||||
"--pipe",
|
||||
"--collect",
|
||||
"--quiet",
|
||||
"--uid=coulobre-panel",
|
||||
"--property=EnvironmentFile=/etc/coulobre/panel.env",
|
||||
PYTHON,
|
||||
"-m",
|
||||
"django",
|
||||
*args,
|
||||
log=log,
|
||||
)
|
||||
|
||||
|
||||
def verify_panel(hostname, release, log):
|
||||
installed = run(
|
||||
PYTHON,
|
||||
"-c",
|
||||
"from importlib.metadata import version; "
|
||||
"print(version('coulobre-panel'))",
|
||||
log=log,
|
||||
).strip()
|
||||
if installed != release.version:
|
||||
raise UpdateError(
|
||||
"The installed version differs from the selected release."
|
||||
)
|
||||
request = (
|
||||
f"GET /sign-in/ HTTP/1.0\r\nHost: {hostname}\r\n"
|
||||
"X-Forwarded-Proto: https\r\n\r\n"
|
||||
)
|
||||
for _ in range(20):
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(2)
|
||||
peer.connect("/run/coulobre-panel/panel.sock")
|
||||
peer.sendall(request.encode("ascii"))
|
||||
with peer.makefile("rb") as reply:
|
||||
if reply.readline(256).split()[1:2] == [b"200"]:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise UpdateError(
|
||||
"The upgraded panel did not respond to the sign-in check."
|
||||
)
|
||||
|
||||
|
||||
def back_up(backup, log):
|
||||
shutil.copytree(VENV, backup / "venv", symlinks=True)
|
||||
shutil.copytree(CONFIG.parent, backup / "config", symlinks=True)
|
||||
with (backup / "panel.sql").open("xb") as dump:
|
||||
run(
|
||||
"/usr/bin/mariadb-dump",
|
||||
"--protocol=socket",
|
||||
"--user=root",
|
||||
"--socket=/run/mysqld/mysqld.sock",
|
||||
"--single-transaction",
|
||||
"--add-drop-database",
|
||||
"--databases",
|
||||
"coulobre_panel",
|
||||
stdout=dump,
|
||||
log=log,
|
||||
)
|
||||
if (backup / "panel.sql").stat().st_size == 0:
|
||||
raise UpdateError("The database recovery dump is empty.")
|
||||
|
||||
|
||||
def check_dependencies(wheel, log):
|
||||
try:
|
||||
run(
|
||||
PYTHON,
|
||||
"-m",
|
||||
"pip",
|
||||
"--isolated",
|
||||
"install",
|
||||
"--dry-run",
|
||||
"--no-index",
|
||||
wheel,
|
||||
log=log,
|
||||
)
|
||||
except UpdateError:
|
||||
raise UpdateError(
|
||||
"The installed dependencies cannot satisfy this release. "
|
||||
"Use the manual upgrade procedure."
|
||||
) from None
|
||||
|
||||
|
||||
def apply_update(status, request, hostname):
|
||||
backup = STATE / datetime.now(UTC).strftime("recovery-%Y%m%dT%H%M%S%fZ")
|
||||
backup.mkdir(mode=0o700)
|
||||
status["recovery"] = backup.name
|
||||
changed = False
|
||||
stopped = []
|
||||
with (
|
||||
(backup / "update.log").open("xb") as log,
|
||||
TemporaryDirectory(dir=STATE) as download,
|
||||
):
|
||||
try:
|
||||
release = selected_release(
|
||||
request["version"],
|
||||
status["installed_version"],
|
||||
request["sha256"],
|
||||
)
|
||||
publish_status(status, "running", "Verifying the release package.")
|
||||
wheel = download_wheel(release, download)
|
||||
check_dependencies(wheel, log)
|
||||
check_installation(release.version)
|
||||
active = active_units(log)
|
||||
if not {PANEL, BEAT, WORKER} <= set(active):
|
||||
raise UpdateError(
|
||||
"Start the panel, scheduler and worker before updating."
|
||||
)
|
||||
publish_status(
|
||||
status, "running", "Stopping the panel and its workers."
|
||||
)
|
||||
sockets = [
|
||||
unit for unit in active if unit.endswith((".socket", ".timer"))
|
||||
]
|
||||
services = [
|
||||
unit
|
||||
for unit in active
|
||||
if unit not in {PANEL, BEAT} and unit.endswith(".service")
|
||||
]
|
||||
stopped = active
|
||||
systemctl("stop", [PANEL, BEAT, *sockets], log)
|
||||
if "coulobre-health.timer" in active:
|
||||
systemctl("stop", ["coulobre-health.service"], log)
|
||||
systemctl("stop", services, log)
|
||||
if "Result=timeout" in run(
|
||||
"/usr/bin/systemctl",
|
||||
"show",
|
||||
"-p",
|
||||
"Result",
|
||||
*services,
|
||||
log=log,
|
||||
):
|
||||
raise UpdateError(
|
||||
"A worker did not shut down cleanly. "
|
||||
"Finish its jobs before retrying."
|
||||
)
|
||||
pending = run(
|
||||
"/usr/bin/systemctl",
|
||||
"list-units",
|
||||
"--state=active,activating",
|
||||
"--plain",
|
||||
"--no-legend",
|
||||
"coulobre-*@*.service",
|
||||
log=log,
|
||||
)
|
||||
if any(
|
||||
not line.startswith("coulobre-update@")
|
||||
for line in pending.splitlines()
|
||||
if line.strip()
|
||||
):
|
||||
raise UpdateError(
|
||||
"A provisioning service is still running. "
|
||||
"Retry after it finishes."
|
||||
)
|
||||
(backup / "units.json").write_text(json.dumps(active))
|
||||
publish_status(status, "running", "Creating the recovery backup.")
|
||||
back_up(backup, log)
|
||||
publish_status(
|
||||
status, "running", "Installing the verified release."
|
||||
)
|
||||
changed = True
|
||||
run(
|
||||
PYTHON,
|
||||
"-m",
|
||||
"pip",
|
||||
"--isolated",
|
||||
"install",
|
||||
"--no-index",
|
||||
"--no-deps",
|
||||
wheel,
|
||||
log=log,
|
||||
umask=0o022,
|
||||
)
|
||||
run(PYTHON, "-m", "pip", "check", log=log)
|
||||
publish_status(
|
||||
status,
|
||||
"running",
|
||||
"Applying migrations and collecting static files.",
|
||||
)
|
||||
manage("check", log=log)
|
||||
manage("migrate", "--noinput", log=log)
|
||||
manage("collectstatic", "--noinput", log=log)
|
||||
publish_status(
|
||||
status, "running", "Starting services and verifying the panel."
|
||||
)
|
||||
systemctl("start", stopped, log)
|
||||
if not set(active) <= set(active_units(log)):
|
||||
raise UpdateError("Some panel services did not restart.")
|
||||
verify_panel(hostname, release, log)
|
||||
status["installed_version"] = release.version
|
||||
publish_status(
|
||||
status,
|
||||
"succeeded",
|
||||
"The updated panel responded and its services restarted.",
|
||||
)
|
||||
except (OSError, UpdateError) as error:
|
||||
if not changed:
|
||||
try:
|
||||
systemctl("start", stopped, log)
|
||||
except UpdateError:
|
||||
changed = True
|
||||
message = (
|
||||
str(error)
|
||||
if isinstance(error, UpdateError)
|
||||
else "An update operation failed. Check the private log."
|
||||
)
|
||||
publish_status(
|
||||
status, "recovery_required" if changed else "failed", message
|
||||
)
|
||||
|
||||
|
||||
def read_request(peer):
|
||||
peer.settimeout(4)
|
||||
caller = peer.getsockopt(
|
||||
socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")
|
||||
)
|
||||
_, uid, _ = struct.unpack("3i", caller)
|
||||
if uid != getpwnam("coulobre-panel").pw_uid:
|
||||
raise UpdateError("Only the Coulobre panel can request updates.")
|
||||
with peer.makefile("rb") as stream:
|
||||
request = json.loads(stream.readline(2048))
|
||||
if request == {"action": "linked-nodes"}:
|
||||
return request
|
||||
if not isinstance(request, dict) or set(request) != {
|
||||
"version",
|
||||
"sha256",
|
||||
"actor",
|
||||
}:
|
||||
raise UpdateError("The update request is invalid.")
|
||||
if not all(
|
||||
isinstance(value, str)
|
||||
and value
|
||||
and len(value) <= 160
|
||||
and value.isprintable()
|
||||
for value in request.values()
|
||||
):
|
||||
raise UpdateError("The update request is invalid.")
|
||||
version_key(request["version"])
|
||||
if not SHA256.fullmatch(request["sha256"]):
|
||||
raise UpdateError("The update request is invalid.")
|
||||
return request
|
||||
|
||||
|
||||
def reply(peer, **payload):
|
||||
peer.sendall(json.dumps(payload).encode() + b"\n")
|
||||
|
||||
|
||||
def handle_request(peer):
|
||||
request = read_request(peer)
|
||||
if request.get("action") == "linked-nodes":
|
||||
try:
|
||||
nodes = linked_status(installation_plan())
|
||||
except UpdateError as error:
|
||||
reply(
|
||||
peer,
|
||||
accepted=True,
|
||||
status=display_status(),
|
||||
problem=str(error),
|
||||
)
|
||||
else:
|
||||
reply(peer, accepted=True, status=display_status(), nodes=nodes)
|
||||
return
|
||||
with LOCK.open("a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError as error:
|
||||
raise UpdateError("An update is already running.") from error
|
||||
os.fchmod(lock.fileno(), 0o600)
|
||||
previous = read_status()
|
||||
if previous.get("state") == "running":
|
||||
publish_status(
|
||||
previous,
|
||||
"recovery_required",
|
||||
"The previous update was interrupted. "
|
||||
"Review the recovery files.",
|
||||
)
|
||||
if previous.get("state") == "recovery_required":
|
||||
raise UpdateError(
|
||||
"Resolve the previous update before starting another one."
|
||||
)
|
||||
installed = version("coulobre-panel")
|
||||
status = {
|
||||
"installed_version": installed,
|
||||
"target_version": request["version"],
|
||||
"actor": request["actor"],
|
||||
}
|
||||
LOGGER.info(
|
||||
"Update from %s to %s requested by %s.",
|
||||
installed,
|
||||
status["target_version"],
|
||||
status["actor"],
|
||||
)
|
||||
try:
|
||||
hostname = check_installation(request["version"])
|
||||
except UpdateError as error:
|
||||
publish_status(status, "failed", str(error))
|
||||
raise
|
||||
publish_status(status, "running", "Checking release compatibility.")
|
||||
reply(peer, accepted=True)
|
||||
peer.close()
|
||||
apply_update(status, request, hostname)
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
with socket.socket(fileno=0) as peer:
|
||||
try:
|
||||
handle_request(peer)
|
||||
except (OSError, ValueError, UpdateError) as error:
|
||||
message = (
|
||||
str(error)
|
||||
if isinstance(error, UpdateError)
|
||||
else "Could not accept the update request."
|
||||
)
|
||||
with suppress(OSError):
|
||||
reply(peer, accepted=False, message=message)
|
||||
@@ -201,12 +201,14 @@ def serve_mail_archive(operation):
|
||||
from .account_restore_request import apply_restore_once
|
||||
from .mail_node_backup import backup_mailbox, restore_mailbox
|
||||
from .node_files import require_root_directory
|
||||
from .receiver_scope import check_mail_service_peer
|
||||
|
||||
source, output = sys.stdin.buffer, sys.stdout.buffer
|
||||
identity = {"version": 1, "operation": operation}
|
||||
try:
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run the mail archive service as root.")
|
||||
check_mail_service_peer()
|
||||
request = MailArchiveRequest.parse(read_header(source), operation)
|
||||
identity = request.manifest()
|
||||
require_root_directory(WORK_DIRECTORY)
|
||||
|
||||
@@ -74,13 +74,13 @@ def replace_configuration(path, content, *, mode=0o644):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def locked_root_directory(path):
|
||||
def locked_root_directory(path, *, shared=False):
|
||||
import fcntl
|
||||
|
||||
require_root_directory(path)
|
||||
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
fcntl.flock(fd, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
|
||||
yield fd
|
||||
finally:
|
||||
os.close(fd)
|
||||
@@ -0,0 +1,114 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import shlex
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
|
||||
from .node_files import (
|
||||
locked_root_directory,
|
||||
read_root_file,
|
||||
require_root_directory,
|
||||
write_new_file,
|
||||
)
|
||||
from .release_updates import UpdateError, version_key
|
||||
|
||||
NODE_KEYS = Path("/etc/ssh/coulobre-node-keys")
|
||||
|
||||
|
||||
def maintenance_path(role):
|
||||
return NODE_KEYS / f".{role}-upgrade.json"
|
||||
|
||||
|
||||
def rollout_target(role):
|
||||
path = maintenance_path(role)
|
||||
try:
|
||||
path.lstat()
|
||||
require_root_directory(NODE_KEYS)
|
||||
data = json.loads(read_root_file(path, mode=0o600))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
if (
|
||||
not isinstance(data, dict)
|
||||
or set(data) != {"target", "panels"}
|
||||
or not isinstance(data["panels"], dict)
|
||||
):
|
||||
raise ValueError("Invalid receiver maintenance record.")
|
||||
try:
|
||||
version_key(data["target"])
|
||||
except UpdateError as error:
|
||||
raise ValueError(str(error)) from None
|
||||
return data["target"]
|
||||
|
||||
|
||||
def receiver_panel_keys(role):
|
||||
require_root_directory(NODE_KEYS)
|
||||
accounts = sorted(NODE_KEYS.glob(f"coulobre-{role}-p-*"))
|
||||
unrestricted = NODE_KEYS / f"coulobre-{role}-request"
|
||||
if unrestricted.exists():
|
||||
accounts.append(unrestricted)
|
||||
fingerprints = set()
|
||||
for account in accounts:
|
||||
for line in read_root_file(account, mode=0o644).splitlines():
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
_, key_type, key = shlex.split(line)
|
||||
if key_type != "ssh-ed25519":
|
||||
raise ValueError("Expected an Ed25519 key for every panel.")
|
||||
digest = hashlib.sha256(
|
||||
base64.b64decode(key, validate=True)
|
||||
).digest()
|
||||
fingerprint = base64.b64encode(digest).decode().rstrip("=")
|
||||
fingerprints.add(f"SHA256:{fingerprint}")
|
||||
if not fingerprints:
|
||||
raise ValueError("No authorized panel keys were found.")
|
||||
return fingerprints
|
||||
|
||||
|
||||
def verify_inventory(role, source):
|
||||
require_root_directory(source.parent)
|
||||
plan = json.loads(read_root_file(source, mode=0o600))
|
||||
if (
|
||||
not isinstance(plan, dict)
|
||||
or set(plan) != {"target", "panels"}
|
||||
or not isinstance(plan["panels"], dict)
|
||||
or set(plan["panels"]) != receiver_panel_keys(role)
|
||||
):
|
||||
raise ValueError("Account for every authorized panel key in the plan.")
|
||||
try:
|
||||
target = version_key(plan["target"])
|
||||
releases = {
|
||||
version_key(release) for release in plan["panels"].values()
|
||||
}
|
||||
except UpdateError as error:
|
||||
raise ValueError(str(error)) from None
|
||||
if len(releases) != 1:
|
||||
raise ValueError("All linked panels must agree on their release.")
|
||||
return plan, target, releases.pop()
|
||||
|
||||
|
||||
def begin_maintenance(role, source):
|
||||
with locked_root_directory(NODE_KEYS):
|
||||
plan, target, panels = verify_inventory(role, source)
|
||||
receiver = version_key(version("coulobre-panel"))
|
||||
if not panels <= receiver <= target or panels == target:
|
||||
raise ValueError(
|
||||
"Use an upgrade target and the current linked panel versions."
|
||||
)
|
||||
write_new_file(
|
||||
maintenance_path(role), json.dumps(plan) + "\n", mode=0o600
|
||||
)
|
||||
|
||||
|
||||
def finish_maintenance(role, source):
|
||||
with locked_root_directory(NODE_KEYS):
|
||||
plan, target, panels = verify_inventory(role, source)
|
||||
receiver = version("coulobre-panel")
|
||||
if not (
|
||||
rollout_target(role) == plan["target"] == receiver
|
||||
and target == panels
|
||||
):
|
||||
raise ValueError(
|
||||
"The receiver and every linked panel must be at the target."
|
||||
)
|
||||
maintenance_path(role).unlink()
|
||||
@@ -4,6 +4,8 @@ from importlib.metadata import version
|
||||
|
||||
PROBE = {"version": 1, "operation": "probe"}
|
||||
PROBE_BYTES = (json.dumps(PROBE) + "\n").encode()
|
||||
STATUS_PROBE = PROBE | {"version": 2}
|
||||
STATUS_PROBE_BYTES = (json.dumps(STATUS_PROBE) + "\n").encode()
|
||||
PROBE_LIMIT = 4096
|
||||
|
||||
|
||||
@@ -11,6 +13,44 @@ def probe_identity(role):
|
||||
return PROBE | {"role": role, "release": version("coulobre-panel")}
|
||||
|
||||
|
||||
def parse_status_probe(body, role):
|
||||
from .release_updates import UpdateError, version_key
|
||||
|
||||
try:
|
||||
if len(body) > PROBE_LIMIT:
|
||||
raise ValueError
|
||||
reply = json.loads(body)
|
||||
if (
|
||||
not isinstance(reply, dict)
|
||||
or type(reply.get("version")) is not int
|
||||
or reply["version"] not in {1, 2}
|
||||
or reply.get("operation") != "probe"
|
||||
or reply.get("role") != role
|
||||
or reply.get("state")
|
||||
not in {"configured", "maintenance", "failed"}
|
||||
):
|
||||
raise ValueError
|
||||
version_key(reply.get("release"))
|
||||
target = reply.get("upgrade_target")
|
||||
if reply["state"] == "maintenance":
|
||||
if reply["version"] != 2:
|
||||
raise ValueError
|
||||
version_key(target)
|
||||
else:
|
||||
target = None
|
||||
except (ValueError, TypeError, UpdateError, RecursionError) as error:
|
||||
raise ValueError(
|
||||
"The receiver returned no trusted release status."
|
||||
) from error
|
||||
return {
|
||||
"role": role,
|
||||
"protocol": reply["version"],
|
||||
"release": reply["release"],
|
||||
"state": reply["state"],
|
||||
"upgrade_target": target,
|
||||
}
|
||||
|
||||
|
||||
def check_receiver(role):
|
||||
if role == "dns":
|
||||
from .dns_node_apply import RNDC, ZONE_DIRECTORY, run
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import json
|
||||
import sys
|
||||
from contextlib import nullcontext
|
||||
|
||||
from .receiver_scope import authorized_request
|
||||
|
||||
MAX_REQUEST_BYTES = 4096
|
||||
|
||||
@@ -14,6 +17,8 @@ def serve_apply_request(
|
||||
include_result=False,
|
||||
probe_role=None,
|
||||
):
|
||||
from .node_maintenance import rollout_target
|
||||
|
||||
report = {"version": manifest_version}
|
||||
try:
|
||||
body = sys.stdin.buffer.read(limit + 1)
|
||||
@@ -28,16 +33,52 @@ def serve_apply_request(
|
||||
and isinstance(payload, dict)
|
||||
and payload.get("operation") == "probe"
|
||||
):
|
||||
from .node_probe import PROBE, check_receiver, probe_identity
|
||||
from .node_probe import (
|
||||
PROBE,
|
||||
STATUS_PROBE,
|
||||
check_receiver,
|
||||
probe_identity,
|
||||
)
|
||||
|
||||
if payload != PROBE or type(payload.get("version")) is not int:
|
||||
raise ValueError("Expected a version 1 node probe.")
|
||||
report = probe_identity(probe_role)
|
||||
check_receiver(probe_role)
|
||||
if (
|
||||
payload not in (PROBE, STATUS_PROBE)
|
||||
or type(payload.get("version")) is not int
|
||||
):
|
||||
raise ValueError("Expected a supported node probe.")
|
||||
report = probe_identity(probe_role) | {
|
||||
"version": payload["version"]
|
||||
}
|
||||
with authorized_request(probe_role):
|
||||
check_receiver(probe_role)
|
||||
target = rollout_target(probe_role)
|
||||
if target and payload == PROBE:
|
||||
raise ValueError("The receiver is in upgrade maintenance.")
|
||||
if target:
|
||||
print(
|
||||
json.dumps(
|
||||
report
|
||||
| {
|
||||
"state": "maintenance",
|
||||
"upgrade_target": target,
|
||||
"problem": None,
|
||||
}
|
||||
)
|
||||
)
|
||||
return 0
|
||||
else:
|
||||
if probe_role is not None and rollout_target(probe_role):
|
||||
raise ValueError("The receiver is in upgrade maintenance.")
|
||||
spec = parse_manifest(payload)
|
||||
report = spec.manifest() if identity is None else identity(spec)
|
||||
result = apply(spec)
|
||||
guard = (
|
||||
nullcontext()
|
||||
if probe_role is None
|
||||
else authorized_request(probe_role, spec)
|
||||
)
|
||||
with guard:
|
||||
if probe_role is not None and rollout_target(probe_role):
|
||||
raise ValueError("The receiver is in upgrade maintenance.")
|
||||
result = apply(spec)
|
||||
if include_result and result is not None:
|
||||
report.update(result)
|
||||
except (OSError, ValueError) as error:
|
||||
|
||||
+162
-8
@@ -1,6 +1,7 @@
|
||||
import argparse
|
||||
import grp
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
@@ -22,11 +23,23 @@ from .node_files import (
|
||||
require_root_directory,
|
||||
write_new_file,
|
||||
)
|
||||
from .node_maintenance import (
|
||||
NODE_KEYS,
|
||||
begin_maintenance,
|
||||
finish_maintenance,
|
||||
receiver_panel_keys,
|
||||
rollout_target,
|
||||
)
|
||||
from .node_probe import PROBE_BYTES, PROBE_LIMIT, check_receiver, verify_probe
|
||||
from .receiver_scope import (
|
||||
scope_files,
|
||||
scope_path,
|
||||
scoped_account,
|
||||
scoped_domains,
|
||||
)
|
||||
from .sftp_keys import read_public_keys
|
||||
|
||||
PANEL_SSH = Path("/etc/coulobre-remote")
|
||||
NODE_KEYS = Path("/etc/ssh/coulobre-node-keys")
|
||||
SSH_DROP_IN = Path("/etc/ssh/sshd_config.d/00-coulobre-node-requests.conf")
|
||||
SYSTEMD = Path("/etc/systemd/system")
|
||||
COMMAND_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
|
||||
@@ -172,7 +185,21 @@ def install_receivers(assets, roles):
|
||||
for role in roles:
|
||||
install_receiver(assets, role)
|
||||
config = assets / "openssh/coulobre-node-requests.conf.example"
|
||||
added = put_file(SSH_DROP_IN, config.read_text())
|
||||
desired = config.read_text()
|
||||
original = (
|
||||
read_root_file(SSH_DROP_IN) if SSH_DROP_IN.exists() else None
|
||||
)
|
||||
legacy = (
|
||||
desired.replace(",coulobre-dns-p-*,coulobre-mail-p-*", "")
|
||||
.replace(",coulobre-dns-p-*", "")
|
||||
.replace(",coulobre-mail-p-*", "")
|
||||
)
|
||||
migrated = original == legacy
|
||||
if migrated:
|
||||
replace_configuration(SSH_DROP_IN, desired)
|
||||
added = False
|
||||
else:
|
||||
added = put_file(SSH_DROP_IN, desired)
|
||||
try:
|
||||
require_root_directory(Path("/run/sshd"), create_mode=0o755)
|
||||
run("/usr/sbin/sshd", "-t")
|
||||
@@ -182,6 +209,8 @@ def install_receivers(assets, roles):
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired):
|
||||
if added:
|
||||
SSH_DROP_IN.unlink()
|
||||
elif migrated:
|
||||
replace_configuration(SSH_DROP_IN, original)
|
||||
raise
|
||||
run("systemctl", "daemon-reload")
|
||||
run(
|
||||
@@ -192,12 +221,13 @@ def install_receivers(assets, roles):
|
||||
)
|
||||
|
||||
|
||||
def check_ssh_receiver(role):
|
||||
def check_ssh_receiver(role, account=None):
|
||||
account = account or role.receiver
|
||||
live = run(
|
||||
"/usr/sbin/sshd",
|
||||
"-T",
|
||||
"-C",
|
||||
f"user={role.receiver},host=localhost,addr=127.0.0.1",
|
||||
f"user={account},host=localhost,addr=127.0.0.1",
|
||||
).decode()
|
||||
expected = {
|
||||
f"forcecommand {role.relay}",
|
||||
@@ -205,6 +235,8 @@ def check_ssh_receiver(role):
|
||||
"authenticationmethods publickey",
|
||||
"disableforwarding yes",
|
||||
"permituserrc no",
|
||||
"permituserenvironment no",
|
||||
"permittunnel no",
|
||||
"permittty no",
|
||||
"pubkeyauthentication yes",
|
||||
"passwordauthentication no",
|
||||
@@ -213,8 +245,15 @@ def check_ssh_receiver(role):
|
||||
"authorizedkeyscommand none",
|
||||
}
|
||||
if not expected <= set(live.splitlines()):
|
||||
raise ValueError(f"Check the effective SSH policy for {account}.")
|
||||
if account != role.receiver and any(
|
||||
line.startswith("acceptenv ")
|
||||
and set(line.split()[1:]) - {"LANG", "LC_*", "COLORTERM", "NO_COLOR"}
|
||||
for line in live.splitlines()
|
||||
):
|
||||
raise ValueError(
|
||||
f"Check the effective SSH policy for {role.receiver}."
|
||||
"Restrict accepted SSH environment variables to locale and "
|
||||
"terminal color settings."
|
||||
)
|
||||
|
||||
|
||||
@@ -229,6 +268,10 @@ def one_public_key(path):
|
||||
def authorize_panel(role, key_path):
|
||||
key = one_public_key(key_path)
|
||||
with locked_root_directory(NODE_KEYS):
|
||||
if rollout_target(role.name):
|
||||
raise ValueError("The receiver is in upgrade maintenance.")
|
||||
if scope_files(role.name):
|
||||
raise ValueError("Use domain-scoped keys on this receiver.")
|
||||
check_ssh_receiver(role)
|
||||
destination = NODE_KEYS / role.receiver
|
||||
old = (
|
||||
@@ -245,6 +288,60 @@ def authorize_panel(role, key_path):
|
||||
write_new_file(destination, entry, mode=0o644)
|
||||
|
||||
|
||||
def authorize_scoped_panel(role, panel, key_path, domains):
|
||||
account = scoped_account(role.name, panel)
|
||||
key = one_public_key(key_path)
|
||||
if not key.startswith("ssh-ed25519 "):
|
||||
raise ValueError("Use an Ed25519 panel public key.")
|
||||
domains = {canonical_domain(domain) for domain in domains}
|
||||
path = scope_path(account)
|
||||
destination = NODE_KEYS / account
|
||||
with locked_root_directory(NODE_KEYS):
|
||||
if rollout_target(role.name):
|
||||
raise ValueError("The receiver is in upgrade maintenance.")
|
||||
legacy = NODE_KEYS / role.receiver
|
||||
if legacy.exists() and any(
|
||||
line.strip() and not line.lstrip().startswith("#")
|
||||
for line in read_root_file(legacy, mode=0o644).splitlines()
|
||||
):
|
||||
raise ValueError(
|
||||
"Remove unrestricted panel keys before enabling scopes."
|
||||
)
|
||||
for other in scope_files(role.name):
|
||||
if other == path:
|
||||
continue
|
||||
assigned = scoped_domains(other)
|
||||
if (
|
||||
domains & assigned
|
||||
or role.name == "dns"
|
||||
and any(
|
||||
domain.endswith(f".{existing}")
|
||||
or existing.endswith(f".{domain}")
|
||||
for domain in domains
|
||||
for existing in assigned
|
||||
)
|
||||
):
|
||||
raise ValueError("A domain overlaps another panel's scope.")
|
||||
scoped_peers = NODE_KEYS.glob(f"coulobre-{role.name}-p-*")
|
||||
for peer in scoped_peers:
|
||||
if peer != destination and any(
|
||||
has_authorized_key(line, key)
|
||||
for line in read_root_file(peer, mode=0o644).splitlines()
|
||||
):
|
||||
raise ValueError(
|
||||
"A panel key may have only one scope per role."
|
||||
)
|
||||
ensure_identity(account, home="/", shell="/bin/sh", group=role.group)
|
||||
check_ssh_receiver(role, account)
|
||||
entry = f'command="{role.relay}",restrict {key}\n'
|
||||
contents = json.dumps(sorted(domains)) + "\n"
|
||||
if path.exists():
|
||||
scoped_domains(path)
|
||||
put_file(destination, entry)
|
||||
replace_configuration(path, contents, mode=0o600)
|
||||
return account
|
||||
|
||||
|
||||
def has_authorized_key(line, key):
|
||||
if line.lstrip().startswith("#"):
|
||||
return False
|
||||
@@ -315,10 +412,14 @@ def normalize_host(host):
|
||||
return canonical_domain(host)
|
||||
|
||||
|
||||
def ssh_setup(assets, role, host, port):
|
||||
def ssh_setup(assets, role, host, port, *, scope=None):
|
||||
config = (
|
||||
assets / f"openssh/{role.name}-node-client.conf.example"
|
||||
).read_text()
|
||||
if scope is not None:
|
||||
config = config.replace(
|
||||
f"User {role.receiver}", f"User {scoped_account(role.name, scope)}"
|
||||
)
|
||||
return config.replace(
|
||||
f"HostName {role.name}.example.org", f"HostName {host}"
|
||||
).replace("Port 22", f"Port {port}")
|
||||
@@ -367,12 +468,12 @@ def stage_ssh_settings(role, config, known_hosts, group):
|
||||
)
|
||||
|
||||
|
||||
def enrol_panel(assets, role, host, port, host_key):
|
||||
def enrol_panel(assets, role, host, port, host_key, *, scope=None):
|
||||
host = normalize_host(host)
|
||||
key = one_public_key(host_key)
|
||||
entry = host if port == 22 else f"[{host}]:{port}"
|
||||
known_hosts = f"{entry} {key}\n"
|
||||
config = ssh_setup(assets, role, host, port)
|
||||
config = ssh_setup(assets, role, host, port, scope=scope)
|
||||
_, group = prepare_panel(role)
|
||||
require_root_directory(SYSTEMD)
|
||||
with locked_root_directory(PANEL_SSH):
|
||||
@@ -438,6 +539,22 @@ def ssh_port(value):
|
||||
return port
|
||||
|
||||
|
||||
def check_receiver_drained(role):
|
||||
active = run(
|
||||
"systemctl",
|
||||
"list-units",
|
||||
"--state=active,activating,deactivating",
|
||||
"--no-legend",
|
||||
"--plain",
|
||||
f"{role.unit}.socket",
|
||||
f"{role.unit}@*.service",
|
||||
)
|
||||
if active.strip():
|
||||
raise ValueError(
|
||||
"Stop the receiver socket and let its requests drain."
|
||||
)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(prog="coulobre-node-setup")
|
||||
parser.add_argument("--source", type=Path, default=Path.cwd())
|
||||
@@ -449,7 +566,17 @@ def main(argv=None):
|
||||
for command, help_text in (
|
||||
("prepare-panel", "Prepare and print the panel's public SSH key."),
|
||||
("authorize-panel", "Authorize a panel public key on this receiver."),
|
||||
(
|
||||
"authorize-scoped-panel",
|
||||
"Assign exact domains to one panel identity.",
|
||||
),
|
||||
("check-receiver", "Check the service configuration on this node."),
|
||||
("list-panels", "List the authorized panel key fingerprints."),
|
||||
("begin-maintenance", "Stage a verified receiver upgrade plan."),
|
||||
(
|
||||
"finish-maintenance",
|
||||
"Verify the final plan and resume the receiver.",
|
||||
),
|
||||
(
|
||||
"enrol-panel",
|
||||
"Verify and install a remote relay on the panel host.",
|
||||
@@ -463,10 +590,17 @@ def main(argv=None):
|
||||
action.add_argument("role", choices=ROLES)
|
||||
if command == "authorize-panel":
|
||||
action.add_argument("public_key", type=Path)
|
||||
if command == "authorize-scoped-panel":
|
||||
action.add_argument("panel")
|
||||
action.add_argument("public_key", type=Path)
|
||||
action.add_argument("domains", nargs="+")
|
||||
if command in {"begin-maintenance", "finish-maintenance"}:
|
||||
action.add_argument("inventory", type=Path)
|
||||
if command == "enrol-panel":
|
||||
action.add_argument("host")
|
||||
action.add_argument("host_key", type=Path)
|
||||
action.add_argument("--port", type=ssh_port, default=22)
|
||||
action.add_argument("--scope")
|
||||
args = parser.parse_args(argv)
|
||||
if os.geteuid() != 0:
|
||||
parser.exit(1, "coulobre-node-setup: Run this command as root.\n")
|
||||
@@ -489,9 +623,28 @@ def main(argv=None):
|
||||
elif args.command == "authorize-panel":
|
||||
authorize_panel(role, args.public_key)
|
||||
print(f"Authorized the panel key for the {role.name} receiver.")
|
||||
elif args.command == "authorize-scoped-panel":
|
||||
account = authorize_scoped_panel(
|
||||
role, args.panel, args.public_key, args.domains
|
||||
)
|
||||
print(
|
||||
f"Authorized {account}. Use --scope {args.panel} on the panel."
|
||||
)
|
||||
elif args.command == "check-receiver":
|
||||
check_receiver(role.name)
|
||||
print(f"The local {role.name} services are ready.")
|
||||
elif args.command == "list-panels":
|
||||
print("\n".join(sorted(receiver_panel_keys(role.name))))
|
||||
elif args.command == "begin-maintenance":
|
||||
check_ssh_receiver(role)
|
||||
check_receiver_drained(role)
|
||||
begin_maintenance(role.name, args.inventory)
|
||||
print(f"The {role.name} receiver is in upgrade maintenance.")
|
||||
elif args.command == "finish-maintenance":
|
||||
check_ssh_receiver(role)
|
||||
check_receiver(role.name)
|
||||
finish_maintenance(role.name, args.inventory)
|
||||
print(f"The {role.name} receiver is accepting requests.")
|
||||
elif args.command == "enrol-panel":
|
||||
enrol_panel(
|
||||
release_assets(args.source),
|
||||
@@ -499,6 +652,7 @@ def main(argv=None):
|
||||
args.host,
|
||||
args.port,
|
||||
args.host_key,
|
||||
scope=args.scope,
|
||||
)
|
||||
print(
|
||||
f"Verified the {role.name} receiver. "
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import socket
|
||||
import stat
|
||||
import struct
|
||||
import sys
|
||||
from contextlib import contextmanager
|
||||
|
||||
from .domain_names import canonical_domain
|
||||
from .node_files import (
|
||||
locked_root_directory,
|
||||
read_root_file,
|
||||
require_root_directory,
|
||||
)
|
||||
from .node_maintenance import NODE_KEYS, rollout_target
|
||||
|
||||
LOCAL_WORKERS = {
|
||||
"dns": "coulobre-dns-publisher",
|
||||
"mail": "coulobre-mail-provisioner",
|
||||
}
|
||||
MAIL_SERVICE_PEERS = {
|
||||
"coulobre-mail-archive-backup",
|
||||
"coulobre-mail-archive-restore",
|
||||
"coulobre-mail-credential-request",
|
||||
}
|
||||
|
||||
|
||||
def scoped_account(role, panel):
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,11}", panel):
|
||||
raise ValueError(
|
||||
"Use 1 to 12 lowercase letters, digits or hyphens for the panel."
|
||||
)
|
||||
return f"coulobre-{role}-p-{panel}"
|
||||
|
||||
|
||||
def scope_files(role):
|
||||
return sorted(NODE_KEYS.glob(f".scope-coulobre-{role}-p-*.json"))
|
||||
|
||||
|
||||
def scope_path(account):
|
||||
return NODE_KEYS / f".scope-{account}.json"
|
||||
|
||||
|
||||
def scoped_domains(path):
|
||||
require_root_directory(path.parent)
|
||||
domains = json.loads(read_root_file(path, mode=0o600))
|
||||
if (
|
||||
not isinstance(domains, list)
|
||||
or not domains
|
||||
or any(
|
||||
not isinstance(domain, str) or canonical_domain(domain) != domain
|
||||
for domain in domains
|
||||
)
|
||||
):
|
||||
raise ValueError("The receiver has an invalid domain scope.")
|
||||
return set(domains)
|
||||
|
||||
|
||||
def socket_peer():
|
||||
try:
|
||||
descriptor = sys.stdin.fileno()
|
||||
except (AttributeError, OSError, ValueError):
|
||||
return None
|
||||
if type(descriptor) is not int or not stat.S_ISSOCK(
|
||||
os.fstat(descriptor).st_mode
|
||||
):
|
||||
return None
|
||||
with socket.fromfd(descriptor, socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
credentials = peer.getsockopt(
|
||||
socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")
|
||||
)
|
||||
_, uid, _ = struct.unpack("3i", credentials)
|
||||
try:
|
||||
return pwd.getpwuid(uid).pw_name
|
||||
except KeyError as error:
|
||||
raise ValueError(
|
||||
"The receiver could not identify the peer."
|
||||
) from error
|
||||
|
||||
|
||||
def manifest_domain(spec):
|
||||
manifest = spec.manifest()
|
||||
for field in ("mailbox", "resource"):
|
||||
if field in manifest:
|
||||
manifest = manifest[field]
|
||||
break
|
||||
return manifest.get("domain")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def authorized_request(role, spec=None):
|
||||
peer = socket_peer()
|
||||
if peer in (None, "root", LOCAL_WORKERS[role]):
|
||||
yield
|
||||
return
|
||||
with locked_root_directory(NODE_KEYS, shared=True):
|
||||
if peer == f"coulobre-{role}-request":
|
||||
if scope_files(role):
|
||||
raise ValueError(
|
||||
"Use a domain-scoped panel key for this receiver."
|
||||
)
|
||||
elif peer.startswith(f"coulobre-{role}-p-"):
|
||||
domains = scoped_domains(scope_path(peer))
|
||||
if spec is not None and manifest_domain(spec) not in domains:
|
||||
raise ValueError(
|
||||
"The panel key is not assigned to this domain."
|
||||
)
|
||||
else:
|
||||
raise ValueError("The peer is not authorized for this receiver.")
|
||||
yield
|
||||
|
||||
|
||||
def check_mail_service_peer():
|
||||
if socket_peer() in MAIL_SERVICE_PEERS and (
|
||||
scope_files("mail") or rollout_target("mail")
|
||||
):
|
||||
raise ValueError(
|
||||
"The remote mail service is unavailable on this receiver."
|
||||
)
|
||||
@@ -0,0 +1,187 @@
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
ORIGIN = "https://code.hosting.hippogrief.nl"
|
||||
REPOSITORY = "hippogrief/coulobre"
|
||||
MANIFEST = "web-update.json"
|
||||
VERSION = re.compile(
|
||||
r"(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(?:rc([1-9][0-9]{0,5}))?"
|
||||
)
|
||||
SHA256 = re.compile(r"[0-9a-f]{64}")
|
||||
MAX_WHEEL = 32 * 1024 * 1024
|
||||
|
||||
|
||||
class UpdateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def version_key(value):
|
||||
match = VERSION.fullmatch(value) if isinstance(value, str) else None
|
||||
if match is None:
|
||||
raise UpdateError("Use a published Coulobre release version.")
|
||||
major, minor, patch, candidate = match.groups()
|
||||
return (
|
||||
int(major),
|
||||
int(minor),
|
||||
int(patch),
|
||||
candidate is None,
|
||||
int(candidate or 0),
|
||||
)
|
||||
|
||||
|
||||
def release_tag(version):
|
||||
version_key(version)
|
||||
base, marker, candidate = version.partition("rc")
|
||||
return f"v{base}-rc.{candidate}" if marker else f"v{base}"
|
||||
|
||||
|
||||
def wheel_name(version):
|
||||
version_key(version)
|
||||
return f"coulobre_panel-{version}-py3-none-any.whl"
|
||||
|
||||
|
||||
def open_project(path):
|
||||
headers = {"User-Agent": "Coulobre Panel updater"}
|
||||
return build_opener(NoRedirect()).open(
|
||||
Request(ORIGIN + path, headers=headers), timeout=8
|
||||
)
|
||||
|
||||
|
||||
def read_json(path, limit=1024 * 1024):
|
||||
try:
|
||||
with open_project(path) as reply:
|
||||
content = reply.read(limit + 1)
|
||||
if len(content) > limit:
|
||||
raise UpdateError("The release response is larger than expected.")
|
||||
return json.loads(content)
|
||||
except (ValueError, OSError, RecursionError) as error:
|
||||
raise UpdateError(
|
||||
"Could not read the published Coulobre release."
|
||||
) from error
|
||||
|
||||
|
||||
def release_asset_path(version, name):
|
||||
return f"/{REPOSITORY}/releases/download/{release_tag(version)}/{name}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Release:
|
||||
version: str
|
||||
notes: str
|
||||
prerelease: bool
|
||||
sha256: str
|
||||
|
||||
|
||||
def compatible_release(item, installed):
|
||||
if not isinstance(item, dict) or item.get("draft") is not False:
|
||||
return None
|
||||
tag = item.get("tag_name")
|
||||
if not isinstance(tag, str) or not tag.startswith("v"):
|
||||
return None
|
||||
version = tag[1:].replace("-rc.", "rc")
|
||||
try:
|
||||
if release_tag(version) != tag or version_key(version) <= version_key(
|
||||
installed
|
||||
):
|
||||
return None
|
||||
except UpdateError:
|
||||
return None
|
||||
assets = item.get("assets")
|
||||
if not isinstance(assets, list):
|
||||
return None
|
||||
names = {
|
||||
asset.get("name")
|
||||
for asset in assets
|
||||
if isinstance(asset, dict) and isinstance(asset.get("name"), str)
|
||||
}
|
||||
if not {MANIFEST, wheel_name(version)} <= names:
|
||||
return None
|
||||
manifest = read_json(release_asset_path(version, MANIFEST), limit=8192)
|
||||
if (
|
||||
not isinstance(manifest, dict)
|
||||
or manifest.get("schema") != 1
|
||||
or manifest.get("version") != version
|
||||
or not isinstance(manifest.get("upgrade_from"), list)
|
||||
or not isinstance(manifest.get("sha256"), str)
|
||||
or not SHA256.fullmatch(manifest["sha256"])
|
||||
):
|
||||
raise UpdateError("The published update manifest is invalid.")
|
||||
if installed not in manifest["upgrade_from"]:
|
||||
return None
|
||||
return Release(
|
||||
version,
|
||||
str(item.get("body") or "")[:12000],
|
||||
"rc" in version or bool(item.get("prerelease")),
|
||||
manifest["sha256"],
|
||||
)
|
||||
|
||||
|
||||
def available_releases(installed):
|
||||
version_key(installed)
|
||||
items = read_json(f"/api/v1/repos/{REPOSITORY}/releases?limit=10")
|
||||
if not isinstance(items, list):
|
||||
raise UpdateError("The release catalog is invalid.")
|
||||
releases = [
|
||||
release
|
||||
for item in items
|
||||
if (release := compatible_release(item, installed))
|
||||
]
|
||||
return sorted(
|
||||
releases,
|
||||
key=lambda release: version_key(release.version),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
|
||||
def selected_release(version, installed, digest):
|
||||
tag = release_tag(version)
|
||||
item = read_json(f"/api/v1/repos/{REPOSITORY}/releases/tags/{tag}")
|
||||
release = compatible_release(item, installed)
|
||||
if (
|
||||
release is None
|
||||
or release.version != version
|
||||
or release.sha256 != digest
|
||||
):
|
||||
raise UpdateError(
|
||||
"The selected release changed or is incompatible. "
|
||||
"Review the catalog again."
|
||||
)
|
||||
return release
|
||||
|
||||
|
||||
def download_wheel(release, directory):
|
||||
name = wheel_name(release.version)
|
||||
dest = Path(directory) / name
|
||||
digest = hashlib.sha256()
|
||||
total = 0
|
||||
try:
|
||||
with (
|
||||
open_project(release_asset_path(release.version, name)) as reply,
|
||||
dest.open("xb") as output,
|
||||
):
|
||||
while chunk := reply.read(65536):
|
||||
total += len(chunk)
|
||||
if total > MAX_WHEEL:
|
||||
raise UpdateError(
|
||||
"The release package is larger than expected."
|
||||
)
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
except OSError as error:
|
||||
raise UpdateError(
|
||||
"Could not download the Coulobre release package."
|
||||
) from error
|
||||
if digest.hexdigest() != release.sha256:
|
||||
raise UpdateError(
|
||||
"The release package does not match its published checksum."
|
||||
)
|
||||
return dest
|
||||
@@ -6,6 +6,7 @@ from .credential_rotation import valid_generation
|
||||
from .database_node import DEFAULT_SOCKET, DatabaseSpec
|
||||
from .mail_node import MailboxSpec
|
||||
from .node_requests import serve_apply_request
|
||||
from .receiver_scope import check_mail_service_peer
|
||||
|
||||
REQUEST_VERSION = 1
|
||||
CREDENTIAL_SOCKET = "/run/coulobre-service-credentials.sock"
|
||||
@@ -98,6 +99,8 @@ def main(argv=None):
|
||||
|
||||
def parse(payload):
|
||||
request = ServiceCredentialRequest.from_manifest(payload)
|
||||
if request.kind == "mailbox":
|
||||
check_mail_service_peer()
|
||||
if args.mailbox_only and request.kind != "mailbox":
|
||||
raise ValueError("This node handles mailbox requests only.")
|
||||
return request
|
||||
|
||||
@@ -85,6 +85,7 @@ MIDDLEWARE = [
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"coulobre.hosting.panel_sessions.PanelSessionMiddleware",
|
||||
"django_otp.middleware.OTPMiddleware",
|
||||
"coulobre.hosting.sign_in.PrivilegedFactorMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
@@ -271,6 +272,9 @@ LOCAL_MAILBOX_CREDENTIALS = (
|
||||
os.environ.get("COULOBRE_LOCAL_MAILBOX_CREDENTIALS") == "1"
|
||||
)
|
||||
MAIL_IMAP_HOST = os.environ.get("COULOBRE_MAIL_IMAP_HOST", "").strip()
|
||||
MAIL_SUBMISSION_HOST = os.environ.get(
|
||||
"COULOBRE_MAIL_SUBMISSION_HOST", ""
|
||||
).strip()
|
||||
MAIL_DNS_RESOLVERS = ip_addresses_env("COULOBRE_MAIL_DNS_RESOLVERS", 3)
|
||||
MAIL_SENDING_IPS = ip_addresses_env("COULOBRE_MAIL_SENDING_IPS", 4)
|
||||
MAIL_MX_IPS = ip_addresses_env("COULOBRE_MAIL_MX_IPS", 4)
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest import TestCase
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from . import linked_updates, local_update, node_maintenance
|
||||
from .node_probe import PROBE, STATUS_PROBE, parse_status_probe
|
||||
from .node_requests import serve_apply_request
|
||||
from .release_updates import UpdateError
|
||||
|
||||
ORIGINAL = "0.11.0rc1"
|
||||
TARGET = "0.11.1rc1"
|
||||
|
||||
|
||||
def receiver(role, release, *, protocol=2, state="maintenance", target=TARGET):
|
||||
return {
|
||||
"version": protocol,
|
||||
"operation": "probe",
|
||||
"role": role,
|
||||
"release": release,
|
||||
"state": state,
|
||||
"upgrade_target": target,
|
||||
}
|
||||
|
||||
|
||||
class LinkedUpdateTests(TestCase):
|
||||
def test_only_target_version_in_maintenance_enables_update(self):
|
||||
def staged(body):
|
||||
return linked_updates.staged_for_release(
|
||||
parse_status_probe(json.dumps(body).encode(), "dns"), TARGET
|
||||
)
|
||||
|
||||
self.assertTrue(staged(receiver("dns", TARGET)))
|
||||
self.assertFalse(staged(receiver("dns", ORIGINAL)))
|
||||
self.assertFalse(staged(receiver("dns", TARGET, state="configured")))
|
||||
self.assertFalse(staged(receiver("dns", TARGET, target="0.11.2rc1")))
|
||||
self.assertFalse(
|
||||
staged(receiver("dns", TARGET, protocol=1, state="configured"))
|
||||
)
|
||||
|
||||
def test_roster_requires_every_shared_panel_before_leaving_maintenance(
|
||||
self,
|
||||
):
|
||||
with TemporaryDirectory() as root:
|
||||
inventory = Path(root) / "inventory.json"
|
||||
state = Path(root) / "keys"
|
||||
state.mkdir()
|
||||
keys = {"SHA256:panel-one", "SHA256:panel-two"}
|
||||
|
||||
def write_plan(panels):
|
||||
inventory.write_text(
|
||||
json.dumps({"target": TARGET, "panels": panels})
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(node_maintenance, "NODE_KEYS", state),
|
||||
patch.object(node_maintenance, "locked_root_directory"),
|
||||
patch.object(node_maintenance, "require_root_directory"),
|
||||
patch.object(
|
||||
node_maintenance,
|
||||
"read_root_file",
|
||||
side_effect=Path.read_text,
|
||||
) as read,
|
||||
patch.object(
|
||||
node_maintenance, "receiver_panel_keys", return_value=keys
|
||||
),
|
||||
patch.object(
|
||||
node_maintenance, "version", return_value=ORIGINAL
|
||||
) as release,
|
||||
):
|
||||
read.side_effect = lambda path, mode: path.read_text()
|
||||
write_plan({key: ORIGINAL for key in keys})
|
||||
node_maintenance.begin_maintenance("dns", inventory)
|
||||
self.assertEqual(
|
||||
node_maintenance.rollout_target("dns"), TARGET
|
||||
)
|
||||
release.return_value = TARGET
|
||||
|
||||
write_plan({"SHA256:panel-one": TARGET})
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "every authorized panel"
|
||||
):
|
||||
node_maintenance.finish_maintenance("dns", inventory)
|
||||
|
||||
write_plan(
|
||||
{"SHA256:panel-one": TARGET, "SHA256:panel-two": ORIGINAL}
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "agree"):
|
||||
node_maintenance.finish_maintenance("dns", inventory)
|
||||
self.assertEqual(
|
||||
node_maintenance.rollout_target("dns"), TARGET
|
||||
)
|
||||
|
||||
write_plan({key: TARGET for key in keys})
|
||||
node_maintenance.finish_maintenance("dns", inventory)
|
||||
self.assertIsNone(node_maintenance.rollout_target("dns"))
|
||||
|
||||
def test_unknown_receiver_blocks_root_update_until_it_reports_target(self):
|
||||
nodes = [
|
||||
{
|
||||
"protocol": 2,
|
||||
"state": "maintenance",
|
||||
"release": TARGET,
|
||||
"upgrade_target": TARGET,
|
||||
},
|
||||
{
|
||||
"protocol": None,
|
||||
"state": "unavailable",
|
||||
"release": None,
|
||||
"upgrade_target": None,
|
||||
},
|
||||
]
|
||||
with (
|
||||
patch.object(
|
||||
local_update,
|
||||
"installation_plan",
|
||||
return_value={"hostname": "panel.example.test"},
|
||||
),
|
||||
patch.object(local_update, "linked_status", return_value=nodes),
|
||||
):
|
||||
with self.assertRaisesRegex(UpdateError, "every linked receiver"):
|
||||
local_update.check_installation(TARGET)
|
||||
nodes[1].update(nodes[0])
|
||||
self.assertEqual(
|
||||
local_update.check_installation(TARGET), "panel.example.test"
|
||||
)
|
||||
|
||||
def test_receiver_preserves_probe_and_blocks_provisioning_in_maintenance(
|
||||
self,
|
||||
):
|
||||
parse = Mock()
|
||||
apply = Mock()
|
||||
inputs = [
|
||||
STATUS_PROBE,
|
||||
PROBE,
|
||||
{"kind": "bind9_zone", "domain": "example.test", "version": 1},
|
||||
]
|
||||
expected = ["maintenance", "failed", "failed"]
|
||||
for payload, outcome in zip(inputs, expected, strict=True):
|
||||
with (
|
||||
patch(
|
||||
"coulobre.node_requests.sys.stdin",
|
||||
buffer=io.BytesIO(json.dumps(payload).encode()),
|
||||
),
|
||||
patch("sys.stdout", new_callable=io.StringIO) as output,
|
||||
patch("coulobre.node_probe.check_receiver"),
|
||||
patch("coulobre.node_probe.version", return_value=TARGET),
|
||||
patch(
|
||||
"coulobre.node_maintenance.rollout_target",
|
||||
return_value=TARGET,
|
||||
),
|
||||
):
|
||||
result = serve_apply_request(1, parse, apply, probe_role="dns")
|
||||
self.assertEqual(result, int(outcome == "failed"))
|
||||
self.assertEqual(
|
||||
json.loads(output.getvalue())["state"], outcome
|
||||
)
|
||||
parse.assert_not_called()
|
||||
apply.assert_not_called()
|
||||
@@ -0,0 +1,192 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import socket
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest import TestCase
|
||||
from unittest.mock import Mock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from . import node_maintenance, node_setup, receiver_scope
|
||||
from .dns_node import DnsZone
|
||||
from .mail_node import MailboxQuotaUpdate, MailboxSpec
|
||||
from .mail_policy import MailRouting
|
||||
from .mail_queue import MailQueueRequest
|
||||
from .node_requests import serve_apply_request
|
||||
from .node_retirement import RetirementRequest
|
||||
from .service_access import ServiceAccessRequest
|
||||
|
||||
|
||||
def check_request(role, spec=None):
|
||||
with receiver_scope.authorized_request(role, spec):
|
||||
pass
|
||||
|
||||
|
||||
class ReceiverScopeTests(TestCase):
|
||||
def setUp(self):
|
||||
lock = patch.object(
|
||||
receiver_scope, "locked_root_directory", return_value=nullcontext()
|
||||
)
|
||||
lock.start()
|
||||
self.addCleanup(lock.stop)
|
||||
|
||||
def test_unix_peer_identity_comes_from_the_kernel(self):
|
||||
left, right = socket.socketpair()
|
||||
with (
|
||||
left,
|
||||
right,
|
||||
patch(
|
||||
"coulobre.receiver_scope.sys.stdin.fileno",
|
||||
return_value=left.fileno(),
|
||||
),
|
||||
):
|
||||
try:
|
||||
peer = receiver_scope.socket_peer()
|
||||
except PermissionError:
|
||||
self.skipTest("SO_PEERCRED is unavailable in this sandbox")
|
||||
self.assertEqual(peer, pwd.getpwuid(os.getuid()).pw_name)
|
||||
|
||||
def test_exact_domain_applies_to_all_managed_mail_operations(self):
|
||||
mailbox = MailboxSpec("alpha.example.test", "sales")
|
||||
requests = (
|
||||
mailbox,
|
||||
MailboxQuotaUpdate(mailbox),
|
||||
MailQueueRequest(mailbox.domain),
|
||||
MailRouting(mailbox.domain, {}),
|
||||
ServiceAccessRequest(mailbox, True),
|
||||
RetirementRequest(mailbox, str(uuid4())),
|
||||
)
|
||||
with (
|
||||
patch.object(
|
||||
receiver_scope,
|
||||
"socket_peer",
|
||||
return_value="coulobre-mail-p-alpha",
|
||||
),
|
||||
patch.object(
|
||||
receiver_scope, "scoped_domains", return_value={mailbox.domain}
|
||||
),
|
||||
):
|
||||
for request in requests:
|
||||
check_request("mail", request)
|
||||
for domain in ("beta.example.test", "sub.alpha.example.test"):
|
||||
with self.assertRaisesRegex(ValueError, "not assigned"):
|
||||
check_request("mail", MailQueueRequest(domain))
|
||||
|
||||
def test_scope_is_enforced_before_dispatching_dns_operations(self):
|
||||
zone = DnsZone(
|
||||
"beta.example.test",
|
||||
1,
|
||||
("ns.example.test",),
|
||||
"hostmaster.example.test",
|
||||
)
|
||||
apply = Mock()
|
||||
request = RetirementRequest(zone, str(uuid4()))
|
||||
with (
|
||||
patch.object(
|
||||
receiver_scope,
|
||||
"socket_peer",
|
||||
return_value="coulobre-dns-p-alpha",
|
||||
),
|
||||
patch.object(
|
||||
receiver_scope,
|
||||
"scoped_domains",
|
||||
return_value={"alpha.example.test"},
|
||||
),
|
||||
patch(
|
||||
"coulobre.node_requests.sys.stdin",
|
||||
buffer=io.BytesIO(json.dumps(request.manifest()).encode()),
|
||||
),
|
||||
patch("sys.stdout", new_callable=io.StringIO) as output,
|
||||
):
|
||||
result = serve_apply_request(
|
||||
1, lambda data: request, apply, probe_role="dns"
|
||||
)
|
||||
self.assertEqual(result, 1)
|
||||
self.assertIn(
|
||||
"not assigned", json.loads(output.getvalue())["problem"]
|
||||
)
|
||||
apply.assert_not_called()
|
||||
|
||||
def test_legacy_and_service_ssh_accounts_cannot_bypass_scoped_mail(self):
|
||||
with (
|
||||
patch.object(
|
||||
receiver_scope,
|
||||
"socket_peer",
|
||||
return_value="coulobre-mail-request",
|
||||
) as peer,
|
||||
patch.object(
|
||||
receiver_scope, "scope_files", return_value=[Path("/scope")]
|
||||
),
|
||||
):
|
||||
with self.assertRaisesRegex(ValueError, "domain-scoped"):
|
||||
check_request("mail")
|
||||
peer.return_value = "coulobre-dns-p-alpha"
|
||||
with self.assertRaisesRegex(ValueError, "not authorized"):
|
||||
check_request("mail")
|
||||
for name in receiver_scope.MAIL_SERVICE_PEERS:
|
||||
peer.return_value = name
|
||||
with self.assertRaisesRegex(ValueError, "unavailable"):
|
||||
receiver_scope.check_mail_service_peer()
|
||||
peer.return_value = "root"
|
||||
check_request("mail")
|
||||
receiver_scope.check_mail_service_peer()
|
||||
|
||||
def test_scopes_reject_overlap_and_record_both_keys(
|
||||
self,
|
||||
):
|
||||
role = node_setup.ROLES["dns"]
|
||||
key = Path("public-key")
|
||||
with (
|
||||
TemporaryDirectory() as scratch,
|
||||
patch.object(
|
||||
node_setup, "locked_root_directory", return_value=nullcontext()
|
||||
),
|
||||
patch.object(
|
||||
node_setup,
|
||||
"one_public_key",
|
||||
side_effect=(
|
||||
"ssh-ed25519 YWJj",
|
||||
"ssh-ed25519 ZGVm",
|
||||
"ssh-ed25519 ZGVm",
|
||||
),
|
||||
),
|
||||
patch.object(node_setup, "check_ssh_receiver"),
|
||||
patch.object(node_setup, "ensure_identity"),
|
||||
patch.object(node_setup, "rollout_target", return_value=None),
|
||||
):
|
||||
root = Path(scratch)
|
||||
|
||||
def read(path, *, mode=None):
|
||||
return path.read_text()
|
||||
|
||||
with (
|
||||
patch.object(node_setup, "NODE_KEYS", root),
|
||||
patch("coulobre.node_files.os.fchown"),
|
||||
patch.object(receiver_scope, "NODE_KEYS", root),
|
||||
patch.object(node_maintenance, "NODE_KEYS", root),
|
||||
patch.object(receiver_scope, "require_root_directory"),
|
||||
patch.object(node_maintenance, "require_root_directory"),
|
||||
patch.object(
|
||||
receiver_scope, "read_root_file", side_effect=read
|
||||
),
|
||||
patch.object(node_setup, "read_root_file", side_effect=read),
|
||||
patch.object(
|
||||
node_maintenance, "read_root_file", side_effect=read
|
||||
),
|
||||
):
|
||||
node_setup.authorize_scoped_panel(
|
||||
role, "one", key, ["alpha.example.test"]
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "overlaps"):
|
||||
node_setup.authorize_scoped_panel(
|
||||
role, "two", key, ["sub.alpha.example.test"]
|
||||
)
|
||||
node_setup.authorize_scoped_panel(
|
||||
role, "two", key, ["beta.example.test"]
|
||||
)
|
||||
self.assertEqual(
|
||||
len(node_maintenance.receiver_panel_keys(role.name)), 2
|
||||
)
|
||||
@@ -0,0 +1,106 @@
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest import TestCase
|
||||
from unittest.mock import patch
|
||||
|
||||
from . import local_update, release_updates
|
||||
from .release_updates import Release, UpdateError
|
||||
|
||||
|
||||
class ReleaseCatalogTests(TestCase):
|
||||
def test_requires_compatible_published_manifest_and_marks_candidates(self):
|
||||
target = "0.10.1rc2"
|
||||
installed = "0.10.1rc1"
|
||||
item = {
|
||||
"draft": False,
|
||||
"tag_name": "v0.10.1-rc.2",
|
||||
"prerelease": False,
|
||||
"assets": [
|
||||
{"name": "web-update.json"},
|
||||
{"name": release_updates.wheel_name(target)},
|
||||
],
|
||||
}
|
||||
manifest = {
|
||||
"schema": 1,
|
||||
"version": target,
|
||||
"upgrade_from": [installed],
|
||||
"sha256": "a" * 64,
|
||||
}
|
||||
with patch(
|
||||
"coulobre.release_updates.read_json", return_value=manifest
|
||||
):
|
||||
release = release_updates.compatible_release(item, installed)
|
||||
self.assertTrue(release.prerelease)
|
||||
self.assertEqual(release.version, target)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(
|
||||
item | {"draft": True}, installed
|
||||
)
|
||||
)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(item, "0.10.0rc1")
|
||||
)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(item, "0.10.1")
|
||||
)
|
||||
|
||||
def test_rejects_a_package_with_the_wrong_checksum(self):
|
||||
release = Release(
|
||||
"0.10.1rc2", "", True, hashlib.sha256(b"expected").hexdigest()
|
||||
)
|
||||
with (
|
||||
TemporaryDirectory() as directory,
|
||||
patch(
|
||||
"coulobre.release_updates.open_project",
|
||||
return_value=BytesIO(b"other"),
|
||||
),
|
||||
self.assertRaisesRegex(UpdateError, "published checksum"),
|
||||
):
|
||||
release_updates.download_wheel(release, directory)
|
||||
|
||||
|
||||
class LocalUpdateStatusTests(TestCase):
|
||||
def test_orphaned_running_state_is_visible_after_a_restart(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
lock = root / "update.lock"
|
||||
lock.touch()
|
||||
with patch.multiple(
|
||||
local_update, STATUS=root / "status.json", LOCK=lock
|
||||
):
|
||||
local_update.publish_status(
|
||||
{}, "running", "Applying migrations."
|
||||
)
|
||||
self.assertEqual(
|
||||
local_update.display_status()["state"], "recovery_required"
|
||||
)
|
||||
with lock.open("a") as active:
|
||||
local_update.fcntl.flock(
|
||||
active, local_update.fcntl.LOCK_EX
|
||||
)
|
||||
self.assertEqual(
|
||||
local_update.display_status()["state"], "running"
|
||||
)
|
||||
|
||||
def test_fails_preflight_before_mutating_packages_or_services(self):
|
||||
with (
|
||||
TemporaryDirectory() as directory,
|
||||
patch(
|
||||
"coulobre.local_update.selected_release",
|
||||
side_effect=UpdateError("Incompatible release."),
|
||||
),
|
||||
patch("coulobre.local_update.run") as commands,
|
||||
):
|
||||
root = Path(directory)
|
||||
with patch.multiple(
|
||||
local_update, STATE=root, STATUS=root / "status.json"
|
||||
):
|
||||
local_update.apply_update(
|
||||
{"installed_version": "0.10.1rc1"},
|
||||
{"version": "0.10.1rc2", "sha256": "a" * 64},
|
||||
"panel.example.net",
|
||||
)
|
||||
self.assertEqual(local_update.read_status()["state"], "failed")
|
||||
self.assertFalse(commands.called)
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import shlex
|
||||
import stat
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -69,7 +70,7 @@ class InstallerParametersTests(unittest.TestCase):
|
||||
"rabbitmq",
|
||||
]
|
||||
self.assertEqual(
|
||||
json.loads(env["COULOBRE_SERVICE_HEALTH"]),
|
||||
json.loads(shlex.split(env["COULOBRE_SERVICE_HEALTH"])[0]),
|
||||
{"panel": {"local": base + extras}},
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Describe a reviewed wheel for the web updater."
|
||||
)
|
||||
parser.add_argument("wheel", type=Path)
|
||||
parser.add_argument("upgrade_from", nargs="+")
|
||||
args = parser.parse_args()
|
||||
version_pattern = r"\d+\.\d+\.\d+(?:rc\d+)?"
|
||||
match = re.fullmatch(
|
||||
rf"coulobre_panel-({version_pattern})-py3-none-any\.whl",
|
||||
args.wheel.name,
|
||||
)
|
||||
if match is None or any(
|
||||
not re.fullmatch(version_pattern, item) for item in args.upgrade_from
|
||||
):
|
||||
parser.error("Use a Coulobre wheel and the tested installed versions.")
|
||||
with args.wheel.open("rb") as wheel:
|
||||
checksum = hashlib.file_digest(wheel, "sha256").hexdigest()
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"version": match[1],
|
||||
"upgrade_from": args.upgrade_from,
|
||||
"sha256": checksum,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user