Add scoped redirects, database logins and SFTP folder access

This commit is contained in:
parkel committed 2026-11-23 23:02:32 +01:00
1 parent 0263aa4bfa
commit 4b60663821
50 files changed
+2637 -54

No files matched your search

@@ -0,0 +1,16 @@
[Unit]
Description=Restore authorized Coulobre SFTP filesystem mounts
RequiresMountsFor=/srv/coulobre /var/lib/coulobre/web-node
After=local-fs.target
Before=ssh.service sshd.service
[Service]
Type=oneshot
User=root
ExecStart=/opt/coulobre/bin/coulobre-folder-sftp restore-mounts
UMask=0077
RemainAfterExit=yes
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,16 @@
[Unit]
Description=Coulobre folder SFTP management socket
Wants=coulobre-folder-sftp-mounts.service
After=coulobre-folder-sftp-mounts.service
[Socket]
ListenStream=/run/coulobre-folder-sftp.sock
SocketUser=root
SocketGroup=coulobre-sftp-provisioning
SocketMode=0660
Accept=yes
MaxConnections=2
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,15 @@
[Unit]
Description=Coulobre folder SFTP management request
After=local-fs.target
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
ExecStart=/opt/coulobre/bin/coulobre-folder-sftp apply
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=2min
UMask=0077
NoNewPrivileges=true
+41
View File
@@ -2918,3 +2918,44 @@ For upgrades with local backups already enabled, install the current
`coulobre-account-backup@.service` from the release before relying on SFTP `coulobre-account-backup@.service` from the release before relying on SFTP
exports. The unit needs write access to the managed web and web-node exports. The unit needs write access to the managed web and web-node
directories to publish the customer copy. directories to publish the customer copy.
## Enable folder-scoped SFTP logins
Folder logins use the existing key-only SSH policy and a separate chroot for
each login. The web node exposes the approved website directory through an
ID-mapped bind mount. Uploads are owned by the original website user on
disk, so the hosting account's filesystem quota still applies. The primary
hosting login retains access to its backup directory.
Use a kernel and filesystem that support ID-mapped mounts. Install these
units from the same release as the existing local SFTP worker.
```bash
sudo install -m 0644 deploy/systemd/coulobre-folder-sftp.socket \
deploy/systemd/coulobre-folder-sftp@.service \
deploy/systemd/coulobre-folder-sftp-mounts.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now coulobre-folder-sftp-mounts.service \
coulobre-folder-sftp.socket
```
Set `COULOBRE_LOCAL_FOLDER_SFTP=1` in the panel environment and restart the
panel and workers. Customers can add and remove logins in **SFTP Users**.
An empty folder selects the website document root. A changed or missing
directory leaves the login unavailable until its access is recreated.
Remove folder logins before changing the customer, changing the primary
domain or retiring the account.
## Manage database logins and SQL exports
Customers can add read-only or read-write logins for individual provisioned
databases. The read-write mode grants record-level changes. The primary
managed login retains its existing schema permissions and authentication.
Additional logins follow account suspension and can launch phpMyAdmin when
the existing bridge and credential service are enabled.
With account backups and SFTP enabled, use **Databases → Manage logins →
SQL export** to request a logical dump. Retrieve the latest completed export
over the account's primary SFTP login from
`/backups/database-<suffix>.sql.gz`. The export includes one selected
database.
+1
View File
@@ -33,6 +33,7 @@ coulobre-node-setup = "coulobre.node_setup:main"
coulobre-service-credentials = "coulobre.service_credentials:main" coulobre-service-credentials = "coulobre.service_credentials:main"
coulobre-service-health = "coulobre.service_health:main" coulobre-service-health = "coulobre.service_health:main"
coulobre-update = "coulobre.local_update:main" coulobre-update = "coulobre.local_update:main"
coulobre-folder-sftp = "coulobre.web_node_folder_sftp:main"
coulobre-web-node = "coulobre.web_node:main" coulobre-web-node = "coulobre.web_node:main"
[project.optional-dependencies] [project.optional-dependencies]
+42 -3
View File
@@ -18,6 +18,7 @@ from .node_requests import serve_apply_request
REQUEST_VERSION = 1 REQUEST_VERSION = 1
REMOTE_MAIL_VERSION = 2 REMOTE_MAIL_VERSION = 2
CUSTOMER_EXPORT_VERSION = 3 CUSTOMER_EXPORT_VERSION = 3
DATABASE_EXPORT_VERSION = 4
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups") BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
BACKUP_SOCKET = "/run/coulobre-account-backup.sock" BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
BACKUP_TIMEOUT_SECONDS = 30 * 60 BACKUP_TIMEOUT_SECONDS = 30 * 60
@@ -29,6 +30,21 @@ class AccountBackupRequest:
backup: AccountBackup backup: AccountBackup
remote_mail: bool = False remote_mail: bool = False
publish_to_customer: bool = False publish_to_customer: bool = False
database_suffix: str = ""
def __post_init__(self):
if self.database_suffix and (
not self.publish_to_customer
or self.remote_mail
or self.backup.include_website
or self.backup.additional_websites
or self.backup.mailboxes is not None
or tuple(database.suffix for database in self.backup.databases)
!= (self.database_suffix,)
):
raise ValueError(
"A database export must contain one matching database."
)
@classmethod @classmethod
def from_manifest(cls, data): def from_manifest(cls, data):
@@ -36,7 +52,9 @@ class AccountBackupRequest:
raise ValueError("Expected a local account backup request.") raise ValueError("Expected a local account backup request.")
version = data["version"] version = data["version"]
fields = {"version", "backup_id", "backup"} fields = {"version", "backup_id", "backup"}
if version == CUSTOMER_EXPORT_VERSION: if version == DATABASE_EXPORT_VERSION:
fields.add("database_suffix")
if version in (CUSTOMER_EXPORT_VERSION, DATABASE_EXPORT_VERSION):
fields.add("remote_mail") fields.add("remote_mail")
if ( if (
data.keys() != fields data.keys() != fields
@@ -45,6 +63,7 @@ class AccountBackupRequest:
REQUEST_VERSION, REQUEST_VERSION,
REMOTE_MAIL_VERSION, REMOTE_MAIL_VERSION,
CUSTOMER_EXPORT_VERSION, CUSTOMER_EXPORT_VERSION,
DATABASE_EXPORT_VERSION,
) )
or not isinstance(data["backup_id"], str) or not isinstance(data["backup_id"], str)
or type(data.get("remote_mail", False)) is not bool or type(data.get("remote_mail", False)) is not bool
@@ -61,8 +80,17 @@ class AccountBackupRequest:
raise ValueError( raise ValueError(
"Expected mailboxes in the remote backup request." "Expected mailboxes in the remote backup request."
) )
database_suffix = data.get("database_suffix", "")
if version == DATABASE_EXPORT_VERSION and (
not isinstance(database_suffix, str) or not database_suffix
):
raise ValueError("Expected a database suffix for this export.")
return cls( return cls(
backup_id, backup, remote_mail, version == CUSTOMER_EXPORT_VERSION backup_id,
backup,
remote_mail,
version in (CUSTOMER_EXPORT_VERSION, DATABASE_EXPORT_VERSION),
database_suffix,
) )
def manifest(self): def manifest(self):
@@ -70,6 +98,11 @@ class AccountBackupRequest:
"version": self.version, "version": self.version,
"backup_id": str(self.backup_id), "backup_id": str(self.backup_id),
"backup": self.backup.manifest(), "backup": self.backup.manifest(),
**(
{"database_suffix": self.database_suffix}
if self.database_suffix
else {}
),
**( **(
{"remote_mail": self.remote_mail} {"remote_mail": self.remote_mail}
if self.publish_to_customer if self.publish_to_customer
@@ -86,6 +119,8 @@ class AccountBackupRequest:
@property @property
def version(self): def version(self):
if self.database_suffix:
return DATABASE_EXPORT_VERSION
if self.publish_to_customer: if self.publish_to_customer:
return CUSTOMER_EXPORT_VERSION return CUSTOMER_EXPORT_VERSION
return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION return REMOTE_MAIL_VERSION if self.remote_mail else REQUEST_VERSION
@@ -146,7 +181,11 @@ def create_requested_backup(request):
if request.publish_to_customer: if request.publish_to_customer:
from .customer_backup_export import export_latest_backup from .customer_backup_export import export_latest_backup
export_latest_backup(request.backup.website, archive) export_latest_backup(
request.backup.website,
archive,
database_suffix=request.database_suffix,
)
return {"archive_bytes": archive.stat().st_size} return {"archive_bytes": archive.stat().st_size}
+16 -2
View File
@@ -4,7 +4,9 @@ import shutil
import stat import stat
from pathlib import Path from pathlib import Path
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from zipfile import ZipFile
from .database_node import DatabaseSpec
from .node_files import check_root_file, require_root_directory from .node_files import check_root_file, require_root_directory
from .web_node_apply import ( from .web_node_apply import (
SitePaths, SitePaths,
@@ -14,7 +16,9 @@ from .web_node_apply import (
) )
def export_latest_backup(site, archive): def export_latest_backup(site, archive, *, database_suffix=""):
if database_suffix:
DatabaseSpec(site.account_id, database_suffix)
# A root-owned directory protects the published export. # A root-owned directory protects the published export.
with locked_web_node(fcntl.LOCK_EX): with locked_web_node(fcntl.LOCK_EX):
check_reservation(site) check_reservation(site)
@@ -47,7 +51,10 @@ def export_latest_backup(site, archive):
raise ValueError( raise ValueError(
"The backup directory has unexpected ownership or permissions." "The backup directory has unexpected ownership or permissions."
) )
latest = destination / "latest.zip" component = (
f"database-{database_suffix}.sql.gz" if database_suffix else None
)
latest = destination / (component or "latest.zip")
if os.path.lexists(latest): if os.path.lexists(latest):
info = latest.lstat() info = latest.lstat()
if ( if (
@@ -63,6 +70,13 @@ def export_latest_backup(site, archive):
with NamedTemporaryFile(dir=destination, delete=False) as staged: with NamedTemporaryFile(dir=destination, delete=False) as staged:
temporary = Path(staged.name) temporary = Path(staged.name)
try: try:
if component:
with (
ZipFile(archive) as bundle,
bundle.open(component) as source,
):
shutil.copyfileobj(source, staged, length=1024 * 1024)
else:
with archive.open("rb") as source: with archive.open("rb") as source:
shutil.copyfileobj(source, staged, length=1024 * 1024) shutil.copyfileobj(source, staged, length=1024 * 1024)
staged.flush() staged.flush()
+78
View File
@@ -0,0 +1,78 @@
from dataclasses import dataclass
from .database_node import DatabaseSpec
LOGIN_KIND = "mariadb_database_login"
PRIVILEGES = {
"read": ("SELECT",),
"write": ("SELECT", "INSERT", "UPDATE", "DELETE"),
}
@dataclass(frozen=True)
class DatabaseLoginSpec:
database: DatabaseSpec
login_id: int
def __post_init__(self):
if (
type(self.login_id) is not int
or not 1 <= self.login_id <= 2**63 - 1
):
raise ValueError("Expected a valid managed MariaDB login.")
@property
def name(self):
return f"coulobre_g_{self.login_id}"
def manifest(self):
return {
"kind": LOGIN_KIND,
"database": self.database.manifest(),
"login_id": self.login_id,
}
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys() != {"kind", "database", "login_id"}
or data["kind"] != LOGIN_KIND
):
raise ValueError("Expected a managed MariaDB login.")
return cls(
DatabaseSpec.from_manifest(data["database"]), data["login_id"]
)
@dataclass(frozen=True)
class DatabaseLoginRequest:
login: DatabaseLoginSpec
access: str
operation: str
def __post_init__(self):
if self.access not in PRIVILEGES or self.operation not in (
"grant",
"remove",
):
raise ValueError("Choose a supported MariaDB login operation.")
def manifest(self):
return {
"operation": self.operation,
"login": self.login.manifest(),
"access": self.access,
}
@classmethod
def from_manifest(cls, data):
if data.keys() != {"operation", "login", "access"} or not isinstance(
data["access"], str
):
raise ValueError("Expected a managed MariaDB login operation.")
return cls(
DatabaseLoginSpec.from_manifest(data["login"]),
data["access"],
data["operation"],
)
+9
View File
@@ -110,13 +110,20 @@ def main(argv=None):
args = parser.parse_args(argv) args = parser.parse_args(argv)
if args.command == "apply-request": if args.command == "apply-request":
from .database_login import DatabaseLoginRequest
from .database_node_apply import ( from .database_node_apply import (
apply_database, apply_database,
retire_database, retire_database,
set_database_access, set_database_access,
) )
from .database_node_logins import apply_database_login
def parse(data): def parse(data):
if isinstance(data, dict) and data.get("operation") in (
"grant",
"remove",
):
return DatabaseLoginRequest.from_manifest(data)
return parse_retirement( return parse_retirement(
data, data,
DatabaseSpec.from_manifest, DatabaseSpec.from_manifest,
@@ -126,6 +133,8 @@ def main(argv=None):
) )
def apply(request): def apply(request):
if isinstance(request, DatabaseLoginRequest):
return apply_database_login(request, DEFAULT_SOCKET)
if isinstance(request, RetirementRequest): if isinstance(request, RetirementRequest):
return retire_database(request, DEFAULT_SOCKET) return retire_database(request, DEFAULT_SOCKET)
if isinstance(request, ServiceAccessRequest): if isinstance(request, ServiceAccessRequest):
+6
View File
@@ -553,6 +553,9 @@ def set_database_access(database, socket, suspended):
raise ValueError( raise ValueError(
"MariaDB did not apply the requested login state." "MariaDB did not apply the requested login state."
) )
from .database_node_logins import set_secondary_access
set_secondary_access(cursor, database, record["ownership"], suspended)
if not suspended: if not suspended:
marker.unlink() marker.unlink()
@@ -572,7 +575,10 @@ def retire_database(request, socket):
raise ValueError( raise ValueError(
"Suspend the managed database login before retirement." "Suspend the managed database login before retirement."
) )
from .database_node_logins import retire_secondary_logins
retirement.begin() retirement.begin()
retire_secondary_logins(cursor, database, record["ownership"])
cursor.execute("KILL USER %s", (database.name,)) cursor.execute("KILL USER %s", (database.name,))
marker = record_path.with_suffix(".retired") marker = record_path.with_suffix(".retired")
if not os.path.lexists(marker): if not os.path.lexists(marker):
+253
View File
@@ -0,0 +1,253 @@
import json
import os
from secrets import token_urlsafe
from . import database_node_apply as node
from .database_login import PRIVILEGES, DatabaseLoginSpec
from .database_node_backup import managed_database
from .node_files import read_root_file, require_root_directory, write_new_file
def login_directory(database):
return node.STATE_DIRECTORY / "logins" / database.name
def login_record(login, path, ownership):
record = json.loads(read_root_file(path, mode=0o600))
if (
not isinstance(record, dict)
or record.get("login") != login.manifest()
or record.get("ownership") != ownership
or record.get("access") not in PRIVILEGES
or record.get("plugin")
not in (node.NATIVE_PASSWORD, node.SHA2_PASSWORD)
or not isinstance(record.get("password"), str)
or len(record["password"]) != 43
):
raise ValueError("This login conflicts with its credentials record.")
return record
def login_users(cursor, login, plugin):
_, users = node.read_resources(
cursor, login.name, sha2=plugin == node.SHA2_PASSWORD
)
return users
def validate_login(cursor, login, record, *, allow_missing=False):
users = login_users(cursor, login, record["plugin"])
if not users and allow_missing:
return False
if record["plugin"] == node.SHA2_PASSWORD:
verifier, _ = node.sha2_login(users)
if (
record.get("verifier") is not None
and verifier != record["verifier"]
):
raise ValueError(
"The MariaDB login password has changed on the host."
)
elif users != (
(
"localhost",
node.NATIVE_PASSWORD,
node.native_password_hash(record["password"]),
),
):
raise ValueError(
"The existing login does not match managed credentials."
)
return True
def validate_grants(cursor, login, access):
cursor.execute("SHOW GRANTS FOR %s@'localhost'", (login.name,))
grantee = f"`{login.name}`@`localhost`"
expected_scope = (
f" ON {node.grant_scope(login.database.name)} TO {grantee}"
)
actual = []
for (grant,) in cursor.fetchall():
if (
grant.startswith(
(
f"GRANT USAGE ON *.* TO {grantee} IDENTIFIED VIA ",
f"GRANT USAGE ON *.* TO {grantee} IDENTIFIED BY PASSWORD ",
)
)
and "WITH GRANT OPTION" not in grant
):
continue
if grant.startswith("GRANT ") and grant.endswith(expected_scope):
actual.append(set(grant[6 : -len(expected_scope)].split(", ")))
else:
raise ValueError("The MariaDB login has unmanaged grants.")
if actual != [set(PRIVILEGES[access])]:
raise ValueError("The MariaDB login has unmanaged grants.")
def apply_database_login(request, socket):
if os.geteuid() != 0:
raise ValueError(
"Run the login operation as root on the MariaDB node."
)
login = request.login
with managed_database(login.database, socket) as (cursor, primary, path):
if os.path.lexists(path.with_suffix(".suspended")) or os.path.lexists(
path.with_suffix(".retired")
):
raise ValueError("The MariaDB database is suspended or retired.")
directory = login_directory(login.database)
for folder in (directory.parent, directory):
require_root_directory(folder, create_mode=0o700)
target = directory / f"{login.name}.json"
plugin = primary.get("authentication_plugin", node.NATIVE_PASSWORD)
if not os.path.lexists(target):
if login_users(cursor, login, plugin):
raise ValueError(
"This login is already used outside Coulobre."
)
if request.operation == "remove":
return
if len(list(directory.glob("*.json"))) >= 25:
raise ValueError(
"This database already has 25 supported logins."
)
record = {
"login": login.manifest(),
"ownership": primary["ownership"],
"access": request.access,
"plugin": plugin,
"password": token_urlsafe(32),
}
write_new_file(target, json.dumps(record), mode=0o600)
else:
record = login_record(login, target, primary["ownership"])
exists = validate_login(cursor, login, record, allow_missing=True)
if request.operation == "remove":
if exists:
cursor.execute("KILL USER %s", (login.name,))
cursor.execute("DROP USER %s@'localhost'", (login.name,))
target.unlink()
return
if record["access"] != request.access:
raise ValueError(
"The login has a different recorded access policy."
)
expected = {
"database": login.database.name,
"user": login.name,
"host": "localhost",
"socket": str(socket.resolve()),
"password": record["password"],
}
if not exists:
if record["plugin"] == node.SHA2_PASSWORD:
cursor.execute(
"CREATE USER %s@'localhost' IDENTIFIED VIA "
"caching_sha2_password USING PASSWORD(%s)",
(login.name, record["password"]),
)
else:
cursor.execute(
"CREATE USER %s@'localhost' IDENTIFIED VIA "
"mysql_native_password USING %s",
(
login.name,
node.native_password_hash(record["password"]),
),
)
privileges = ", ".join(PRIVILEGES[record["access"]])
cursor.execute(
f"GRANT {privileges} ON {node.grant_scope(login.database.name)} "
"TO %s@'localhost'",
(login.name,),
)
validate_grants(cursor, login, record["access"])
if record["plugin"] == node.SHA2_PASSWORD:
verifier, _ = node.sha2_login(
login_users(cursor, login, record["plugin"])
)
node.save_credential_record(
target, record | {"verifier": verifier}
)
verify_mariadb_login(expected)
def secondary_credentials(login, socket):
with managed_database(login.database, socket) as (cursor, primary, path):
if os.path.lexists(path.with_suffix(".suspended")) or os.path.lexists(
path.with_suffix(".retired")
):
raise ValueError("The MariaDB database is suspended or retired.")
directory = login_directory(login.database)
require_root_directory(directory)
record = login_record(
login, directory / f"{login.name}.json", primary["ownership"]
)
validate_login(cursor, login, record)
validate_grants(cursor, login, record["access"])
return {
"database": login.database.name,
"user": login.name,
"host": "localhost",
"socket": str(socket.resolve()),
"password": record["password"],
}
def existing_logins(database, ownership):
directory = login_directory(database)
if not os.path.lexists(directory):
return
require_root_directory(directory)
for path in sorted(directory.glob("*.json")):
record = json.loads(read_root_file(path, mode=0o600))
login = DatabaseLoginSpec.from_manifest(record.get("login"))
if login.database != database or path.stem != login.name:
raise ValueError("A secondary login has an unexpected identity.")
yield login, login_record(login, path, ownership), path
def verify_mariadb_login(credentials):
import MySQLdb
if not node.can_sign_in(MySQLdb, credentials, credentials["password"]):
raise ValueError("The secondary MariaDB login could not sign in.")
def set_secondary_access(cursor, database, ownership, suspended):
for login, record, path in existing_logins(database, ownership):
if not validate_login(cursor, login, record, allow_missing=True):
continue
checkpoint = path.with_suffix(".suspended")
if suspended and not checkpoint.exists():
state = (
"locked"
if node.login_is_locked(cursor, login.name)
else "unlocked"
)
write_new_file(checkpoint, state, mode=0o600)
if checkpoint.exists():
state = read_root_file(checkpoint, mode=0o600)
if state not in {"locked", "unlocked"}:
raise ValueError(
"A secondary login has an invalid suspension record."
)
action = "LOCK" if suspended or state == "locked" else "UNLOCK"
cursor.execute(
f"ALTER USER %s@'localhost' ACCOUNT {action}", (login.name,)
)
if not suspended:
checkpoint.unlink()
def retire_secondary_logins(cursor, database, ownership):
for login, record, _ in existing_logins(database, ownership):
if validate_login(cursor, login, record, allow_missing=True):
if not node.login_is_locked(cursor, login.name):
raise ValueError(
"Suspend secondary logins before database retirement."
)
cursor.execute("KILL USER %s", (login.name,))
+83
View File
@@ -0,0 +1,83 @@
from dataclasses import dataclass, field
from .sftp_keys import MAX_KEYS_BYTES, normalize_public_keys
from .web_node import WebSite
from .website_files import directory_parts
FOLDER_SOCKET = "/run/coulobre-folder-sftp.sock"
FOLDER_LIMIT = MAX_KEYS_BYTES + 32 * 1024
def base36(number):
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
result = ""
while number:
number, digit = divmod(number, 36)
result = digits[digit] + result
return result
def folder_user_prefix(site):
return f"cbf-{base36(site.account_id)}-"
@dataclass(frozen=True)
class FolderSftpRequest:
site: WebSite
login_id: int
folder: str
action: str
public_keys: str = field(default="", repr=False)
def __post_init__(self):
if self.site.site_id is not None:
raise ValueError("Choose the primary hosting website.")
if (
type(self.login_id) is not int
or not 1 <= self.login_id <= 2**63 - 1
):
raise ValueError("Choose a valid SFTP login.")
directory_parts(self.folder)
if self.action not in ("create", "keys", "remove"):
raise ValueError("Choose an available SFTP action.")
normalized = normalize_public_keys(self.public_keys)
if (self.action == "remove") == bool(normalized):
raise ValueError(
"Provide at least one key when granting SFTP access."
)
object.__setattr__(self, "public_keys", normalized)
@property
def username(self):
return folder_user_prefix(self.site) + base36(self.login_id)
def scope(self):
return {
"site": self.site.manifest(),
"login_id": self.login_id,
"folder": self.folder,
}
def identity(self):
return self.scope() | {"action": self.action}
def manifest(self):
return self.identity() | {"public_keys": self.public_keys}
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != {
"site",
"login_id",
"folder",
"action",
"public_keys",
}:
raise ValueError("Expected a folder SFTP request.")
return cls(
WebSite.from_manifest(data["site"]),
data["login_id"],
data["folder"],
data["action"],
data["public_keys"],
)
+29 -2
View File
@@ -31,6 +31,7 @@ def account_backup_manifest(
include_mailboxes=False, include_mailboxes=False,
include_website=True, include_website=True,
include_databases=True, include_databases=True,
database_suffix="",
): ):
mailboxes = None mailboxes = None
if include_mailboxes: if include_mailboxes:
@@ -40,7 +41,14 @@ def account_backup_manifest(
mailboxes = tuple(mailbox.spec for mailbox in requests) mailboxes = tuple(mailbox.spec for mailbox in requests)
return AccountBackup( return AccountBackup(
WebSite(account.pk, account.primary_domain), WebSite(account.pk, account.primary_domain),
tuple(database.spec for database in account.databases.all()) tuple(
database.spec
for database in (
account.databases.filter(suffix=database_suffix)
if database_suffix
else account.databases.all()
)
)
if include_databases if include_databases
else (), else (),
mailboxes, mailboxes,
@@ -59,17 +67,31 @@ def queue_account_backup(
customer_id=None, customer_id=None,
include_website=True, include_website=True,
include_databases=True, include_databases=True,
database_suffix="",
): ):
account = lock_hosting_account(account_id, customer_id=customer_id) account = lock_hosting_account(account_id, customer_id=customer_id)
require_open_account(account) require_open_account(account)
if database_suffix and not (
customer_id is not None
and include_databases
and not include_website
and not include_mailboxes
and account.databases.filter(
suffix=database_suffix,
provisioning__finished_at__isnull=False,
provisioning__problem="",
).exists()
):
raise ValidationError("Choose a provisioned database to export.")
if not any((include_mailboxes, include_website, include_databases)): if not any((include_mailboxes, include_website, include_databases)):
raise ValidationError("Select at least one backup component.") raise ValidationError("Select at least one backup component.")
_enqueue_backup( return _enqueue_backup(
account, account,
include_mailboxes=include_mailboxes, include_mailboxes=include_mailboxes,
include_website=include_website, include_website=include_website,
include_databases=include_databases, include_databases=include_databases,
export_customer_id=customer_id, export_customer_id=customer_id,
database_suffix=database_suffix,
) )
@@ -82,6 +104,7 @@ def _enqueue_backup(
include_website=True, include_website=True,
include_databases=True, include_databases=True,
export_customer_id=None, export_customer_id=None,
database_suffix="",
): ):
if not account.backup_jobs.filter(finished_at__isnull=True).exists(): if not account.backup_jobs.filter(finished_at__isnull=True).exists():
job = account.backup_jobs.create( job = account.backup_jobs.create(
@@ -90,16 +113,20 @@ def _enqueue_backup(
include_mailboxes=include_mailboxes, include_mailboxes=include_mailboxes,
include_website=include_website, include_website=include_website,
include_databases=include_databases, include_databases=include_databases,
database_suffix=database_suffix,
), ),
remote_mail=include_mailboxes remote_mail=include_mailboxes
and settings.REMOTE_ACCOUNT_BACKUP_MAIL, and settings.REMOTE_ACCOUNT_BACKUP_MAIL,
scheduled_for=scheduled_for, scheduled_for=scheduled_for,
export_customer_id=export_customer_id, export_customer_id=export_customer_id,
export_database_suffix=database_suffix,
) )
if scheduled_for is not None and offsite_destination: if scheduled_for is not None and offsite_destination:
OffsiteBackupTransfer.objects.create( OffsiteBackupTransfer.objects.create(
backup=job, destination=offsite_destination backup=job, destination=offsite_destination
) )
return job
return None
def _next_backup_run(schedule, now): def _next_backup_run(schedule, now):
@@ -232,6 +232,10 @@ def request_retirement(account_id, policy, confirmation, digest, actor):
raise ValidationError("Choose a retirement policy.") raise ValidationError("Choose a retirement policy.")
if retirement is not None and policy != Policy.RELEASE: if retirement is not None and policy != Policy.RELEASE:
return retirement return retirement
if account.folder_sftp_logins.exists():
raise ValidationError(
"Remove folder SFTP logins before retiring the hosting account."
)
targets = cleanup_targets(account) targets = cleanup_targets(account)
if policy == Policy.RELEASE: if policy == Policy.RELEASE:
for kind, target, _ in targets: for kind, target, _ in targets:
@@ -67,7 +67,8 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
backups = ( backups = (
self.account.backup_jobs.filter( self.account.backup_jobs.filter(
export_customer_id=self.account.customer_id export_customer_id=self.account.customer_id,
export_database_suffix="",
) )
.select_related("expiration") .select_related("expiration")
.order_by("-requested_at")[:30] .order_by("-requested_at")[:30]
@@ -0,0 +1,216 @@
from django import forms
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import (
require_http_methods,
require_POST,
require_safe,
)
from .access import customer_for_user
from .account_backups import queue_account_backup
from .credential_views import DatabaseCredentialView
from .installation_features import panel_feature_allowed
from .models import DatabaseLogin, HostingAccount, HostingDatabase
from .phpmyadmin import phpmyadmin_available
from .resource_requests import lock_hosting_account, require_active_services
from .service_credentials import CredentialKind, enabled_credential_access
from .sftp import site_is_active
class AddDatabaseLoginForm(forms.Form):
label = forms.CharField(max_length=80)
access = forms.ChoiceField(choices=DatabaseLogin.Access.choices)
def signed_in_customer(request):
customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None:
raise PermissionDenied
return customer
@require_safe
@never_cache
def customer_databases(request, pk):
customer = signed_in_customer(request)
account = get_object_or_404(
HostingAccount, pk=pk, customer=customer, retired_at__isnull=True
)
can_reveal = enabled_credential_access(request, CredentialKind.DATABASE)
return render(
request,
"hosting/customer_databases.html",
{
"account": account,
"databases": account.databases.select_related(
"provisioning"
).prefetch_related("logins"),
"show_sso": phpmyadmin_available(request),
"can_reveal": can_reveal,
},
)
@transaction.atomic
def update_database_login(
database, customer, action, *, login_id=None, data=None
):
account = lock_hosting_account(database.account_id, customer.pk)
require_active_services(account)
if (
getattr(getattr(database, "provisioning", None), "state", "")
!= "configured"
):
raise ValidationError("Finish provisioning the database first.")
if action == "add":
if database.logins.count() >= 25:
raise ValidationError(
"This database already has 25 managed logins."
)
DatabaseLogin.objects.create(
database=database,
requested_customer_id=customer.pk,
**data,
)
return
if (
not login_id
or not login_id.isascii()
or not login_id.isdecimal()
or len(login_id) > 18
):
raise Http404
login = get_object_or_404(database.logins, pk=int(login_id))
if login.finished_at is None:
raise ValidationError("Wait for the current login operation.")
DatabaseLogin.objects.requeue(
database.logins.filter(pk=login.pk),
action="remove",
requested_customer_id=customer.pk,
)
@require_http_methods(("GET", "HEAD", "POST"))
@never_cache
def database_login_editor(request, pk):
customer = signed_in_customer(request)
if not panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"):
raise Http404
database = get_object_or_404(
HostingDatabase.objects.select_related("account", "provisioning"),
account__retired_at__isnull=True,
account__customer=customer,
pk=pk,
)
action = request.POST.get("action")
form = AddDatabaseLoginForm(request.POST if action == "add" else None)
problem = ""
if request.method == "POST":
if action not in {"add", "remove"}:
raise Http404
if action == "remove" or form.is_valid():
try:
update_database_login(
database,
customer,
action,
login_id=request.POST.get("login"),
data=form.cleaned_data if action == "add" else None,
)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
problem = " ".join(error.messages)
else:
return redirect("panel:database_logins", pk=pk)
return render(
request,
"hosting/database_logins.html",
{
"database": database,
"form": form,
"problem": problem,
"logins": database.logins.order_by("label"),
"can_export": can_export_database(database),
"export_job": database.account.backup_jobs.filter(
export_database_suffix=database.suffix,
export_customer_id=customer.pk,
)
.order_by("-pk")
.first(),
"show_sso": phpmyadmin_available(request),
"can_reveal": enabled_credential_access(
request, CredentialKind.DATABASE
),
},
)
def can_export_database(database):
return (
panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
and settings.LOCAL_WEB_SFTP
and site_is_active(database.account)
and not database.account.services_suspended
and getattr(getattr(database, "provisioning", None), "state", "")
== "configured"
)
@require_POST
@never_cache
def database_sql_export(request, pk):
customer = signed_in_customer(request)
database = get_object_or_404(
HostingDatabase.objects.select_related("account", "provisioning"),
pk=pk,
account__customer=customer,
account__retired_at__isnull=True,
)
if not can_export_database(database):
raise Http404
try:
job = queue_account_backup(
database.account_id,
customer_id=customer.pk,
include_website=False,
database_suffix=database.suffix,
)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
messages.error(request, " ".join(error.messages))
else:
if job:
messages.success(request, "SQL export queued.")
else:
messages.error(
request, "Wait for the current account backup to finish."
)
return redirect("panel:database_logins", pk=database.pk)
class DatabaseLoginCredentialView(DatabaseCredentialView):
queryset = DatabaseLogin.objects.filter(
finished_at__isnull=False,
problem="",
action="grant",
database__account__retired_at__isnull=True,
database__account__services_suspended=False,
).select_related("database__account")
customer_relation = "database__account__customer"
@property
def account(self):
return self.resource.database.account
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.pop("rotation_url", None)
return context
+156
View File
@@ -0,0 +1,156 @@
from django import forms
from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from coulobre.sftp_keys import normalize_public_keys
from coulobre.website_files import directory_parts
from .access import customer_for_user
from .models import FolderSftpLogin, HostingAccount
from .resource_requests import (
lock_hosting_account,
require_active_services,
require_open_account,
)
from .sftp import site_is_active
class FolderLoginForm(forms.Form):
label = forms.CharField(max_length=80)
folder = forms.CharField(
label="Folder relative to the website document root",
required=False,
max_length=1024,
help_text="Leave blank for the entire website document root.",
)
public_keys = forms.CharField(
label="SSH public keys",
widget=forms.Textarea(attrs={"rows": 4, "spellcheck": "false"}),
help_text="Paste one public key per line.",
)
def __init__(self, *args, edit=False, **kwargs):
super().__init__(*args, **kwargs)
if edit:
self.fields.pop("label")
self.fields.pop("folder")
def clean_folder(self):
folder = self.cleaned_data["folder"]
try:
directory_parts(folder)
except ValueError as error:
raise ValidationError(str(error)) from error
return folder
def clean_public_keys(self):
try:
keys = normalize_public_keys(self.cleaned_data["public_keys"])
except ValueError as error:
raise ValidationError(str(error)) from error
if not keys:
raise ValidationError("Provide at least one SSH public key.")
return keys
@transaction.atomic
def save_folder_login(account_id, customer_id, action, login, data):
account = lock_hosting_account(account_id, customer_id)
require_open_account(account)
if action != "remove":
require_active_services(account)
if not site_is_active(account):
raise ValidationError(
"Activate the website before granting SFTP access."
)
if action == "create":
if account.folder_sftp_logins.count() >= 10:
raise ValidationError("This account has ten folder SFTP logins.")
account.folder_sftp_logins.create(
requested_customer_id=customer_id,
domain=account.primary_domain,
**data,
)
else:
jobs = account.folder_sftp_logins.filter(pk=login.pk)
current = jobs.get()
if current.finished_at is None:
raise ValidationError("Wait for the current login operation.")
FolderSftpLogin.objects.requeue(
jobs,
action=action,
requested_customer_id=customer_id,
**data,
)
@never_cache
@require_http_methods(("GET", "HEAD", "POST"))
def folder_sftp_users(request, pk):
customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None:
raise PermissionDenied
if not settings.LOCAL_WEB_SFTP:
raise Http404
account = get_object_or_404(
HostingAccount, pk=pk, customer=customer, retired_at__isnull=True
)
action = request.POST.get("action", "create")
login = None
if (login_id := request.GET.get("login")) is not None:
if (
not login_id.isascii()
or not login_id.isdecimal()
or len(login_id) > 18
):
raise Http404
login = get_object_or_404(account.folder_sftp_logins, pk=int(login_id))
edit = login is not None
form = FolderLoginForm(
request.POST
if action != "remove" and request.method == "POST"
else None,
edit=edit,
initial={"public_keys": login.public_keys} if edit else {},
)
enabled = settings.LOCAL_FOLDER_SFTP
problem = ""
if request.method == "POST":
if (
not enabled
or action not in {"create", "keys", "remove"}
or ((action != "create") != edit)
):
raise Http404
if action == "remove" or form.is_valid():
try:
save_folder_login(
pk,
customer.pk,
action,
login,
{} if action == "remove" else form.cleaned_data,
)
except (HostingAccount.DoesNotExist, FolderSftpLogin.DoesNotExist):
raise Http404 from None
except ValidationError as error:
problem = " ".join(error.messages)
else:
return redirect("panel:folder_sftp_users", pk=pk)
return render(
request,
"hosting/folder_sftp_users.html",
{
"account": account,
"form": form,
"login": login,
"enabled": enabled,
"logins": account.folder_sftp_logins.order_by("label"),
"problem": problem,
},
)
+29 -5
View File
@@ -11,9 +11,15 @@ from django.views.decorators.cache import never_cache
from django.views.generic import FormView from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin from django.views.generic.detail import SingleObjectMixin
from coulobre.mail_policy import MailRouting, MailVacation, parse_mail_policy from coulobre.mail_policy import (
DEFAULT_REPEAT_DAYS,
MAX_REPEAT_DAYS,
MailRouting,
MailVacation,
parse_mail_policy,
)
from .access import TenantScopeMixin, can_manage_hosting from .access import TenantScopeMixin, can_manage_hosting, reseller_for_user
from .mail_policies import ( from .mail_policies import (
mail_policy_available, mail_policy_available,
policy_account, policy_account,
@@ -131,6 +137,17 @@ class MailVacationForm(MailPolicyForm):
), ),
) )
repeat_days = forms.IntegerField(
label="Days between replies to the same sender",
min_value=1,
max_value=MAX_REPEAT_DAYS,
initial=DEFAULT_REPEAT_DAYS,
required=False,
help_text=(
"Leave blank for seven days. The mail node enforces its limits."
),
)
def make_spec(self, cleaned): def make_spec(self, cleaned):
values = { values = {
key: cleaned[key] for key in ("enabled", "subject", "message") key: cleaned[key] for key in ("enabled", "subject", "message")
@@ -142,7 +159,11 @@ class MailVacationForm(MailPolicyForm):
if timestamp if timestamp
else "" else ""
) )
return MailVacation(self.resource.spec, **values) return MailVacation(
self.resource.spec,
repeat_days=cleaned.get("repeat_days") or DEFAULT_REPEAT_DAYS,
**values,
)
@method_decorator(never_cache, name="dispatch") @method_decorator(never_cache, name="dispatch")
@@ -152,8 +173,10 @@ class MailPolicyEditor(
template_name = "hosting/mail_policy_form.html" template_name = "hosting/mail_policy_form.html"
def has_permission(self): def has_permission(self):
return getattr(self.request, "impersonation", None) is None and ( return (
super().has_permission() reseller_for_user(self.request.user) is None
and getattr(self.request, "impersonation", None) is None
and super().has_permission()
) )
def get_permission_required(self): def get_permission_required(self):
@@ -190,6 +213,7 @@ class MailPolicyEditor(
initial["catchall"] = spec.catchall initial["catchall"] = spec.catchall
else: else:
initial.update(spec.manifest()) initial.update(spec.manifest())
initial["repeat_days"] = spec.repeat_days
for name in ("starts_at", "ends_at"): for name in ("starts_at", "ends_at"):
initial[name] = initial[name].removesuffix("+00:00") initial[name] = initial[name].removesuffix("+00:00")
return initial return initial
@@ -0,0 +1,68 @@
# Generated by Django 5.2.19 on 2026-11-23 21:44
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0069_certificate_uploads"),
]
operations = [
migrations.CreateModel(
name="WebsiteRedirectPolicy",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
(
"domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("website", models.JSONField()),
("requested_rules", models.JSONField(default=list)),
("applied_rules", models.JSONField(default=list)),
(
"requested_customer_id",
models.PositiveBigIntegerField(null=True),
),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="redirect_policies",
to="hosting.hostingaccount",
),
),
],
options={
"constraints": [
models.UniqueConstraint(
fields=("account", "domain"),
name="website_redirect_per_domain",
)
],
},
),
]
@@ -0,0 +1,74 @@
# Generated by Django 5.2.19 on 2026-11-23 21:52
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0070_website_redirect_policy"),
]
operations = [
migrations.CreateModel(
name="DatabaseLogin",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
("label", models.CharField(max_length=80)),
(
"access",
models.CharField(
choices=[
("read", "Read only"),
("write", "Read and write"),
],
default="read",
max_length=6,
),
),
("action", models.CharField(default="grant", max_length=6)),
("requested_customer_id", models.PositiveBigIntegerField()),
(
"database",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="logins",
to="hosting.hostingdatabase",
),
),
],
options={
"abstract": False,
},
),
migrations.AddField(
model_name="phpmyadmingrant",
name="database_login",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="hosting.databaselogin",
),
),
]
@@ -0,0 +1,17 @@
# Generated by Django 5.2.19 on 2026-11-23 21:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0071_database_login"),
]
operations = [
migrations.AddField(
model_name="accountbackupjob",
name="export_database_suffix",
field=models.CharField(blank=True, default="", max_length=24),
),
]
@@ -0,0 +1,61 @@
# Generated by Django 5.2.19 on 2026-11-23 21:59
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
import coulobre.hosting.fields
class Migration(migrations.Migration):
dependencies = [
("hosting", "0072_database_export"),
]
operations = [
migrations.CreateModel(
name="FolderSftpLogin",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
(
"domain",
coulobre.hosting.fields.DomainNameField(max_length=253),
),
("label", models.CharField(max_length=80)),
("folder", models.CharField(blank=True, max_length=1024)),
("public_keys", models.TextField()),
("action", models.CharField(default="create", max_length=6)),
("requested_customer_id", models.PositiveBigIntegerField()),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="folder_sftp_logins",
to="hosting.hostingaccount",
),
),
],
options={
"abstract": False,
},
),
]
+82
View File
@@ -14,6 +14,7 @@ from django.utils import timezone
from coulobre.account_backup_request import backup_archive from coulobre.account_backup_request import backup_archive
from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS from coulobre.account_backup_retention import MAX_RETAINED_BACKUPS
from coulobre.account_restore_request import MAX_RESTORE_PATH_BYTES from coulobre.account_restore_request import MAX_RESTORE_PATH_BYTES
from coulobre.database_login import DatabaseLoginSpec
from coulobre.database_node import ( from coulobre.database_node import (
DATABASE_SUFFIX_PATTERN, DATABASE_SUFFIX_PATTERN,
INVALID_SUFFIX, INVALID_SUFFIX,
@@ -594,6 +595,12 @@ class ServiceSignOnGrant(models.Model):
class PhpMyAdminGrant(ServiceSignOnGrant): class PhpMyAdminGrant(ServiceSignOnGrant):
database = models.ForeignKey(HostingDatabase, on_delete=models.CASCADE) database = models.ForeignKey(HostingDatabase, on_delete=models.CASCADE)
database_login = models.ForeignKey(
"DatabaseLogin",
null=True,
blank=True,
on_delete=models.CASCADE,
)
class RoundcubeGrant(ServiceSignOnGrant): class RoundcubeGrant(ServiceSignOnGrant):
@@ -828,6 +835,57 @@ class ProvisioningJob(models.Model):
return "running" if self.started_at else "queued" return "running" if self.started_at else "queued"
class FolderSftpLogin(ProvisioningJob):
account = models.ForeignKey(
HostingAccount,
on_delete=models.CASCADE,
related_name="folder_sftp_logins",
)
domain = DomainNameField(max_length=253)
label = models.CharField(max_length=80)
folder = models.CharField(max_length=1024, blank=True)
public_keys = models.TextField()
action = models.CharField(max_length=6, default="create")
requested_customer_id = models.PositiveBigIntegerField()
@property
def spec(self):
from coulobre.folder_sftp import FolderSftpRequest
return FolderSftpRequest(
WebSite(self.account_id, self.domain),
self.pk,
self.folder,
self.action,
self.public_keys if self.action != "remove" else "",
)
class DatabaseLogin(ProvisioningJob):
class Access(models.TextChoices):
READ = "read", "Read only"
WRITE = "write", "Read and write"
database = models.ForeignKey(
HostingDatabase,
related_name="logins",
on_delete=models.CASCADE,
)
label = models.CharField(max_length=80)
access = models.CharField(
max_length=6, choices=Access, default=Access.READ
)
action = models.CharField(max_length=6, default="grant")
requested_customer_id = models.PositiveBigIntegerField()
def __str__(self):
return self.spec.name
@property
def spec(self):
return DatabaseLoginSpec(self.database.spec, self.pk)
class OperatorOperation(ProvisioningJob): class OperatorOperation(ProvisioningJob):
actor = models.ForeignKey( actor = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True
@@ -1037,6 +1095,27 @@ class WebsiteCertificateJob(ProvisioningJob):
certificate = models.JSONField(default=dict) certificate = models.JSONField(default=dict)
class WebsiteRedirectPolicy(ProvisioningJob):
account = models.ForeignKey(
HostingAccount,
on_delete=models.CASCADE,
related_name="redirect_policies",
)
domain = DomainNameField(max_length=253)
website = models.JSONField()
requested_rules = models.JSONField(default=list)
applied_rules = models.JSONField(default=list)
requested_customer_id = models.PositiveBigIntegerField(null=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["account", "domain"],
name="website_redirect_per_domain",
)
]
class WebsiteAlias(ProvisioningJob): class WebsiteAlias(ProvisioningJob):
wait_for_website = models.BooleanField(default=False) wait_for_website = models.BooleanField(default=False)
@@ -1166,6 +1245,9 @@ class AccountBackupJob(ProvisioningJob):
manifest = models.JSONField() manifest = models.JSONField()
remote_mail = models.BooleanField(default=False) remote_mail = models.BooleanField(default=False)
export_customer_id = models.PositiveBigIntegerField(null=True, blank=True) export_customer_id = models.PositiveBigIntegerField(null=True, blank=True)
export_database_suffix = models.CharField(
max_length=24, blank=True, default=""
)
scheduled_for = models.DateTimeField(null=True, blank=True) scheduled_for = models.DateTimeField(null=True, blank=True)
archive_bytes = models.PositiveBigIntegerField(null=True, blank=True) archive_bytes = models.PositiveBigIntegerField(null=True, blank=True)
retention_protected = models.BooleanField(default=False) retention_protected = models.BooleanField(default=False)
+70 -9
View File
@@ -1,7 +1,8 @@
from django.conf import settings from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.http import Http404, JsonResponse from django.http import Http404, JsonResponse
from django.shortcuts import render from django.shortcuts import get_object_or_404, render
from django.utils.functional import cached_property
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.debug import ( from django.views.decorators.debug import (
@@ -13,7 +14,12 @@ from django.views.decorators.http import require_POST
from .access import customer_for_user from .access import customer_for_user
from .credential_views import DatabaseCredentialView from .credential_views import DatabaseCredentialView
from .installation_features import panel_feature_allowed from .installation_features import panel_feature_allowed
from .models import HostingDatabase, PhpMyAdminGrant, ServiceCredentialAccess from .models import (
DatabaseLogin,
HostingDatabase,
PhpMyAdminGrant,
ServiceCredentialAccess,
)
from .service_credentials import ( from .service_credentials import (
CredentialKind, CredentialKind,
CredentialOutcome, CredentialOutcome,
@@ -37,8 +43,35 @@ def phpmyadmin_available(request):
) )
def active_database_logins():
return DatabaseLogin.objects.filter(
finished_at__isnull=False, problem="", action="grant"
)
class PhpMyAdminLaunch(DatabaseCredentialView): class PhpMyAdminLaunch(DatabaseCredentialView):
http_method_names = ["post"] http_method_names = ["post"]
secondary = False
@cached_property
def selected_login(self):
if not self.secondary:
return None
return get_object_or_404(
active_database_logins().select_related("database__account"),
pk=self.kwargs["pk"],
database__in=self.get_queryset().filter(
account__services_suspended=False
),
)
@cached_property
def resource(self):
return (
self.selected_login.database
if self.secondary
else super().resource
)
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs) response = super().dispatch(request, *args, **kwargs)
@@ -50,7 +83,10 @@ class PhpMyAdminLaunch(DatabaseCredentialView):
if not phpmyadmin_available(request): if not phpmyadmin_available(request):
raise Http404 raise Http404
token = issue_signon_grant( token = issue_signon_grant(
PhpMyAdminGrant, request.user, database=self.resource PhpMyAdminGrant,
request.user,
database=self.resource,
database_login=self.selected_login,
) )
return render( return render(
request, request,
@@ -60,7 +96,11 @@ class PhpMyAdminLaunch(DatabaseCredentialView):
+ "/coulobre-signon.php", + "/coulobre-signon.php",
"ticket": token, "ticket": token,
"product": "phpMyAdmin", "product": "phpMyAdmin",
"resource": self.resource.spec.name, "resource": (
self.selected_login.spec.name
if self.secondary
else self.resource.spec.name
),
"ticket_field": "ticket", "ticket_field": "ticket",
"account": self.account, "account": self.account,
}, },
@@ -68,8 +108,10 @@ class PhpMyAdminLaunch(DatabaseCredentialView):
def actor_has_database_access(actor, database): def actor_has_database_access(actor, database):
if database.account.retired_at is not None or not can_reveal_credentials( if (
actor, CredentialKind.DATABASE database.account.retired_at is not None
or database.account.services_suspended
or not can_reveal_credentials(actor, CredentialKind.DATABASE)
): ):
return False return False
customer = customer_for_user(actor) customer = customer_for_user(actor)
@@ -85,7 +127,9 @@ def redeem_phpmyadmin(request):
if not phpmyadmin_available(request): if not phpmyadmin_available(request):
raise Http404 raise Http404
token = bridge_ticket(request, settings.PHPMYADMIN_BRIDGE_KEY) token = bridge_ticket(request, settings.PHPMYADMIN_BRIDGE_KEY)
grant = consume_signon_grant(PhpMyAdminGrant, token, "database__account") grant = consume_signon_grant(
PhpMyAdminGrant, token, "database__account", "database_login"
)
if grant is None: if grant is None:
raise Http404 raise Http404
actor = signon_actor(grant, grant.actor) actor = signon_actor(grant, grant.actor)
@@ -93,17 +137,28 @@ def redeem_phpmyadmin(request):
raise Http404 raise Http404
database = grant.database database = grant.database
resource = database.spec
if grant.database_login_id is not None:
login = (
active_database_logins()
.filter(pk=grant.database_login_id, database=database)
.select_related("database")
.first()
)
if login is None:
raise Http404
resource = login.spec
audit = ServiceCredentialAccess.objects.create( audit = ServiceCredentialAccess.objects.create(
actor=grant.actor, actor=grant.actor,
actor_username=grant.actor.get_username(), actor_username=grant.actor.get_username(),
hosting_account_id=database.account_id, hosting_account_id=database.account_id,
kind=CredentialKind.DATABASE, kind=CredentialKind.DATABASE,
resource=database.spec.name, resource=resource.name,
method=ServiceCredentialAccess.Method.PHPMYADMIN, method=ServiceCredentialAccess.Method.PHPMYADMIN,
outcome=CredentialOutcome.REQUESTED, outcome=CredentialOutcome.REQUESTED,
) )
try: try:
credentials = fetch_service_credentials(database.spec) credentials = fetch_service_credentials(resource)
except (OSError, ValueError): except (OSError, ValueError):
audit.outcome = CredentialOutcome.UNAVAILABLE audit.outcome = CredentialOutcome.UNAVAILABLE
audit.save(update_fields=["outcome"]) audit.save(update_fields=["outcome"])
@@ -123,6 +178,12 @@ def redeem_phpmyadmin(request):
or actor is None or actor is None
or current.spec != database.spec or current.spec != database.spec
or not actor_has_database_access(actor, current) or not actor_has_database_access(actor, current)
or (
grant.database_login_id is not None
and not active_database_logins()
.filter(pk=grant.database_login_id, database=current)
.exists()
)
): ):
audit.outcome = CredentialOutcome.UNAVAILABLE audit.outcome = CredentialOutcome.UNAVAILABLE
audit.save(update_fields=["outcome"]) audit.save(update_fields=["outcome"])
+218
View File
@@ -0,0 +1,218 @@
from django import forms
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from coulobre.domain_names import canonical_domain
from coulobre.web_node import WebAlias, WebSite
from coulobre.web_redirects import (
MAX_DESTINATION,
RedirectConfiguration,
RedirectRule,
)
from .access import customer_for_user
from .certificate_views import account_certificate_sites
from .installation_features import panel_feature_allowed
from .models import HostingAccount, WebsiteAlias, WebsiteRedirectPolicy
from .resource_requests import lock_hosting_account, require_active_services
class RedirectForm(forms.Form):
source = forms.CharField(
label="Path",
max_length=181,
help_text="Enter the exact path, such as /old-page.",
)
destination = forms.CharField(
label="Destination URL",
max_length=MAX_DESTINATION,
)
status = forms.TypedChoiceField(
label="HTTP status",
choices=[
(301, "301 Moved permanently"),
(302, "302 Temporary redirect"),
(307, "307 Temporary redirect, keep request method"),
(308, "308 Permanent redirect, keep request method"),
],
initial=302,
coerce=int,
)
def __init__(self, *args, kind, **kwargs):
super().__init__(*args, **kwargs)
self.kind = kind
if kind == "domain":
del self.fields["source"]
def clean(self):
data = super().clean()
if not self.errors:
try:
self.rule = RedirectRule(
data.get("source", "*"),
data["destination"],
data["status"],
)
except ValueError as error:
raise forms.ValidationError(str(error)) from error
return data
def hosted_redirect_targets(account):
targets = account_certificate_sites(account)
if account.primary_domain not in targets:
return targets
for alias in (
WebsiteAlias.objects.filter(
reservation__account=account,
primary_domain=account.primary_domain,
http_active=True,
)
.exclude(operation=WebsiteAlias.Operation.REMOVE)
.select_related("reservation")
):
domain = alias.reservation.domain
targets[domain] = WebAlias(
WebSite(account.pk, account.primary_domain), domain
)
return targets
@transaction.atomic
def request_redirect_change(
account, website, actor, *, rule=None, source=None
):
account = lock_hosting_account(account.pk, actor)
require_active_services(account)
if hosted_redirect_targets(account).get(website.domain) != website:
raise ValidationError("This website is no longer available.")
job = account.redirect_policies.filter(domain=website.domain).first()
if job is not None and job.finished_at is None:
raise ValidationError("Wait for the current redirect change.")
applied = (
job.applied_rules if job and job.website == website.manifest() else []
)
current = {
item["source"]: RedirectRule.from_manifest(item) for item in applied
}
if rule is not None:
if rule.source in current:
raise ValidationError(
"Remove the existing redirect for this path first."
)
current[rule.source] = rule
elif source in current:
del current[source]
else:
raise ValidationError("This redirect no longer exists.")
try:
desired = RedirectConfiguration(website, tuple(current.values()))
except ValueError as error:
raise ValidationError(str(error)) from error
if job is None:
WebsiteRedirectPolicy.objects.create(
account=account,
domain=website.domain,
website=website.manifest(),
requested_rules=desired.manifest()["rules"],
requested_customer_id=actor,
)
else:
WebsiteRedirectPolicy.objects.requeue(
WebsiteRedirectPolicy.objects.filter(pk=job.pk),
website=website.manifest(),
requested_rules=desired.manifest()["rules"],
requested_customer_id=actor,
applied_rules=applied,
)
@never_cache
@require_http_methods(("GET", "HEAD", "POST"))
def customer_redirects(request, pk):
customer = customer_for_user(request.user)
if customer is None or getattr(request, "impersonation", None) is not None:
raise PermissionDenied
if not panel_feature_allowed("LOCAL_WEB_ACTIVATION"):
raise Http404
account = get_object_or_404(
HostingAccount, pk=pk, customer=customer, retired_at__isnull=True
)
sites = hosted_redirect_targets(account)
try:
domain = canonical_domain(
request.GET.get(
"domain", next(iter(sites), account.primary_domain)
)
)
except ValueError as error:
raise Http404 from error
website = sites.get(domain)
if "domain" in request.GET and website is None:
raise Http404
kind = request.GET.get("tab", "site")
if kind not in {"site", "domain"}:
raise Http404
action = request.POST.get("action")
problem = ""
form = RedirectForm(
request.POST if action == "create" else None,
kind=kind,
)
if request.method == "POST":
if website is None or action not in {"create", "remove"}:
raise Http404
if action == "remove" or form.is_valid():
try:
request_redirect_change(
account,
website,
customer.pk,
rule=form.rule if action == "create" else None,
source=request.POST.get("source"),
)
except HostingAccount.DoesNotExist:
raise Http404 from None
except ValidationError as error:
problem = " ".join(error.messages)
else:
return redirect(
reverse(
"panel:customer_redirects",
args=[pk],
query={"domain": domain, "tab": kind},
)
)
job = (
account.redirect_policies.filter(
domain=domain, website=website.manifest()
).first()
if website
else None
)
return render(
request,
"hosting/customer_redirects.html",
{
"account": account,
"sites": sites,
"domain": domain,
"kind": kind,
"form": form,
"problem": problem,
"job": job,
"redirects": [
rule
for rule in job.applied_rules
if (rule["source"] == "*") == (kind == "domain")
]
if job
else [],
},
)
@@ -165,6 +165,13 @@ def save_operator_account(account, actor, *, changed_fields=None):
require_open_account(previous) require_open_account(previous)
if "primary_domain" in changed_fields: if "primary_domain" in changed_fields:
require_active_services(previous) require_active_services(previous)
if {"customer", "primary_domain"}.intersection(
changed_fields
) and previous.folder_sftp_logins.exists():
raise ValidationError(
"Remove folder SFTP logins before changing the customer "
"or primary domain."
)
previous_reseller_id = previous.reseller_id previous_reseller_id = previous.reseller_id
reseller_id = ( reseller_id = (
account.reseller_id account.reseller_id
+6 -1
View File
@@ -12,6 +12,7 @@ from django.utils import timezone
from django.views.decorators.debug import sensitive_variables from django.views.decorators.debug import sensitive_variables
from coulobre.credential_rotation import valid_generation from coulobre.credential_rotation import valid_generation
from coulobre.database_login import DatabaseLoginSpec
from coulobre.service_credentials import ( from coulobre.service_credentials import (
CREDENTIAL_SOCKET, CREDENTIAL_SOCKET,
CREDENTIAL_TIMEOUT_SECONDS, CREDENTIAL_TIMEOUT_SECONDS,
@@ -172,7 +173,11 @@ def fetch_service_credentials(resource, rotation=None):
if spec.kind == CredentialKind.DATABASE: if spec.kind == CredentialKind.DATABASE:
keys += ("database", "host", "socket") keys += ("database", "host", "socket")
expected = { expected = {
"database": resource.name, "database": (
resource.database.name
if isinstance(resource, DatabaseLoginSpec)
else resource.name
),
"user": resource.name, "user": resource.name,
"host": "localhost", "host": "localhost",
} }
+166 -5
View File
@@ -44,8 +44,10 @@ from .models import (
AccountRetirementJob, AccountRetirementJob,
AccountServiceJob, AccountServiceJob,
ComponentRestoreJob, ComponentRestoreJob,
DatabaseLogin,
DatabaseProvisioning, DatabaseProvisioning,
DnsPublication, DnsPublication,
FolderSftpLogin,
HostingAccount, HostingAccount,
HostingMailDomain, HostingMailDomain,
IndependentWebsite, IndependentWebsite,
@@ -65,6 +67,7 @@ from .models import (
WebProvisioningPlan, WebProvisioningPlan,
WebsiteAlias, WebsiteAlias,
WebsiteCertificateJob, WebsiteCertificateJob,
WebsiteRedirectPolicy,
WebsiteRestoreJob, WebsiteRestoreJob,
WebsiteScheduledJob, WebsiteScheduledJob,
) )
@@ -170,6 +173,11 @@ def render_web_plan(plan_id):
@shared_task @shared_task
def dispatch_web_activations(): def dispatch_web_activations():
if settings.LOCAL_WEB_ACTIVATION: if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
WebsiteRedirectPolicy,
deploy_website_redirects,
WEB_ACTIVATION_QUEUE,
)
dispatch_provisioning_jobs( dispatch_provisioning_jobs(
IndependentWebsite, IndependentWebsite,
provision_independent_website, provision_independent_website,
@@ -250,12 +258,21 @@ def dispatch_web_https():
@shared_task @shared_task
def dispatch_web_sftp(): def dispatch_web_sftp():
if settings.LOCAL_WEB_SFTP: if settings.LOCAL_WEB_SFTP:
if settings.LOCAL_FOLDER_SFTP:
dispatch_provisioning_jobs(
FolderSftpLogin, apply_folder_sftp_job, WEB_SFTP_QUEUE
)
dispatch_provisioning_jobs(SiteSFTP, update_web_sftp, WEB_SFTP_QUEUE) dispatch_provisioning_jobs(SiteSFTP, update_web_sftp, WEB_SFTP_QUEUE)
@shared_task @shared_task
def dispatch_database_provisioning(): def dispatch_database_provisioning():
if settings.LOCAL_DATABASE_PROVISIONING: if settings.LOCAL_DATABASE_PROVISIONING:
dispatch_provisioning_jobs(
DatabaseLogin,
provision_database_login,
DATABASE_PROVISIONING_QUEUE,
)
dispatch_provisioning_jobs( dispatch_provisioning_jobs(
DatabaseProvisioning, DatabaseProvisioning,
provision_database, provision_database,
@@ -828,6 +845,23 @@ def create_account_backup(job_id):
def apply_account_backup(job): def apply_account_backup(job):
if job.export_customer_id is None:
return create_backup_job_archive(job)
with transaction.atomic():
try:
job.account = lock_hosting_account(
job.account_id, job.export_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account's customer assignment changed."
) from None
if job.account.retired_at is not None:
raise ValueError("The hosting account is retired.")
return create_backup_job_archive(job)
def create_backup_job_archive(job):
backup = AccountBackup.from_manifest(job.manifest) backup = AccountBackup.from_manifest(job.manifest)
if backup.website.account_id != job.account_id: if backup.website.account_id != job.account_id:
raise ValueError("The backup manifest belongs to a different account.") raise ValueError("The backup manifest belongs to a different account.")
@@ -855,17 +889,13 @@ def apply_account_backup(job):
raise ValueError( raise ValueError(
"Enable local mailbox backups before trying again." "Enable local mailbox backups before trying again."
) )
if (
job.export_customer_id is not None
and job.export_customer_id != job.account.customer_id
):
raise ValueError("The hosting account's customer assignment changed.")
size = create_local_account_backup( size = create_local_account_backup(
AccountBackupRequest( AccountBackupRequest(
job.backup_id, job.backup_id,
backup, backup,
remote_mail=job.remote_mail, remote_mail=job.remote_mail,
publish_to_customer=job.export_customer_id is not None, publish_to_customer=job.export_customer_id is not None,
database_suffix=job.export_database_suffix,
) )
) )
return {"archive_bytes": size} return {"archive_bytes": size}
@@ -1462,3 +1492,134 @@ def apply_certificate_job(job_id):
WebsiteCertificateJob.objects.filter( WebsiteCertificateJob.objects.filter(
pk=job_id, finished_at__isnull=False pk=job_id, finished_at__isnull=False
).exclude(encrypted_upload="").update(encrypted_upload="") ).exclude(encrypted_upload="").update(encrypted_upload="")
@shared_task(acks_late=True, reject_on_worker_lost=True)
def deploy_website_redirects(job_id):
from coulobre.web_redirects import OPERATION, RedirectConfiguration
from .node_client import apply_on_local_node
from .redirect_views import hosted_redirect_targets
def apply(job):
with transaction.atomic():
try:
account = lock_hosting_account(
job.account_id, job.requested_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account is no longer available."
) from None
request = RedirectConfiguration.from_manifest(
{
"operation": OPERATION,
"website": job.website,
"rules": job.requested_rules,
}
)
if (
account.retired_at is not None
or account.services_suspended
or hosted_redirect_targets(account).get(job.domain)
!= request.website
):
raise ValueError("The website is no longer available.")
apply_on_local_node(
request,
"/run/coulobre-web-apply.sock",
"web node",
"redirect update",
)
return {"applied_rules": job.requested_rules}
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
WebsiteRedirectPolicy.objects.all(),
job_id,
apply,
"The web node did not confirm the website redirect update.",
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_database_login(job_id):
from coulobre.database_login import DatabaseLoginRequest
from .node_client import apply_on_local_node
def apply(job):
with transaction.atomic():
try:
account = lock_hosting_account(
job.database.account_id, job.requested_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account is no longer available."
) from None
if account.retired_at is not None or account.services_suspended:
raise ValueError("The hosting account is inactive.")
spec = DatabaseLoginRequest(job.spec, job.access, job.action)
apply_on_local_node(
spec,
"/run/coulobre-database-apply.sock",
"MariaDB node",
"database login",
)
return {}
if settings.LOCAL_DATABASE_PROVISIONING:
run_provisioning_job(
DatabaseLogin.objects.select_related("database"),
job_id,
apply,
"The MariaDB node did not confirm the login operation.",
)
DatabaseLogin.objects.filter(
pk=job_id, action="remove", problem="", finished_at__isnull=False
).delete()
@shared_task(acks_late=True, reject_on_worker_lost=True)
def apply_folder_sftp_job(job_id):
from coulobre.folder_sftp import FOLDER_SOCKET
from .node_client import apply_on_local_node
def apply(job):
with transaction.atomic():
try:
account = lock_hosting_account(
job.account_id, job.requested_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account is no longer available."
) from None
if (
account.retired_at is not None
or account.primary_domain != job.domain
or (account.services_suspended and job.action != "remove")
):
raise ValueError("The hosting account is inactive.")
spec = job.spec
apply_on_local_node(
spec,
FOLDER_SOCKET,
"web node",
"folder SFTP login",
identity=spec.identity(),
)
return {}
if settings.LOCAL_FOLDER_SFTP:
run_provisioning_job(
FolderSftpLogin.objects.all(),
job_id,
apply,
"The hosting node did not confirm the folder SFTP operation.",
)
FolderSftpLogin.objects.filter(
pk=job_id, action="remove", problem="", finished_at__isnull=False
).delete()
@@ -1,6 +1,7 @@
<VirtualHost *:$port> <VirtualHost *:$port>
ServerName $domain ServerName $domain
DocumentRoot "$document_root" DocumentRoot "$document_root"
IncludeOptional "$redirect_rules"
$tls_settings $tls_settings
$usage_logs $usage_logs
<Directory "$document_root"> <Directory "$document_root">
@@ -0,0 +1,19 @@
{% extends "hosting/base.html" %}
{% block title %}Databases · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading">
<div><h1>Databases</h1><p class="heading-meta">{{ account.primary_domain }}</p></div>
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">Add database</a>
</header>
<section class="surface"><div class="table-scroll"><table>
<thead><tr><th scope="col">Database</th><th scope="col">State</th><th scope="col">Primary login</th><th scope="col">Additional logins</th></tr></thead>
<tbody>{% for db in databases %}
<tr><th scope="row">{{ db.spec.name }}</th><td>{{ db.provisioning.state|default:"Requested"|capfirst }}</td><td>
{% if db.provisioning.state == 'configured' %}
{% if can_reveal %}<a href="{% url 'panel:database_credentials' db.pk %}">Credentials</a>{% endif %}
{% if show_sso %}<form method="post" class="inline-form" action="{% url 'panel:phpmyadmin_launch' db.pk %}">{% csrf_token %}<button type="submit" class="button secondary">Open phpMyAdmin</button></form>{% endif %}
{% endif %}
</td><td><a href="{% url 'panel:database_logins' db.pk %}">{{ db.logins.count }} · Manage logins</a></td></tr>
{% empty %}<tr><td colspan="4">No databases in this hosting account.</td></tr>{% endfor %}</tbody>
</table></div></section>
{% endblock %}
@@ -0,0 +1,36 @@
{% extends "hosting/base.html" %}
{% block title %}Redirects · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><div><h1>Redirects</h1><p class="heading-meta">{{ account.primary_domain }}</p></div></header>
{% if sites %}
<section class="surface">
<form method="get" class="toolbar form-actions">
<label for="redirect-domain">Website or alias</label>
<select id="redirect-domain" name="domain">{% for candidate in sites %}<option value="{{ candidate }}"{% if candidate == domain %} selected{% endif %}>{{ candidate }}</option>{% endfor %}</select>
<input type="hidden" name="tab" value="{{ kind }}">
<button type="submit" class="button secondary">Select hostname</button>
</form>
</section>
<nav class="account-navigation" aria-label="Redirects">
<a href="?tab=domain&amp;domain={{ domain }}"{% if kind == 'domain' %} aria-current="page"{% endif %}>Domain redirects</a>
<a href="?tab=site&amp;domain={{ domain }}"{% if kind == 'site' %} aria-current="page"{% endif %}>Site redirects</a>
</nav>
{% if job and not job.finished_at %}<p class="notice">{{ job.state|capfirst }} · <a href="?tab={{ kind }}&amp;domain={{ domain }}">Refresh status</a></p>{% endif %}
{% if problem %}<p class="notice" role="alert">{{ problem }}</p>{% endif %}
{% if job.problem %}<p class="notice" role="alert">{{ job.problem }}</p>{% endif %}
<section class="surface"><div class="table-scroll"><table>
<thead><tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Status</th><th scope="col">Actions</th></tr></thead>
<tbody>{% for row in redirects %}<tr>
<th scope="row">{{ domain }}{% if kind == 'site' %}{{ row.source }}{% endif %}</th>
<td><code>{{ row.destination }}</code></td><td>{{ row.status }}</td>
<td><form method="post">{% csrf_token %}<input type="hidden" name="source" value="{{ row.source }}"><button type="submit" class="button secondary" name="action" value="remove"{% if job and not job.finished_at %} disabled{% endif %}>Remove</button></form></td>
</tr>{% empty %}<tr><td colspan="4">No redirects of this type.</td></tr>{% endfor %}</tbody>
</table></div></section>
<section class="surface editor-surface">
<h2>Add {% if kind == 'domain' %}domain{% else %}site{% endif %} redirect</h2>
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}
<button type="submit" class="button primary" name="action" value="create"{% if job and not job.finished_at %} disabled{% endif %}>Add redirect</button>
</form>
</section>
{% else %}<p class="notice">Activate a website or an alias before adding redirects.</p>{% endif %}
{% endblock %}
@@ -0,0 +1,43 @@
{% extends "hosting/base.html" %}
{% block title %}Database logins · Coulobre Panel <section class="surface editor-surface">
<h2>SQL export</h2>
{% if export_job %}<p>{{ export_job.state|capfirst }} · {{ export_job.requested_at|date:"j M Y H:i" }} UTC</p>{% endif %}
{% if export_job.state == 'configured' %}<p>Download over SFTP at <code>/backups/database-{{ database.suffix }}.sql.gz</code>.</p>{% endif %}
{% if export_job.problem %}<p>{{ export_job.problem }}</p>{% endif %}
{% if can_export %}<form method="post" action="{% url 'panel:database_export' database.pk %}">{% csrf_token %}
<button type="submit" class="button secondary"{% if export_job and not export_job.finished_at %} disabled{% endif %}>Export SQL</button>
</form>{% else %}<p>SQL exports require the account's SFTP and backup services.</p>{% endif %}
</section>
{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'panel:customer_databases' database.account_id %}">← Databases</a>
<header class="page-heading"><div><h1>Database logins</h1><p class="heading-meta">{{ database.spec.name }}</p></div></header>
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
{% if problem %}<p class="notice" role="alert">{{ problem }}</p>{% endif %}
<section class="surface"><div class="table-scroll"><table>
<thead><tr><th scope="col">Login</th><th scope="col">Access</th><th scope="col">State</th><th scope="col">Actions</th></tr></thead>
<tbody>{% for login in logins %}<tr>
<th scope="row">{{ login.label }}<br><code>{{ login.spec.name }}</code></th><td>{{ login.get_access_display }}</td><td>{{ login.state|capfirst }}{% if login.problem %}<p>{{ login.problem }}</p>{% endif %}</td>
<td>
{% if login.state == 'configured' and login.action == 'grant' %}
{% if can_reveal %}<a href="{% url 'panel:database_login_credentials' login.pk %}">Credentials</a>{% endif %}
{% if show_sso %}<form method="post" class="inline-form" action="{% url 'panel:phpmyadmin_login' login.pk %}">{% csrf_token %}<button type="submit" class="button secondary">Open phpMyAdmin</button></form>{% endif %}
{% endif %}
{% if login.finished_at %}<form method="post" class="inline-form">{% csrf_token %}<input type="hidden" name="login" value="{{ login.pk }}"><button class="button secondary" type="submit" name="action" value="remove">Remove login</button></form>{% endif %}
</td>
</tr>{% empty %}<tr><td colspan="4">No additional logins.</td></tr>{% endfor %}</tbody>
</table></div></section>
<section class="surface editor-surface">
<h2>Add database login</h2>
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}<button class="button primary" name="action" value="add" type="submit">Add login</button></form>
</section>
<section class="surface editor-surface">
<h2>SQL export</h2>
{% if export_job %}<p>{{ export_job.state|capfirst }} · {{ export_job.requested_at|date:"j M Y H:i" }} UTC</p>{% endif %}
{% if export_job.state == 'configured' %}<p>Download over SFTP at <code>/backups/database-{{ database.suffix }}.sql.gz</code>.</p>{% endif %}
{% if export_job.problem %}<p>{{ export_job.problem }}</p>{% endif %}
{% if can_export %}<form method="post" action="{% url 'panel:database_export' database.pk %}">{% csrf_token %}
<button type="submit" class="button secondary"{% if export_job and not export_job.finished_at %} disabled{% endif %}>Export SQL</button>
</form>{% else %}<p>SQL exports require the account's SFTP and backup services.</p>{% endif %}
</section>
{% endblock %}
@@ -0,0 +1,35 @@
{% extends "hosting/base.html" %}
{% block title %}SFTP Users · Coulobre Panel{% endblock %}
{% block content %}
<header class="page-heading"><div><h1>SFTP Users</h1><p class="heading-meta">{{ account.primary_domain }}</p></div></header>
{% if problem %}<p class="notice" role="alert">{{ problem }}</p>{% endif %}
<section class="surface">
<header class="section-heading"><div><h2>Primary hosting login</h2><p>Access to the hosting account, including files in <code>/backups</code>.</p></div>
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">Manage SSH keys</a></header>
</section>
<section class="surface"><div class="table-scroll"><table>
<thead><tr><th scope="col">Folder login</th><th scope="col">Website folder</th><th scope="col">State</th><th scope="col">Actions</th></tr></thead>
<tbody>{% for entry in logins %}
<tr><th scope="row">{{ entry.label }}<br><code>{{ entry.spec.username }}</code></th><td>{{ entry.folder|default:"Entire website" }}</td>
<td>{{ entry.state|capfirst }}{% if entry.problem %}<p>{{ entry.problem }}</p>{% endif %}</td>
<td>{% if enabled and entry.finished_at %}
<a class="button secondary" href="?login={{ entry.pk }}">Manage keys</a>
<form method="post" class="inline-form" action="?login={{ entry.pk }}">{% csrf_token %}
<button class="button secondary" name="action" value="remove" type="submit">Remove access</button>
</form>
{% endif %}</td>
</tr>
{% empty %}<tr><td colspan="4">No folder logins.</td></tr>{% endfor %}</tbody>
</table></div></section>
{% if enabled %}
<section class="surface editor-surface">
<h2>{% if login %}SSH keys for {{ login.label }}{% else %}Add folder login{% endif %}</h2>
<form method="post" class="editor">{% csrf_token %}{{ form.as_div }}
<div class="form-actions">
<button class="button primary" name="action" value="{% if login %}keys{% else %}create{% endif %}" type="submit">{% if login %}Save keys{% else %}Add folder login{% endif %}</button>
{% if login %}<a class="button secondary" href="{% url 'panel:folder_sftp_users' account.pk %}">Cancel</a>{% endif %}
</div>
</form>
</section>
{% else %}<p class="notice">Folder logins require the scoped SFTP worker on the web server.</p>{% endif %}
{% endblock %}
+7 -1
View File
@@ -136,7 +136,7 @@ class MailPolicyTests(TestCase):
self.client.post(self.routing, data), self.routing self.client.post(self.routing, data), self.routing
) )
def test_reseller_can_schedule_replies_and_an_outsider_cannot_access_them( def test_customer_replies_respect_account_scope_and_repeat_interval(
self, self,
): ):
data = { data = {
@@ -145,12 +145,17 @@ class MailPolicyTests(TestCase):
"message": "Back Monday.\n— Alice", "message": "Back Monday.\n— Alice",
"starts_at": "2026-11-25T07:30", "starts_at": "2026-11-25T07:30",
"ends_at": "2026-11-30T10:30", "ends_at": "2026-11-30T10:30",
"repeat_days": "3",
} }
self.client.force_login(self.outsider) self.client.force_login(self.outsider)
for url in (self.vacation, self.routing): for url in (self.vacation, self.routing):
self.assertEqual(self.client.get(url).status_code, 404) self.assertEqual(self.client.get(url).status_code, 404)
self.assertEqual(self.client.post(url, data).status_code, 404) self.assertEqual(self.client.post(url, data).status_code, 404)
self.client.force_login(self.reseller) self.client.force_login(self.reseller)
self.assertEqual(
self.client.post(self.vacation, data).status_code, 403
)
self.client.force_login(self.customer)
self.assertContains( self.assertContains(
self.client.post( self.client.post(
self.vacation, data | {"ends_at": "2026-11-25T07:00"} self.vacation, data | {"ends_at": "2026-11-25T07:00"}
@@ -165,6 +170,7 @@ class MailPolicyTests(TestCase):
spec = parse_mail_policy(job.manifest) spec = parse_mail_policy(job.manifest)
self.assertEqual(spec.starts_at, "2026-11-25T07:30:00+00:00") self.assertEqual(spec.starts_at, "2026-11-25T07:30:00+00:00")
self.assertEqual(spec.ends_at, "2026-11-30T10:30:00+00:00") self.assertEqual(spec.ends_at, "2026-11-30T10:30:00+00:00")
self.assertEqual(spec.repeat_days, 3)
with patch( with patch(
"coulobre.hosting.mail_policies.apply_on_local_node" "coulobre.hosting.mail_policies.apply_on_local_node"
) as node: ) as node:
@@ -377,7 +377,10 @@ class SignInLimitsTests(TestCase):
self.assertEqual(client_address(request), "unknown") self.assertEqual(client_address(request), "unknown")
@override_settings(TRUST_APACHE_CLIENT_IP=False) @override_settings(TRUST_APACHE_CLIENT_IP=False)
def test_sign_in_limit_cannot_be_reset_with_a_forwarded_header(self): @patch("coulobre.hosting.sign_in_limits.current_window", return_value=1)
def test_sign_in_limit_cannot_be_reset_with_a_forwarded_header(
self, _window
):
url = reverse("panel:login") url = reverse("panel:login")
for attempt in range(9): for attempt in range(9):
response = self.client.post( response = self.client.post(
+43
View File
@@ -23,9 +23,16 @@ from .backup_restores import RestoreKind
from .certificate_views import customer_certificates, operator_certificates from .certificate_views import customer_certificates, operator_certificates
from .credential_views import DatabaseCredentialView, MailboxCredentialView from .credential_views import DatabaseCredentialView, MailboxCredentialView
from .customer_backup_views import CustomerBackupView, CustomerRestoreView from .customer_backup_views import CustomerBackupView, CustomerRestoreView
from .database_login_views import (
DatabaseLoginCredentialView,
customer_databases,
database_login_editor,
database_sql_export,
)
from .dns_defaults_views import DnsDefaultsView from .dns_defaults_views import DnsDefaultsView
from .dns_replica_views import DnsReplicaView from .dns_replica_views import DnsReplicaView
from .domain_services import domain_workspace from .domain_services import domain_workspace
from .folder_sftp_views import folder_sftp_users
from .health_views import ServiceHealthView from .health_views import ServiceHealthView
from .independent_website_views import ( from .independent_website_views import (
IndependentWebsiteCreate, IndependentWebsiteCreate,
@@ -55,6 +62,7 @@ from .password_reset import (
CustomerResetDoneView, CustomerResetDoneView,
) )
from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin from .phpmyadmin import PhpMyAdminLaunch, redeem_phpmyadmin
from .redirect_views import customer_redirects
from .reseller_onboarding_views import ( from .reseller_onboarding_views import (
ResellerCustomerCreate, ResellerCustomerCreate,
ResellerCustomerLink, ResellerCustomerLink,
@@ -87,12 +95,47 @@ from .workspaces import customer_workspace, system_workspace
app_name = "panel" app_name = "panel"
urlpatterns = [ urlpatterns = [
path(
"hosting/<int:pk>/databases/",
customer_databases,
name="customer_databases",
),
path(
"databases/<int:pk>/logins/",
database_login_editor,
name="database_logins",
),
path(
"database-logins/<int:pk>/credentials/",
DatabaseLoginCredentialView.as_view(),
name="database_login_credentials",
),
path(
"database-logins/<int:pk>/phpmyadmin/",
PhpMyAdminLaunch.as_view(secondary=True),
name="phpmyadmin_login",
),
path(
"databases/<int:pk>/export/",
database_sql_export,
name="database_export",
),
path(
"hosting/<int:pk>/sftp/",
folder_sftp_users,
name="folder_sftp_users",
),
path("ssl/", operator_certificates, name="operator_certificates"), path("ssl/", operator_certificates, name="operator_certificates"),
path( path(
"hosting/<int:pk>/certificates/", "hosting/<int:pk>/certificates/",
customer_certificates, customer_certificates,
name="customer_certificates", name="customer_certificates",
), ),
path(
"hosting/<int:pk>/redirects/",
customer_redirects,
name="customer_redirects",
),
path("mail-delivery/", MailDeliveryView.as_view(), name="mail_delivery"), path("mail-delivery/", MailDeliveryView.as_view(), name="mail_delivery"),
path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"), path("mail-queue/", MailQueueIndex.as_view(), name="mail_queue_index"),
path( path(
+5 -2
View File
@@ -19,11 +19,12 @@ CUSTOMER_ACCOUNT = "coulobre_active_hosting_account"
CUSTOMER_PAGES = { CUSTOMER_PAGES = {
"domains": ("Domains", "account", "websites"), "domains": ("Domains", "account", "websites"),
"dns": ("DNS Editor", "account", "domains-dns"), "dns": ("DNS Editor", "account", "domains-dns"),
"redirects": ("Redirects", "customer_redirects", ""),
"php": ("PHP Settings", "account", "websites"), "php": ("PHP Settings", "account", "websites"),
"files": ("File Manager", "website_files", ""), "files": ("File Manager", "website_files", ""),
"certificates": ("SSL Certificates", "customer_certificates", ""), "certificates": ("SSL Certificates", "customer_certificates", ""),
"sftp": ("SFTP Users", "sftp_keys", ""), "sftp": ("SFTP Users", "folder_sftp_users", ""),
"databases": ("Databases", "account", "databases"), "databases": ("Databases", "customer_databases", ""),
"email": ("Email Accounts", "account", "email"), "email": ("Email Accounts", "account", "email"),
"forwarders": ("Forwarders", "account", "email"), "forwarders": ("Forwarders", "account", "email"),
"replies": ("Automatic replies", "account", "email"), "replies": ("Automatic replies", "account", "email"),
@@ -54,6 +55,7 @@ def customer_pages(request):
pages = CUSTOMER_PAGES.copy() pages = CUSTOMER_PAGES.copy()
for key, enabled in ( for key, enabled in (
("files", panel_feature_allowed("WEB_FILE_MANAGER")), ("files", panel_feature_allowed("WEB_FILE_MANAGER")),
("redirects", panel_feature_allowed("LOCAL_WEB_ACTIVATION")),
("sftp", settings.LOCAL_WEB_SFTP), ("sftp", settings.LOCAL_WEB_SFTP),
("backups", panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")), ("backups", panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")),
("tasks", panel_feature_allowed("WEBSITE_JOBS")), ("tasks", panel_feature_allowed("WEBSITE_JOBS")),
@@ -211,6 +213,7 @@ def groups_for(request, *, customer, manager):
"domains", "domains",
"dns", "dns",
"certificates", "certificates",
"redirects",
"sftp", "sftp",
"databases", "databases",
"php", "php",
+3 -1
View File
@@ -29,7 +29,9 @@ def vacation_script(spec):
for line in spec.message.split("\n") for line in spec.message.split("\n")
) )
reply = ( reply = (
f"vacation :days 7 :subject {sieve_string(spec.subject)} text:\n" f"vacation :days {spec.repeat_days} "
f":subject {sieve_string(spec.subject)} "
"text:\n"
f"{body}\n.\n;\n" f"{body}\n.\n;\n"
) )
if not dates: if not dates:
+20 -3
View File
@@ -8,6 +8,8 @@ from .domain_names import canonical_domain
from .mail_node import LOCAL_PART_MAX_LENGTH, MailboxSpec from .mail_node import LOCAL_PART_MAX_LENGTH, MailboxSpec
MAIL_POLICY_LIMIT = 64 * 1024 MAIL_POLICY_LIMIT = 64 * 1024
DEFAULT_REPEAT_DAYS = 7
MAX_REPEAT_DAYS = 60
MAX_ALIASES = 100 MAX_ALIASES = 100
MAX_DESTINATIONS = 10 MAX_DESTINATIONS = 10
OPERATIONS = ("set_mail_routing", "set_mail_vacation") OPERATIONS = ("set_mail_routing", "set_mail_vacation")
@@ -122,8 +124,14 @@ class MailVacation(MailPolicy):
message: str = "" message: str = ""
starts_at: str = "" starts_at: str = ""
ends_at: str = "" ends_at: str = ""
repeat_days: int = DEFAULT_REPEAT_DAYS
def __post_init__(self): def __post_init__(self):
if (
type(self.repeat_days) is not int
or not 1 <= self.repeat_days <= MAX_REPEAT_DAYS
):
raise ValueError("Choose a reply interval between 1 and 60 days.")
if type(self.enabled) is not bool: if type(self.enabled) is not bool:
raise ValueError("Choose whether to enable the autoresponder.") raise ValueError("Choose whether to enable the autoresponder.")
if not isinstance(self.subject, str) or not isinstance( if not isinstance(self.subject, str) or not isinstance(
@@ -168,7 +176,11 @@ class MailVacation(MailPolicy):
"message": self.message, "message": self.message,
"starts_at": self.starts_at, "starts_at": self.starts_at,
"ends_at": self.ends_at, "ends_at": self.ends_at,
} } | (
{"repeat_days": self.repeat_days}
if self.repeat_days != DEFAULT_REPEAT_DAYS
else {}
)
def parse_mail_policy(data): def parse_mail_policy(data):
@@ -184,14 +196,18 @@ def parse_mail_policy(data):
return MailRouting( return MailRouting(
data["domain"], data["aliases"], data["catchall"] data["domain"], data["aliases"], data["catchall"]
) )
if data.get("operation") == "set_mail_vacation" and fields == { vacation_fields = {
"mailbox", "mailbox",
"enabled", "enabled",
"subject", "subject",
"message", "message",
"starts_at", "starts_at",
"ends_at", "ends_at",
}: }
if data.get("operation") == "set_mail_vacation" and fields in (
vacation_fields,
vacation_fields | {"repeat_days"},
):
return MailVacation( return MailVacation(
MailboxSpec.from_manifest(data["mailbox"]), MailboxSpec.from_manifest(data["mailbox"]),
data["enabled"], data["enabled"],
@@ -199,5 +215,6 @@ def parse_mail_policy(data):
data["message"], data["message"],
data["starts_at"], data["starts_at"],
data["ends_at"], data["ends_at"],
data.get("repeat_days", DEFAULT_REPEAT_DAYS),
) )
raise ValueError("Expected a version 1 mail policy.") raise ValueError("Expected a version 1 mail policy.")
+21 -3
View File
@@ -3,6 +3,7 @@ import os
from dataclasses import dataclass from dataclasses import dataclass
from .credential_rotation import valid_generation from .credential_rotation import valid_generation
from .database_login import LOGIN_KIND, DatabaseLoginSpec
from .database_node import DEFAULT_SOCKET, DatabaseSpec from .database_node import DEFAULT_SOCKET, DatabaseSpec
from .mail_node import MailboxSpec from .mail_node import MailboxSpec
from .node_requests import serve_apply_request from .node_requests import serve_apply_request
@@ -18,12 +19,17 @@ CREDENTIALS_UNAVAILABLE = "The service credentials are currently unavailable."
@dataclass(frozen=True) @dataclass(frozen=True)
class ServiceCredentialRequest: class ServiceCredentialRequest:
resource: DatabaseSpec | MailboxSpec resource: DatabaseSpec | DatabaseLoginSpec | MailboxSpec
operation: str = "read" operation: str = "read"
rotation_id: str | None = None rotation_id: str | None = None
previous_id: str | None = None previous_id: str | None = None
def __post_init__(self): def __post_init__(self):
if (
isinstance(self.resource, DatabaseLoginSpec)
and self.operation != "read"
):
raise ValueError("This login supports credential retrieval only.")
if self.operation in ("read", "generation"): if self.operation in ("read", "generation"):
if self.rotation_id is None and self.previous_id is None: if self.rotation_id is None and self.previous_id is None:
return return
@@ -41,7 +47,7 @@ class ServiceCredentialRequest:
def kind(self): def kind(self):
return ( return (
"database" "database"
if isinstance(self.resource, DatabaseSpec) if isinstance(self.resource, (DatabaseSpec, DatabaseLoginSpec))
else "mailbox" else "mailbox"
) )
@@ -70,8 +76,16 @@ class ServiceCredentialRequest:
raise ValueError( raise ValueError(
"Expected a database or mailbox credential request." "Expected a database or mailbox credential request."
) )
resource = data["resource"]
parser = parsers[kind]
if (
kind == "database"
and isinstance(resource, dict)
and resource.get("kind") == LOGIN_KIND
):
parser = DatabaseLoginSpec.from_manifest
return cls( return cls(
parsers[kind](data["resource"]), parser(resource),
operation, operation,
data.get("rotation_id"), data.get("rotation_id"),
data.get("previous_id"), data.get("previous_id"),
@@ -123,6 +137,10 @@ def read_service_credentials(request):
raise ValueError(CREDENTIALS_UNAVAILABLE) raise ValueError(CREDENTIALS_UNAVAILABLE)
try: try:
if isinstance(request.resource, DatabaseLoginSpec):
from .database_node_logins import secondary_credentials
return secondary_credentials(request.resource, DEFAULT_SOCKET)
if request.operation == "rotate": if request.operation == "rotate":
return rotate_service_credentials(request) return rotate_service_credentials(request)
read = ( read = (
+3
View File
@@ -222,6 +222,9 @@ LOCAL_WEB_HTTPS = os.environ.get("COULOBRE_LOCAL_WEB_HTTPS") == "1"
WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1" WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1"
WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1" WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1"
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1" LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
LOCAL_FOLDER_SFTP = (
LOCAL_WEB_SFTP and os.environ.get("COULOBRE_LOCAL_FOLDER_SFTP") == "1"
)
LOCAL_DATABASE_PROVISIONING = ( LOCAL_DATABASE_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1" os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") == "1"
) )
+19
View File
@@ -123,12 +123,14 @@ class WebSite:
+ options.render_overrides() + options.render_overrides()
) )
from .web_node_usage import apache_log_directives from .web_node_usage import apache_log_directives
from .web_redirects import redirect_include
return template.substitute( return template.substitute(
values, values,
port=port, port=port,
tls_settings=tls_settings, tls_settings=tls_settings,
usage_logs=apache_log_directives(self).rstrip(), usage_logs=apache_log_directives(self).rstrip(),
redirect_rules=redirect_include(self.node_key, values["domain"]),
) )
@@ -259,6 +261,14 @@ class WebPhpRequest:
def parse_web_request(data): def parse_web_request(data):
if (
isinstance(data, dict)
and data.get("operation") == "set_website_redirects"
):
from .web_redirects import RedirectConfiguration
return RedirectConfiguration.from_manifest(data)
return parse_retirement(data, WebSite.from_manifest, parse_web_apply) return parse_retirement(data, WebSite.from_manifest, parse_web_apply)
@@ -363,6 +373,14 @@ class WebPhpVersionRequest:
def apply_web_request(request): def apply_web_request(request):
from .web_redirects import RedirectConfiguration
if isinstance(request, RedirectConfiguration):
from .web_node_redirects import apply_redirects
apply_redirects(request)
return None
if isinstance(request, WebActivationRequest): if isinstance(request, WebActivationRequest):
from .web_node_apply import apply_site_with_runtime from .web_node_apply import apply_site_with_runtime
@@ -539,6 +557,7 @@ def main(argv=None):
MANIFEST_VERSION, MANIFEST_VERSION,
parse_web_request, parse_web_request,
apply_web_request, apply_web_request,
limit=32768,
include_result=True, include_result=True,
) )
+34 -6
View File
@@ -3,7 +3,12 @@ import os
from pathlib import Path from pathlib import Path
from . import web_node_apply as web from . import web_node_apply as web
from .node_files import read_root_file, require_root_directory, write_new_file from .node_files import (
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
APACHE_CONFIG = Path("/etc/apache2/conf-enabled") APACHE_CONFIG = Path("/etc/apache2/conf-enabled")
SSH_CONFIG = Path("/etc/ssh/sshd_config.d") SSH_CONFIG = Path("/etc/ssh/sshd_config.d")
@@ -44,6 +49,14 @@ def set_sftp_access(site, suspended):
user = site.configuration()["service_user"] user = site.configuration()["service_user"]
path = sftp_suspension_path(site) path = sftp_suspension_path(site)
names = {user}
previous = {f"DenyUsers {user}\n"}
if site.site_id is None:
from .folder_sftp import folder_user_prefix
names.add(folder_user_prefix(site) + "*")
config = f"DenyUsers {' '.join(sorted(names))}\n"
def validate(): def validate():
configuration = web.run( configuration = web.run(
"/usr/sbin/sshd", "/usr/sbin/sshd",
@@ -57,17 +70,25 @@ def set_sftp_access(site, suspended):
if line.startswith("denyusers ") if line.startswith("denyusers ")
for name in line.split()[1:] for name in line.split()[1:]
} }
if suspended and user not in denied: if suspended and not names.issubset(denied):
raise ValueError( raise ValueError(
"OpenSSH did not include the suspension configuration." "OpenSSH did not include the suspension configuration."
) )
set_configuration( set_configuration(
site, suspended, path, f"DenyUsers {user}\n", validate, "ssh" site,
suspended,
path,
config,
validate,
"ssh",
previous=previous,
) )
def set_configuration(site, suspended, path, config, validate, service): def set_configuration(
site, suspended, path, config, validate, service, *, previous=()
):
if os.geteuid() != 0: if os.geteuid() != 0:
raise ValueError( raise ValueError(
"Run the service access request as root on the web node." "Run the service access request as root on the web node."
@@ -76,13 +97,20 @@ def set_configuration(site, suspended, path, config, validate, service):
with web.locked_web_node(fcntl.LOCK_EX): with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(site) web.check_reservation(site)
existed = os.path.lexists(path) existed = os.path.lexists(path)
if existed and read_root_file(path, mode=0o644) != config: actual = read_root_file(path, mode=0o644) if existed else None
if existed and actual not in (config, *previous):
raise ValueError(f"Unexpected configuration at {path}.") raise ValueError(f"Unexpected configuration at {path}.")
if existed and suspended and actual != config:
replace_configuration(path, config)
else:
write_access_configuration(path, config, existed, suspended) write_access_configuration(path, config, existed, suspended)
try: try:
validate() validate()
except (OSError, ValueError): except (OSError, ValueError):
write_access_configuration(path, config, suspended, existed) if actual is None:
path.unlink(missing_ok=True)
else:
replace_configuration(path, actual)
raise raise
# A reload may have taken effect even if the result was lost. # A reload may have taken effect even if the result was lost.
# Keep the requested file state so retry can reload it again. # Keep the requested file state so retry can reload it again.
+6
View File
@@ -174,6 +174,12 @@ def remove_alias(alias):
disable_alias_vhosts(links) disable_alias_vhosts(links)
for apache, _ in paths: for apache, _ in paths:
apache.unlink(missing_ok=True) apache.unlink(missing_ok=True)
from .web_redirects import redirect_include
rules = Path(redirect_include(alias.site.node_key, alias.domain))
if os.path.lexists(rules):
read_root_file(rules)
rules.unlink()
delete_alias_certificate(alias) delete_alias_certificate(alias)
marker.unlink() marker.unlink()
+2 -2
View File
@@ -496,9 +496,9 @@ def configuration_installation():
def check_configuration(path, content): def check_configuration(path, content):
from .web_node_usage import without_usage_logs from .web_redirects import compatible_configs
if read_root_file(path) not in (content, without_usage_logs(content)): if read_root_file(path) not in compatible_configs(content):
raise ValueError(f"Existing configuration differs at {path}.") raise ValueError(f"Existing configuration differs at {path}.")
+281
View File
@@ -0,0 +1,281 @@
import argparse
import fcntl
import json
import os
import subprocess
from contextlib import contextmanager
from pathlib import Path
from . import web_node_apply as web
from .folder_sftp import FOLDER_LIMIT, FolderSftpRequest, folder_user_prefix
from .node_files import (
check_root_file,
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
from .node_requests import serve_apply_request
from .web_node_access import sftp_suspension_path
from .web_node_sftp import (
AUTHORIZED_KEYS,
SFTP_GROUP,
check_sshd,
validate_public_key,
)
from .website_files import directory_parts
JAIL_ROOT = Path("/srv/coulobre/folder-sftp")
DIRECTORY_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
def folder_state():
return web.STATE_DIRECTORY / "folder-sftp"
@contextmanager
def open_scoped_folder(public, folder):
fd = os.open(public, DIRECTORY_FLAGS)
try:
for component in directory_parts(folder):
child = os.open(component, DIRECTORY_FLAGS, dir_fd=fd)
os.close(fd)
fd = child
yield fd, os.fstat(fd)
finally:
os.close(fd)
def is_bound(mountpoint):
with open("/proc/self/mountinfo", encoding="utf-8") as mounts:
return any(line.split()[4] == str(mountpoint) for line in mounts)
def run_mount(*args, bind_fd=None):
try:
result = subprocess.run(
args,
pass_fds=(bind_fd,) if bind_fd is not None else (),
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
timeout=10,
env={
"PATH": "/usr/sbin:/usr/bin",
"LIBMOUNT_FORCE_MOUNT2": "never",
},
)
except (OSError, subprocess.TimeoutExpired):
raise ValueError(
"The SFTP filesystem operation did not complete."
) from None
if result.returncode:
raise ValueError(
"The filesystem could not apply the scoped SFTP mount."
)
def bind_folder(fd, info, mountpoint, uid, gid):
if not is_bound(mountpoint):
mapping = (
f"X-mount.idmap=u:{info.st_uid}:{uid}:1 g:{info.st_gid}:{gid}:1"
)
run_mount(
"/usr/bin/mount",
"--no-canonicalize",
"--bind",
"-o",
f"nosuid,nodev,noexec,{mapping}",
f"/proc/self/fd/{fd}",
str(mountpoint),
bind_fd=fd,
)
target = mountpoint.stat()
if (target.st_uid, target.st_gid) != (uid, gid) or (
target.st_dev,
target.st_ino,
) != (info.st_dev, info.st_ino):
run_mount("/usr/bin/umount", str(mountpoint))
raise ValueError("The SFTP mount did not match the approved folder.")
def current_scope(request, marker):
saved = json.loads(read_root_file(marker, mode=0o600))
if (
not isinstance(saved, dict)
or saved.keys() != {"scope", "device", "inode"}
or saved["scope"] != request.scope()
or type(saved["device"]) is not int
or type(saved["inode"]) is not int
):
raise ValueError("The folder login has a different node registration.")
return saved
def prepare_jail(request, marker, jail):
public, owner, web_group = web.site_storage(request.site)
require_root_directory(jail, create_mode=0o755)
mountpoint = jail / "public"
if not os.path.lexists(mountpoint):
mountpoint.mkdir(mode=0o000)
if not is_bound(mountpoint):
require_root_directory(mountpoint)
if mountpoint.stat().st_mode & 0o777:
raise ValueError("The unmounted jail must be inaccessible.")
username = request.username
with open_scoped_folder(public, request.folder) as (fd, info):
if (
info.st_uid != owner
or info.st_gid
not in {
web_group,
web.current_user(request.site.service_user).pw_gid,
}
or info.st_dev != public.stat().st_dev
):
raise ValueError("Choose a folder owned by the hosting account.")
state = {
"scope": request.scope(),
"device": info.st_dev,
"inode": info.st_ino,
}
if not marker.exists():
if web.current_user(username) is not None:
raise ValueError(
"The SFTP login already exists outside Coulobre."
)
write_new_file(marker, json.dumps(state), mode=0o600)
elif state != current_scope(request, marker):
raise ValueError(
"The original authorized folder is no longer available."
)
web.ensure_system_account(username, jail)
user = web.current_user(username)
group = web.current_group(SFTP_GROUP)
if group is None:
raise ValueError("Set up the Coulobre OpenSSH policy first.")
if username not in group.gr_mem:
web.run("/usr/sbin/usermod", "-a", "-G", SFTP_GROUP, username)
check_sshd(username)
bind_folder(fd, info, mountpoint, user.pw_uid, user.pw_gid)
def remove_jail(request, marker, jail, keys):
if not marker.exists():
if web.current_user(request.username) is not None:
raise ValueError("The SFTP user is outside the managed registry.")
return
current_scope(request, marker)
if os.path.lexists(keys):
check_root_file(keys, mode=0o644)
keys.unlink()
user = web.current_user(request.username)
if user:
web.check_system_account(request.username, jail)
try:
subprocess.run(
["/usr/bin/pkill", "-KILL", "-u", str(user.pw_uid)],
check=False,
timeout=10,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except subprocess.TimeoutExpired:
raise ValueError(
"The active SFTP sessions could not be closed."
) from None
mountpoint = jail / "public"
if is_bound(mountpoint):
run_mount("/usr/bin/umount", str(mountpoint))
if user:
web.run("/usr/sbin/userdel", request.username)
for directory in (mountpoint, jail):
if os.path.lexists(directory):
require_root_directory(directory)
directory.rmdir()
marker.unlink()
def apply_folder_sftp(request):
if os.geteuid() != 0:
raise ValueError("Run folder SFTP operations as root on the web node.")
with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(request.site)
require_root_directory(AUTHORIZED_KEYS)
require_root_directory(folder_state(), create_mode=0o700)
require_root_directory(JAIL_ROOT, create_mode=0o755)
keys = AUTHORIZED_KEYS / request.username
marker = folder_state() / f"{request.username}.json"
jail = JAIL_ROOT / request.username
if request.action == "remove":
return remove_jail(request, marker, jail, keys)
if any(
path.exists() for path in (sftp_suspension_path(request.site),)
):
raise ValueError(
"Resume the hosting account before granting access."
)
if request.action == "keys" or os.path.lexists(keys):
current_scope(request, marker)
for number, key in enumerate(request.public_keys.splitlines(), 1):
validate_public_key(key, number)
prepare_jail(request, marker, jail)
if os.path.lexists(keys):
check_root_file(keys, mode=0o644)
replace_configuration(keys, request.public_keys)
def restore_folder_mounts():
if not folder_state().exists():
return
require_root_directory(folder_state())
require_root_directory(JAIL_ROOT)
for marker in sorted(folder_state().glob("cbf-*.json")):
try:
with web.locked_web_node(fcntl.LOCK_EX):
saved = json.loads(read_root_file(marker, mode=0o600))
scope = saved["scope"]
path = AUTHORIZED_KEYS / marker.stem
if not path.exists():
continue
request = FolderSftpRequest.from_manifest(
scope
| {
"action": "keys",
"public_keys": read_root_file(path, mode=0o644),
}
)
if marker.stem != request.username:
raise ValueError(
"Unexpected folder SFTP registry identity."
)
prepare_jail(request, marker, JAIL_ROOT / request.username)
except (OSError, KeyError, ValueError) as error:
print(
f"Folder SFTP identity {marker.stem} is unavailable: {error}"
)
def folder_login_exists(site):
directory = folder_state()
if not directory.exists():
return False
require_root_directory(directory)
return any(directory.glob(folder_user_prefix(site) + "*.json"))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("apply", "restore-mounts"))
arguments = parser.parse_args()
if arguments.action == "restore-mounts":
restore_folder_mounts()
return 0
return serve_apply_request(
1,
FolderSftpRequest.from_manifest,
apply_folder_sftp,
identity=lambda request: request.identity(),
limit=FOLDER_LIMIT,
)
+82
View File
@@ -0,0 +1,82 @@
import fcntl
import os
from pathlib import Path
from . import web_node_apply as web
from .node_files import (
read_root_file,
replace_configuration,
require_root_directory,
)
from .web_node import WebAlias
from .web_node_aliases import alias_marker, alias_paths, read_alias
from .web_node_tls import https_paths, render_https_configuration
from .web_redirects import redirect_include
def apply_redirects(spec):
resource = spec.website
site = resource.site if isinstance(resource, WebAlias) else resource
with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(site)
paths = web.SitePaths.for_site(site)
web.check_installation(site, paths)
if isinstance(resource, WebAlias):
if read_alias(alias_marker(resource)) != resource:
raise ValueError(
"This alias is no longer reserved by the website."
)
http, https = (
alias_paths(resource),
alias_paths(resource, https=True),
)
else:
http, https = (paths.apache, paths.enabled), https_paths(paths)
for directory in (paths.apache.parent, paths.enabled.parent):
require_root_directory(directory)
changes = []
for (available, enabled), rendered in (
(http, resource.render("apache", socket_path=paths.apache_socket)),
(
https,
render_https_configuration(
resource, socket_path=paths.apache_socket
),
),
):
if (available, enabled) == https and not (
os.path.lexists(available) or os.path.lexists(enabled)
):
continue
web.check_configuration(available, rendered)
web.check_site_link(
enabled, Path("../sites-available") / available.name
)
previous = read_root_file(available)
if previous != rendered:
changes.append((available, previous, rendered))
config = Path(redirect_include(site.node_key, resource.domain))
require_root_directory(config.parent, create_mode=0o755)
previous_rules = (
read_root_file(config) if os.path.lexists(config) else None
)
updated = []
reload_attempted = False
try:
replace_configuration(config, spec.render())
for path, previous, rendered in changes:
replace_configuration(path, rendered)
updated.append((path, previous))
web.run("/usr/sbin/apache2ctl", "configtest")
reload_attempted = True
web.run("/usr/sbin/service", "apache2", "reload")
except (ValueError, OSError, KeyboardInterrupt):
for path, previous in reversed(updated):
replace_configuration(path, previous)
if previous_rules is None:
config.unlink(missing_ok=True)
else:
replace_configuration(config, previous_rules)
if reload_attempted:
web.run("/usr/sbin/service", "apache2", "reload")
raise
+5
View File
@@ -116,6 +116,11 @@ def finish_site_retirement(reservation, retirement):
def check_aliases(site): def check_aliases(site):
if site.site_id is None:
from .web_node_folder_sftp import folder_login_exists
if folder_login_exists(site):
raise ValueError("Remove the website's folder SFTP users first.")
directory = alias_directory() directory = alias_directory()
if not os.path.lexists(directory): if not os.path.lexists(directory):
return return
+2 -7
View File
@@ -93,14 +93,9 @@ def route_legacy_site(site, paths):
for socket in (legacy.socket, paths.route) for socket in (legacy.socket, paths.route)
) )
actual = read_root_file(config) actual = read_root_file(config)
from .web_node_usage import without_usage_logs from .web_redirects import compatible_configs
if actual not in ( if actual not in compatible_configs(before, after):
before,
after,
without_usage_logs(before),
without_usage_logs(after),
):
raise ValueError(f"Existing configuration differs at {config}.") raise ValueError(f"Existing configuration differs at {config}.")
if actual != after: if actual != after:
changes.append((config, actual, after)) changes.append((config, actual, after))
+185
View File
@@ -0,0 +1,185 @@
import re
from dataclasses import dataclass
from hashlib import sha256
from typing import TYPE_CHECKING
from urllib.parse import unquote, urlsplit
from .domain_names import canonical_domain
if TYPE_CHECKING:
from .web_node import WebAlias, WebSite
OPERATION = "set_website_redirects"
MAX_RULES = 25
MAX_DESTINATION = 500
REDIRECT_TYPES = {301, 302, 307, 308}
SOURCE = re.compile(r"/[A-Za-z0-9/._~-]{0,180}")
DESTINATION = re.compile(r"[A-Za-z0-9._~:/?\[\]@!&'()*+,;=%#-]+")
CHALLENGE = "/.well-known/acme-challenge"
def redirect_include(node_key, domain):
domain = canonical_domain(domain)
digest = sha256(f"{node_key}:{domain}".encode("ascii")).hexdigest()
return f"/etc/apache2/coulobre-redirects/{digest}.conf"
def valid_destination(url):
if (
not isinstance(url, str)
or len(url) > MAX_DESTINATION
or not DESTINATION.fullmatch(url)
or any(
ord(character) < 32 or ord(character) >= 127
for character in unquote(url)
)
):
raise ValueError("Enter a valid absolute HTTP or HTTPS address.")
try:
parts = urlsplit(url)
canonical_domain(parts.hostname or "")
port = parts.port
except ValueError:
raise ValueError(
"Enter a valid absolute HTTP or HTTPS address."
) from None
if (
parts.scheme not in {"http", "https"}
or parts.username is not None
or parts.password is not None
or port == 0
):
raise ValueError("Enter a valid absolute HTTP or HTTPS address.")
return parts
@dataclass(frozen=True)
class RedirectRule:
source: str
destination: str
status: int
def __post_init__(self):
if not isinstance(self.source, str) or (
self.source != "*"
and (
not SOURCE.fullmatch(self.source)
or "//" in self.source
or any(part in {".", ".."} for part in self.source.split("/"))
or self.source == CHALLENGE
or self.source.startswith(CHALLENGE + "/")
)
):
raise ValueError(
"Use a website path outside the ACME challenge directory."
)
valid_destination(self.destination)
if type(self.status) is not int or self.status not in REDIRECT_TYPES:
raise ValueError("Choose a supported HTTP redirect status.")
def manifest(self):
return {
"source": self.source,
"destination": self.destination,
"status": self.status,
}
@classmethod
def from_manifest(cls, data):
if not isinstance(data, dict) or data.keys() != {
"source",
"destination",
"status",
}:
raise ValueError("Expected a redirect rule.")
return cls(**data)
def render(self):
pattern = (
r"^/(?![.]well-known/acme-challenge(?:/|$)).*$"
if self.source == "*"
else "^" + self.source.replace(".", "[.]") + "$"
)
return (
f'RedirectMatch {self.status} "{pattern}" "{self.destination}"\n'
)
@dataclass(frozen=True)
class RedirectConfiguration:
website: "WebSite | WebAlias"
rules: tuple[RedirectRule, ...]
def __post_init__(self):
if len(self.rules) > MAX_RULES or len(
{x.source for x in self.rules}
) != len(self.rules):
raise ValueError(
"Choose up to 25 rules with distinct source paths."
)
if (
any(rule.source == "*" for rule in self.rules)
and len(self.rules) != 1
):
raise ValueError(
"Remove site redirects before adding a domain redirect."
)
for rule in self.rules:
target = valid_destination(rule.destination)
if canonical_domain(target.hostname) == self.website.domain and (
rule.source == "*" or rule.source == (target.path or "/")
):
raise ValueError(
"The redirect destination would point back to the source."
)
def identity(self):
return {"operation": OPERATION, "website": self.website.manifest()}
def manifest(self):
return self.identity() | {
"rules": [rule.manifest() for rule in self.rules]
}
@classmethod
def from_manifest(cls, data):
from .web_node import WebAlias, WebSite
if data.keys() != {"operation", "website", "rules"} or not isinstance(
data["rules"], list
):
raise ValueError("Expected a website redirect configuration.")
target = data["website"]
if not isinstance(target, dict):
raise ValueError("Expected a website redirect configuration.")
site = (
WebAlias.from_manifest(target)
if "site" in target
else WebSite.from_manifest(target)
)
return cls(
site,
tuple(RedirectRule.from_manifest(rule) for rule in data["rules"]),
)
def render(self):
return "".join(rule.render() for rule in self.rules)
def compatible_configs(*contents):
from .web_node_usage import without_usage_logs
for content in contents:
no_redirects = "".join(
line
for line in content.splitlines(keepends=True)
if not re.fullmatch(
r' IncludeOptional "/etc/apache2/coulobre-redirects/'
r'[a-f0-9]{64}[.]conf"\n',
line,
)
)
yield content
yield no_redirects
yield without_usage_logs(content)
yield without_usage_logs(no_redirects)