Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions controlplane/lmnsquid/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

from docker.errors import DockerException
from fastapi import Depends, FastAPI, HTTPException, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import ValidationError

from .blocklist import Blocklist, noauth_list
from .config import Settings
Expand Down Expand Up @@ -156,9 +158,15 @@ def patch_instance(name: str, patch: InstancePatch) -> dict[str, Any]:
updates = patch.model_dump(exclude_unset=True)
# Re-validate the merged instance through Instance validators; school/role
# are not in InstancePatch, so the identity/name stays immutable.
merged = Instance.model_validate(
{**existing.model_dump(exclude={"name", "container_name"}), **updates}
)
try:
merged = Instance.model_validate(
{**existing.model_dump(exclude={"name", "container_name"}), **updates}
)
except ValidationError as exc:
# A 422 naming the field, like a bad POST body (it was a bare 500 before).
raise RequestValidationError(
exc.errors(include_url=False, include_context=False)
) from exc
result = _apply(merged)
audit.info(
"patch instance name=%s fields=%s",
Expand Down
13 changes: 13 additions & 0 deletions controlplane/lmnsquid/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ def create(
access_log_enabled: bool = typer.Option(
True, help="log requests (privacy: --no-access-log-enabled)"
),
krb5_clockskew_seconds: int = typer.Option(
300,
help="Kerberos clock skew the proxy accepts, 300-7200 s (krb5.conf clockskew); "
"raise only while client clocks are off, it widens the window for stolen tickets",
),
) -> None:
"""Create (and reconcile) an instance."""
body: dict[str, Any] = {
Expand All @@ -103,6 +108,7 @@ def create(
"cache_size_mb": cache_size_mb,
"log_retention_days": log_retention_days,
"access_log_enabled": access_log_enabled,
"krb5_clockskew_seconds": krb5_clockskew_seconds,
}
if image is not None:
body["image"] = image
Expand Down Expand Up @@ -347,6 +353,11 @@ def edit(
cache_size_mb: Optional[int] = typer.Option(None),
log_retention_days: Optional[int] = typer.Option(None),
access_log_enabled: Optional[bool] = typer.Option(None),
krb5_clockskew_seconds: Optional[int] = typer.Option(
None,
help="Kerberos clock skew the proxy accepts, 300-7200 s; 300 = the default "
"(replaces the container)",
),
) -> None:
"""Change fields of an existing instance without rm+create (re-validated + reconciled).

Expand Down Expand Up @@ -375,6 +386,8 @@ def edit(
body["log_retention_days"] = log_retention_days
if access_log_enabled is not None:
body["access_log_enabled"] = access_log_enabled
if krb5_clockskew_seconds is not None:
body["krb5_clockskew_seconds"] = krb5_clockskew_seconds
if not body:
typer.secho(
"nothing to change — pass at least one option", fg=typer.colors.YELLOW, err=True
Expand Down
9 changes: 7 additions & 2 deletions controlplane/lmnsquid/docker_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from docker.types import LogConfig

from .blocklist import CONTAINER_DIR, Blocklist, noauth_list
from .models import Instance
from .models import KRB5_CLOCKSKEW_DEFAULT, Instance

logger = logging.getLogger("lmnsquid.docker")

Expand Down Expand Up @@ -118,7 +118,7 @@ def _pull(self, image: str) -> None:

def env_for(self, inst: Instance) -> dict[str, str]:
"""Build the environment variables consumed by entrypoint.sh."""
return {
env = {
"INSTANCE": inst.name,
"VISIBLE_HOSTNAME": inst.visible_hostname,
"REALM": inst.realm,
Expand All @@ -131,6 +131,11 @@ def env_for(self, inst: Instance) -> dict[str, str]:
"LOG_RETENTION_DAYS": str(inst.log_retention_days),
"ACCESS_LOG_ENABLED": "1" if inst.access_log_enabled else "0",
}
# Only when it differs from the default (the entrypoint's too): an unchanged env keeps
# the spec fingerprint, so instances at the default are not replaced on upgrade.
if inst.krb5_clockskew_seconds != KRB5_CLOCKSKEW_DEFAULT:
env["KRB5_CLOCKSKEW_SECONDS"] = str(inst.krb5_clockskew_seconds)
return env

def spec_for(self, inst: Instance) -> dict[str, Any]:
"""Everything the container is created from (JSON-able), except its name.
Expand Down
18 changes: 18 additions & 0 deletions controlplane/lmnsquid/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@
"@sha256:0f59a1d47b090de4c2e89b14b929751e5c422126a7d507fa6ac955d25a0b0fd7"
)

# Kerberos clock skew the proxy accepts (krb5.conf [libdefaults] clockskew, seconds; ADR-017).
# 300 is MIT's own default: an instance at it gets no KRB5_CLOCKSKEW_SECONDS in its env, so
# its container spec stays as before and an upgrade replaces no container for it.
KRB5_CLOCKSKEW_DEFAULT = 300
KRB5_CLOCKSKEW_MAX = 7200


def _normalize_cidr_list(value: str) -> str:
"""Split on commas/whitespace, validate each part as a CIDR, and return the
Expand Down Expand Up @@ -72,6 +78,7 @@ class Instance(BaseModel):
image: str = DEFAULT_IMAGE
log_retention_days: int = 30
access_log_enabled: bool = True
krb5_clockskew_seconds: int = KRB5_CLOCKSKEW_DEFAULT

@field_validator("school", "role")
@classmethod
Expand Down Expand Up @@ -152,6 +159,16 @@ def _v_retention(cls, v: int) -> int:
raise ValueError("log_retention_days must be between 1 and 3650")
return v

@field_validator("krb5_clockskew_seconds")
@classmethod
def _v_clockskew(cls, v: int) -> int:
if not KRB5_CLOCKSKEW_DEFAULT <= v <= KRB5_CLOCKSKEW_MAX:
raise ValueError(
f"krb5_clockskew_seconds must be between {KRB5_CLOCKSKEW_DEFAULT} "
f"and {KRB5_CLOCKSKEW_MAX}"
)
return v

@computed_field # type: ignore[prop-decorator]
@property
def name(self) -> str:
Expand Down Expand Up @@ -184,6 +201,7 @@ class InstancePatch(BaseModel):
image: str | None = None
log_retention_days: int | None = None
access_log_enabled: bool | None = None
krb5_clockskew_seconds: int | None = None


class UpdateRequest(BaseModel):
Expand Down
16 changes: 3 additions & 13 deletions controlplane/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from lmnsquid.api import create_app
from lmnsquid.blocklist import Blocklist, noauth_list
from lmnsquid.config import Settings
from lmnsquid.docker_service import DockerService
from lmnsquid.models import Instance
from lmnsquid.reconciler import Reconciler
from lmnsquid.store import Store
Expand Down Expand Up @@ -51,19 +52,8 @@ def __init__(
self.reloaded: list[str] = []

def env_for(self, inst: Instance) -> dict[str, str]:
return {
"INSTANCE": inst.name,
"VISIBLE_HOSTNAME": inst.visible_hostname,
"REALM": inst.realm,
"AD_GROUP": inst.ad_group,
"INTERNET_GROUP": inst.internet_group or "",
"SCHOOL_SUBNETS": inst.school_subnets,
"KEYTAB": f"/run/secrets/{inst.keytab_secret}",
"CACHE_SIZE_MB": str(inst.cache_size_mb),
"HTTP_PORT": str(inst.http_port),
"LOG_RETENTION_DAYS": str(inst.log_retention_days),
"ACCESS_LOG_ENABLED": "1" if inst.access_log_enabled else "0",
}
# The real one (it touches no Docker), so API tests see the env a container gets.
return DockerService.env_for(self, inst) # type: ignore[arg-type]

def ensure_running(self, inst: Instance) -> dict[str, Any]:
self.ensure_calls.append(inst.name)
Expand Down
Loading
Loading