Source code for fleetmesh_node.config.change

"""Who changed what, and under which session.

A node managed by one operator needs none of this: the file changed, and
there was only ever one person who could have changed it. A node managed by
several does, and today it has nothing. `NodeConfig.operator` is a single
pubkey describing whose node it is, not who last touched it. The control
socket is chmod 0o600 with no principal at all, so every change over it is
anonymous and indistinguishable. There is no history of config changes
anywhere in the tree.

Three things make a change attributable, and the node currently has none of
them:

    operator   WHO - a pubkey or did:nostr. This is the UCAN issuer, and it
               is the principal `Parameter.requires` is waiting for: that
               field ships declared-only precisely because nothing
               authenticated one. `Actor` is where it arrives.
    session    WHICH RUN - a uuid meshctl mints per invocation, so a dozen
               changes from one `meshctl apply` are one act, and two
               operators racing are two.
    tool       WHAT MADE IT - 'meshctl/0.2.0', or 'meshnode' for a local
               command. A change nobody remembers making is usually a script.

A `Change` is one parameter moving, with the actor and the layer it came
from. Its `resource` is `Parameter.resource()` - the same string UCAN will
name in `with`, derived rather than written twice - so the record of what
happened and the authority to make it happen refer to the same thing.

Changes are announced on a declared channel, not written to a private file,
so they reach whatever backends an operator configured and are not a fourth
output path beside the journal, the tap and the log.
"""
from __future__ import annotations

import contextlib
import contextvars
import dataclasses
import socket
import struct
import uuid
from typing import Any, Iterator, Mapping, Optional, Sequence, TypedDict

from fleetmesh_core.identity import did as did_mod

from .. import channels

# An actor the node cannot name. Used where a change is real but its author is
# not established - a file edited by hand, a pre-session command - rather than
# inventing an operator, because a wrong name in an audit record is worse than
# an honest blank.
UNKNOWN_OPERATOR: str = ''
LOCAL_TOOL: str = 'meshnode'

# The ladder, weakest first. Every rung is recorded, not only the one that
# answered, because the interesting facts live between the rungs:
#
#   a rung ABSENT is not a rung that FAILED. "no signature offered" and
#   "signature did not verify" are different events and only one of them is
#   an attack.
#
#   two rungs naming different subjects is impersonation, and it is visible
#   only if both are kept. An actor asserting operator X whose signature
#   verifies as Y is the case this exists to catch.
#
#   an audit record has to be re-readable years later, so it must say what was
#   checked at the time rather than what the current code would check.
ASSERTED: str = 'asserted'      # the caller said so. No verification at all.
PEERCRED: str = 'peercred'      # the kernel named a local uid on the socket.
SIGNED: str = 'signed'          # a signature verified against the claimed DID.
DELEGATED: str = 'delegated'    # a UCAN chain proved the ability, maybe via hops.
RUNGS: tuple[str, ...] = (ASSERTED, PEERCRED, SIGNED, DELEGATED)

# Rungs this node can actually climb today. DELEGATED needs the UCAN
# verification that `Parameter.requires` is also waiting on, so it is declared
# and never produced - the same footing, and for the same reason, as
# ACCESS_DECLARED_ONLY in parameter.py. A rung the node cannot climb must read
# as absent, never as satisfied.
RUNGS_AVAILABLE: tuple[str, ...] = (ASSERTED, PEERCRED, SIGNED)

OK, FAILED, ABSENT = 'ok', 'failed', 'absent'


def _method_of(did: str) -> str:
    """The DID method name, or '' for anything that is not a DID.

    Local because `did.parse` raises for a method this profile does not
    speak, and a proof has to be able to record an unrecognised one rather
    than fail while recording that it failed.
    """
    parts = did.split(':', 2)
    return parts[1] if len(parts) >= 3 and parts[0] == 'did' else ''


[docs]class ProofRecord(TypedDict): """One rung as a backend stores it.""" rung: str ok: bool subject: str detail: str method: str
[docs]@dataclasses.dataclass(frozen=True) class Proof: """One rung, and what it said. `subject` is who this rung names in its own terms: a DID for SIGNED, a `uid=1000` for PEERCRED. Kept per rung rather than collapsed into one operator field, because collapsing is exactly what hides a disagreement. """ rung: str ok: bool subject: str = '' detail: str = '' method: str = ''
[docs] def describe(self) -> 'ProofRecord': return {'rung': self.rung, 'ok': self.ok, 'subject': self.subject, 'detail': self.detail, 'method': self.method}
[docs]def asserted(operator: str) -> Proof: """The caller's claim. `ok` is True because the claim was made, not because it was checked - the rung itself is what says it is unverified.""" return Proof(rung=ASSERTED, ok=bool(operator), subject=operator, detail='claimed by the caller, unverified', method=_method_of(operator))
[docs]def peercred_of(conn: Any) -> Optional[Proof]: """SO_PEERCRED off a unix socket, or None where the platform has none. Linux answers with SO_PEERCRED and a struct of pid, uid, gid. macOS and the BSDs answer a different question with LOCAL_PEERCRED and a different struct, and `socket` does not expose it portably, so this returns None there rather than guessing - a rung that cannot be climbed must read absent, not satisfied, and a fabricated uid in an audit record is worse than an honest blank. None is also the answer for a socket that is not a unix socket at all, because a uid means nothing across a network. """ so_peercred = getattr(socket, 'SO_PEERCRED', None) if so_peercred is None: return None try: if conn.family != socket.AF_UNIX: return None raw = conn.getsockopt(socket.SOL_SOCKET, so_peercred, struct.calcsize('3i')) pid, uid, gid = struct.unpack('3i', raw) except (AttributeError, OSError, struct.error): return None return peercred(uid, gid, pid)
[docs]def peercred(uid: int, gid: int = -1, pid: int = -1) -> Proof: """SO_PEERCRED on the control socket. Real and free, and it identifies a unix user rather than an operator, so it corroborates and never establishes: a uid is not a DID and this rung never claims one. """ bits = ['uid=%d' % uid] if gid >= 0: bits.append('gid=%d' % gid) if pid >= 0: bits.append('pid=%d' % pid) return Proof(rung=PEERCRED, ok=uid >= 0, subject='uid:%d' % uid, detail=' '.join(bits) + '; a local user, not a DID')
[docs]def signature(operator: str, msg32: bytes, sig_hex: str) -> Proof: """A signature over `msg32`, checked against the claimed DID's own key. Verified offline or not at all: `fleetmesh_core.identity.did` does no I/O, so a resolvable method comes back refused by name rather than dialling out on an audit path. """ k = did_mod.signing_key(operator) if k is None: return Proof(rung=SIGNED, ok=False, subject=operator, detail=did_mod.refusal(operator), method=_method_of(operator)) curve, _raw = k ok = did_mod.verify(operator, msg32, sig_hex) return Proof(rung=SIGNED, ok=ok, subject=operator, method=_method_of(operator), detail='%s over %s' % ('verified' if ok else 'did not verify', curve))
[docs]def new_session() -> str: """A session id. meshctl mints one per invocation and passes it down.""" return str(uuid.uuid4())
[docs]@dataclasses.dataclass(frozen=True) class Actor: """Who is acting, in which run, through what. Frozen, because an actor is a statement about a moment and editing one after the fact is exactly what an audit record must not permit. """ operator: str = UNKNOWN_OPERATOR session: str = '' tool: str = LOCAL_TOOL at: int = 0 proofs: tuple[Proof, ...] = () @property def named(self) -> bool: """Whether this actor identifies anyone. False is a legitimate answer and is reported as one rather than filled in.""" return bool(self.operator) @property def assurance(self) -> str: """The highest rung that verified, or '' for none. One number is not the record - `ladder()` is - but it is what a policy compares against, so it is computed from the proofs rather than stored, and cannot be asserted independently of them. """ best = '' for p in self.proofs: if p.ok and (not best or RUNGS.index(p.rung) > RUNGS.index(best)): best = p.rung return best @property def verified(self) -> bool: """Whether an identity was actually proved, not merely claimed. ASSERTED and PEERCRED do not count: the first is unchecked by definition and the second names a unix user. This is the distinction an audit record must keep, because a trail that cannot tell a claim from a proof reads as stronger than it is. """ return self.assurance in (SIGNED, DELEGATED)
[docs] def ladder(self) -> 'dict[str, str]': """Every rung and its state: ok, failed, or absent. The whole ladder, not just the rung that answered. A rung that was never offered and a rung that failed are different events, and only the second is an attack. """ state = {r: ABSENT for r in RUNGS} for p in self.proofs: if p.rung in state: state[p.rung] = OK if p.ok else FAILED return state
[docs] def conflicts(self) -> list[str]: """Rungs naming a DID that is not the one claimed. This is the impersonation case and it is detectable only because every rung keeps its own subject: an actor asserting operator X whose signature verifies as Y would, with one collapsed field, have been recorded as X. """ out: list[str] = [] for p in self.proofs: if not p.subject or p.subject.startswith('uid:'): continue if self.operator and p.subject != self.operator: out.append('%s names %s, not %s' % (p.rung, p.subject[:24], self.operator[:24])) return out
[docs] def describe(self) -> ActorRecord: return {'operator': self.operator or '(unknown)', 'session': self.session, 'tool': self.tool, 'at': self.at, 'assurance': self.assurance or '(none)', 'verified': self.verified, 'ladder': self.ladder(), 'conflicts': self.conflicts(), 'proofs': [p.describe() for p in self.proofs]}
# The actor of the request in flight. A ContextVar and not an attribute on # the node: the control socket serves every connection on its own thread, so # `node.acting = actor` let two concurrent requests overwrite each other and # a change could be attributed to whoever asked second. Each thread (and each # asyncio task, should one ever call in) sees only the actor it was given. ACTING: contextvars.ContextVar[Optional['Actor']] = contextvars.ContextVar('fleetmesh_acting', default=None) def acting() -> Optional['Actor']: """Who caused the work running now, or None outside a request.""" return ACTING.get() @contextlib.contextmanager def acting_as(actor: Optional['Actor']) -> Iterator[Optional['Actor']]: """Run a block on behalf of `actor`, restoring whoever was acting before.""" token = ACTING.set(actor) try: yield actor finally: ACTING.reset(token)
[docs]class ActorRecord(TypedDict): """An actor as a backend stores it. A named record for the reason check-dicts.py enforces: an audit row is read by field name. `ladder` and `proofs` are both here on purpose. The ladder is the summary a person reads; the proofs are what was actually checked, which is what a reader needs years later when the code has moved on. """ operator: str session: str tool: str at: int assurance: str verified: bool ladder: dict[str, str] conflicts: list[str] proofs: list[ProofRecord]
[docs]class ChangeRecord(TypedDict): """One change, as a backend stores it.""" resource: str was: Any now: Any source: str operator: str session: str tool: str at: int
[docs]@dataclasses.dataclass(frozen=True) class Change: """One parameter moving from `was` to `now`. `resource` comes from `Parameter.resource()`, so the audit record and the UCAN capability that will authorise it name the same thing. `secret` suppresses the values: an audit trail that prints the wallet URI it just changed has leaked it to everyone who can read the log. """ resource: str was: Any now: Any source: str actor: Actor secret: bool = False REDACTED: str = '(secret)'
[docs] def describe(self) -> ChangeRecord: was: Any = self.REDACTED if self.secret else self.was now: Any = self.REDACTED if self.secret else self.now return {'resource': self.resource, 'was': was, 'now': now, 'source': self.source, 'operator': self.actor.operator or '(unknown)', 'session': self.actor.session, 'tool': self.actor.tool, 'at': self.actor.at}
[docs] def said(self) -> str: who = self.actor.operator[:16] if self.actor.operator else '(unknown operator)' shown_was = self.REDACTED if self.secret else self.was shown_now = self.REDACTED if self.secret else self.now sess = (' session ' + self.actor.session[:8]) if self.actor.session else '' return 'config %s %r -> %r by %s via %s%s' % ( self.resource, shown_was, shown_now, who, self.source, sess)
[docs]def diff(resource_of: Any, before: Mapping[str, Any], after: Mapping[str, Any], params: Sequence[Any], source: str, actor: Actor) -> list[Change]: """Every parameter whose value differs between `before` and `after`. Taken over the declared parameters rather than over the raw keys, so a key nobody declared cannot be recorded as a change to a setting that does not exist, and a `secret` is carried through to the record that must redact it. """ out: list[Change] = [] for p in params: was, now = before.get(p.key), after.get(p.key) if was == now: continue out.append(Change(resource=resource_of(p), was=was, now=now, source=source, actor=actor, secret=bool(getattr(p, 'secret', False)))) return out
# The channel a change is announced on. Declared here beside the record rather # than in a central topic list, which is the arrangement fleetmesh_node/channels.py # exists to establish. CHANGED = channels.Channel( name='config.changed', description='A configuration parameter moved, with who moved it, the session they ' 'moved it in, and the escalation layer it came from. Secret parameters ' 'report that they changed and not to what.', level=channels.NOTE, wire=lambda change: change.describe(), say=lambda change: change.said(), tags=('config', 'audit')) # Raised when a change arrives with nobody named. Separate from the change # itself so an operator can require attribution by watching one channel, # rather than parsing every change for a blank field. UNATTRIBUTED = channels.Channel( name='config.unattributed', description='A configuration change arrived with no operator identity. Expected for a ' 'file edited by hand; on a node managed by several operators it means a ' 'tool is not passing one.', level=channels.TROUBLE, wire=lambda change: change.describe(), say=lambda change: 'config %s changed with no operator named (via %s)' % ( change.resource, change.source), tags=('config', 'audit', 'trouble')) IMPERSONATION = channels.Channel( name='config.identity_conflict', description='Two rungs of the identity ladder named different subjects - an actor ' 'claiming one operator whose signature verified as another. Visible only ' 'because every rung keeps its own subject.', level=channels.TROUBLE, wire=lambda change: change.describe(), say='identity conflict on {resource} (operator {operator})', tags=('config', 'audit', 'identity', 'trouble')) CHANNELS: tuple[channels.Channel, ...] = (CHANGED, UNATTRIBUTED, IMPERSONATION)
[docs]def announce(log: Any, change: Change) -> None: """Say a change happened, and say separately what is wrong with its author. Three channels rather than three fields on one, so an operator can watch the thing they care about: that every change is attributed, or that no identity ever disagreed with itself. """ log.say(CHANGED.name, change) if not change.actor.named: log.say(UNATTRIBUTED.name, change) if change.actor.conflicts(): log.say(IMPERSONATION.name, change)
__all__ = ['Actor', 'ActorRecord', 'Proof', 'ProofRecord', 'asserted', 'peercred', 'signature', 'RUNGS', 'RUNGS_AVAILABLE', 'peercred_of', 'ASSERTED', 'PEERCRED', 'SIGNED', 'DELEGATED', 'OK', 'FAILED', 'ABSENT', 'IMPERSONATION', 'Change', 'ChangeRecord', 'diff', 'announce', 'new_session', 'CHANGED', 'UNATTRIBUTED', 'CHANNELS', 'UNKNOWN_OPERATOR', 'LOCAL_TOOL']