182 lines
5.9 KiB
Python
182 lines
5.9 KiB
Python
import argparse
|
|
import os
|
|
from dataclasses import dataclass
|
|
|
|
from .credential_rotation import valid_generation
|
|
from .database_node import DEFAULT_SOCKET, DatabaseSpec
|
|
from .mail_node import MailboxSpec
|
|
from .node_requests import serve_apply_request
|
|
from .receiver_scope import check_mail_service_peer
|
|
|
|
REQUEST_VERSION = 1
|
|
CREDENTIAL_SOCKET = "/run/coulobre-service-credentials.sock"
|
|
MAIL_CREDENTIAL_SOCKET = "/run/coulobre-mail-credentials.sock"
|
|
CREDENTIAL_TIMEOUT_SECONDS = 15
|
|
ROTATION_TIMEOUT_SECONDS = 25
|
|
CREDENTIALS_UNAVAILABLE = "The service credentials are currently unavailable."
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ServiceCredentialRequest:
|
|
resource: DatabaseSpec | MailboxSpec
|
|
operation: str = "read"
|
|
rotation_id: str | None = None
|
|
previous_id: str | None = None
|
|
|
|
def __post_init__(self):
|
|
if self.operation in ("read", "generation"):
|
|
if self.rotation_id is None and self.previous_id is None:
|
|
return
|
|
elif (
|
|
self.operation == "rotate"
|
|
and isinstance(self.rotation_id, str)
|
|
and valid_generation(self.rotation_id)
|
|
and valid_generation(self.previous_id)
|
|
and self.rotation_id != self.previous_id
|
|
):
|
|
return
|
|
raise ValueError("Expected a valid credential operation.")
|
|
|
|
@property
|
|
def kind(self):
|
|
return (
|
|
"database"
|
|
if isinstance(self.resource, DatabaseSpec)
|
|
else "mailbox"
|
|
)
|
|
|
|
@classmethod
|
|
def from_manifest(cls, data):
|
|
if (
|
|
not isinstance(data, dict)
|
|
or type(data.get("version")) is not int
|
|
or data["version"] != REQUEST_VERSION
|
|
):
|
|
raise ValueError("Expected a service credential request.")
|
|
fields = {"version", "kind", "resource"}
|
|
operation = data.get("operation", "read")
|
|
if operation == "generation":
|
|
fields.add("operation")
|
|
elif operation == "rotate":
|
|
fields.update(("operation", "rotation_id", "previous_id"))
|
|
if data.keys() != fields:
|
|
raise ValueError("Expected a service credential request.")
|
|
parsers = {
|
|
"database": DatabaseSpec.from_manifest,
|
|
"mailbox": MailboxSpec.from_manifest,
|
|
}
|
|
kind = data["kind"]
|
|
if not isinstance(kind, str) or kind not in parsers:
|
|
raise ValueError(
|
|
"Expected a database or mailbox credential request."
|
|
)
|
|
return cls(
|
|
parsers[kind](data["resource"]),
|
|
operation,
|
|
data.get("rotation_id"),
|
|
data.get("previous_id"),
|
|
)
|
|
|
|
def manifest(self):
|
|
manifest = {
|
|
"version": REQUEST_VERSION,
|
|
"kind": self.kind,
|
|
"resource": self.resource.manifest(),
|
|
}
|
|
if self.operation != "read":
|
|
manifest["operation"] = self.operation
|
|
if self.operation == "rotate":
|
|
manifest.update(
|
|
rotation_id=self.rotation_id, previous_id=self.previous_id
|
|
)
|
|
return manifest
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--mailbox-only", action="store_true")
|
|
args = parser.parse_args(argv)
|
|
|
|
def parse(payload):
|
|
request = ServiceCredentialRequest.from_manifest(payload)
|
|
if request.kind == "mailbox":
|
|
check_mail_service_peer()
|
|
if args.mailbox_only and request.kind != "mailbox":
|
|
raise ValueError("This node handles mailbox requests only.")
|
|
return request
|
|
|
|
return serve_apply_request(
|
|
REQUEST_VERSION, parse, read_service_credentials, include_result=True
|
|
)
|
|
|
|
|
|
def read_service_credentials(request):
|
|
if os.geteuid() != 0:
|
|
raise ValueError(CREDENTIALS_UNAVAILABLE)
|
|
setting = f"COULOBRE_LOCAL_{request.kind.upper()}_CREDENTIALS"
|
|
if os.environ.get(setting) != "1":
|
|
raise ValueError(CREDENTIALS_UNAVAILABLE)
|
|
if (
|
|
request.operation != "read"
|
|
and os.environ.get(f"{setting}_ROTATION") != "1"
|
|
):
|
|
raise ValueError(CREDENTIALS_UNAVAILABLE)
|
|
|
|
try:
|
|
if request.operation == "rotate":
|
|
return rotate_service_credentials(request)
|
|
read = (
|
|
read_database_credentials
|
|
if request.kind == "database"
|
|
else read_mailbox_credentials
|
|
)
|
|
if request.operation == "generation":
|
|
return {"generation": read(request.resource, generation_only=True)}
|
|
return read(request.resource)
|
|
except (OSError, ValueError):
|
|
raise ValueError(CREDENTIALS_UNAVAILABLE) from None
|
|
|
|
|
|
def rotate_service_credentials(request):
|
|
if request.kind == "database":
|
|
from .database_node_rotation import rotate_database_credentials
|
|
|
|
record = rotate_database_credentials(request, DEFAULT_SOCKET)
|
|
return {
|
|
key: record[key]
|
|
for key in ("database", "user", "host", "socket", "password")
|
|
}
|
|
|
|
from .mail_node_rotation import rotate_mailbox_credentials
|
|
|
|
return rotate_mailbox_credentials(request)
|
|
|
|
|
|
def read_database_credentials(database, *, generation_only=False):
|
|
from .database_node_backup import managed_database
|
|
|
|
with managed_database(database, DEFAULT_SOCKET) as (_, record, _path):
|
|
if generation_only:
|
|
return record.get("rotation_id")
|
|
return {
|
|
key: record[key]
|
|
for key in ("database", "user", "host", "socket", "password")
|
|
}
|
|
|
|
|
|
def read_mailbox_credentials(mailbox, *, generation_only=False):
|
|
from .mail_node_apply import (
|
|
configured_mail_account,
|
|
credential_path,
|
|
load_credentials,
|
|
locked_state,
|
|
)
|
|
|
|
with locked_state(create=False):
|
|
if configured_mail_account(mailbox) is None:
|
|
raise ValueError(CREDENTIALS_UNAVAILABLE)
|
|
credentials = load_credentials(credential_path(mailbox))
|
|
if generation_only:
|
|
return credentials.rotation_id
|
|
return {"user": mailbox.address, "password": credentials.password}
|