diff --git a/cli/cmd/albedo/daemon_service.go b/cli/cmd/albedo/daemon_service.go index 73855620a..148f4b07d 100644 --- a/cli/cmd/albedo/daemon_service.go +++ b/cli/cmd/albedo/daemon_service.go @@ -26,14 +26,21 @@ func (connector *connector) Status(ctx context.Context) (localdaemon.ServiceStat return localdaemon.ServiceStatus{}, err } if runtime.GOOS == "darwin" { - return launchdStatus(view), nil + status := launchdStatus(view) + if note := localdaemon.ServiceOwnershipNote(view.Observation); note != "" { + if status.Note != "" { + status.Note += "; " + } + status.Note += note + } + return status, nil } mainPID, _ := strconv.Atoi(view.Observation.Properties["MainPID"]) pid := 0 if view.Discovery.Kind == localdaemon.Running || view.Discovery.Kind == localdaemon.Stopping { pid = view.Discovery.Snapshot.Pid } - return localdaemon.ServiceStatus{Unit: view.Unit.Name(), Class: view.Class, State: view.Observation.Properties["ActiveState"], Pid: pid, MainPID: mainPID, Problem: view.Problem}, nil + return localdaemon.ServiceStatus{Unit: view.Unit.Name(), Class: view.Class, State: view.Observation.Properties["ActiveState"], Pid: pid, MainPID: mainPID, Problem: view.Problem, Note: localdaemon.ServiceOwnershipNote(view.Observation)}, nil } func (connector *connector) startService(ctx context.Context) (*daemon.Connection, error) { @@ -60,17 +67,40 @@ func (connector *connector) startService(ctx context.Context) (*daemon.Connectio if view.Class != localdaemon.ServiceIdle && view.Class != localdaemon.ServiceTransition { return nil, view.MutationError() } + initial := view if view.Class == localdaemon.ServiceIdle { - if view.Observation.Properties["ActiveState"] == "failed" { + refresh := func() error { + current, observeErr := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if observeErr != nil { + return observeErr + } + if !localdaemon.RevalidateDeclaration(initial.Unit, initial.Observation, current.Observation) { + return errors.New("service declaration changed before start; replacement left untouched") + } + view = current + if view.Class != localdaemon.ServiceIdle && view.Class != localdaemon.ManagedService && view.Class != localdaemon.ServiceTransition { + return view.MutationError() + } + return nil + } + if err = refresh(); err != nil { + return nil, err + } + if view.Class == localdaemon.ServiceIdle && view.Observation.Properties["ActiveState"] == "failed" { if err = view.Unit.Run(ctx, "reset-failed"); err != nil { return nil, err } } - if err = view.Unit.Run(ctx, "start"); err != nil { - return nil, fmt.Errorf("start may have been submitted: %w; inspect with albedo daemon status", err) + if err = refresh(); err != nil { + return nil, err + } + if view.Class == localdaemon.ServiceIdle { + if err = view.Unit.Run(ctx, "start"); err != nil { + return nil, fmt.Errorf("start may have been submitted: %w; inspect with albedo daemon status", err) + } } } - return localdaemon.AwaitManaged(ctx, connector.options.HomeDir, view.Discovery.Snapshot) + return localdaemon.AwaitManagedService(ctx, connector.options.HomeDir, initial) } func (connector *connector) Stop(parent context.Context, kernels bool) error { @@ -85,6 +115,7 @@ func (connector *connector) Stop(parent context.Context, kernels bool) error { if err != nil { return err } + initial := view for view.Class == localdaemon.ServiceTransition { select { case <-ctx.Done(): @@ -95,6 +126,9 @@ func (connector *connector) Stop(parent context.Context, kernels bool) error { if err != nil { return err } + if !localdaemon.RevalidateDeclaration(initial.Unit, initial.Observation, view.Observation) { + return errors.New("service declaration changed while waiting to stop; replacement left untouched") + } } return connector.stopObserved(ctx, view, kernels) } @@ -112,6 +146,15 @@ func (connector *connector) stopObserved(ctx context.Context, view localdaemon.S if view.Discovery.Kind == localdaemon.Stopping { return daemon.WaitForExit(ctx, view.Discovery.Snapshot.Pid) } + if view.Observation.File == loginservice.DeclaredFile { + current, observeErr := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if observeErr != nil { + return observeErr + } + if !localdaemon.RevalidateDeclaration(view.Unit, view.Observation, current.Observation) || current.Class != view.Class || current.Discovery.Snapshot != view.Discovery.Snapshot || current.Observation.Properties["InvocationID"] != view.Observation.Properties["InvocationID"] { + return errors.New("service changed before shutdown; replacement left untouched") + } + } connection, err := daemon.Attach(ctx, view.Discovery.Snapshot, nil) if err != nil { return err @@ -138,7 +181,7 @@ func (connector *connector) awaitInactive(parent context.Context, view localdaem return err } p := observation.Properties - if observation.File != "owned" || observation.Problem != "" || p["NeedDaemonReload"] != "no" { + if (observation.File != loginservice.OwnedFile && observation.File != loginservice.DeclaredFile) || observation.Problem != "" || p["NeedDaemonReload"] != "no" || !localdaemon.RevalidateDeclaration(view.Unit, view.Observation, observation) { return errors.New("service contract changed during shutdown; inspect with albedo daemon status") } if id := p["InvocationID"]; id != "" && id != view.Observation.Properties["InvocationID"] { @@ -162,6 +205,9 @@ func (connector *connector) awaitInactive(parent context.Context, view localdaem } func (connector *connector) Install(parent context.Context) (string, error) { + if err := connector.serviceOwnershipPreflight(); err != nil { + return "", err + } if runtime.GOOS == "darwin" { return connector.installLaunchd(parent) } @@ -185,6 +231,9 @@ func (connector *connector) Install(parent context.Context) (string, error) { if err != nil { return "", err } + if view.Observation.File != loginservice.OwnedFile && view.Observation.File != loginservice.AbsentFile { + return "", view.Observation.FileOwnershipError() + } if !view.Observation.Available { return "", errors.New("systemd user manager is unavailable") } @@ -193,10 +242,12 @@ func (connector *connector) Install(parent context.Context) (string, error) { } observation := view.Observation installationClass := view.Class - if observation.File == "owned" && observation.Problem == "" && observation.Properties["NeedDaemonReload"] == "yes" { + loadedDrift := observation.LoadedDefinition.Executable != "" && !localdaemon.SameServiceDefinition(observation.Definition, observation.LoadedDefinition) + if observation.File == loginservice.OwnedFile && observation.Problem == "" && (observation.Properties["NeedDaemonReload"] == "yes" || loadedDrift) { loaded := observation loaded.Properties = maps.Clone(observation.Properties) loaded.Properties["NeedDaemonReload"] = "no" + loaded.Definition = observation.LoadedDefinition installationClass = localdaemon.ClassifyService(loaded, view.Discovery) } allowed := installationClass == localdaemon.NoService || installationClass == localdaemon.ManagedService || installationClass == localdaemon.ServiceIdle || installationClass == localdaemon.StandaloneBeside || installationClass == localdaemon.UnloadedService @@ -259,7 +310,7 @@ func (connector *connector) Install(parent context.Context) (string, error) { } return "", fmt.Errorf("service installation incomplete: %w; %s", cause, details) } - if changed || observation.Properties["NeedDaemonReload"] != "no" { + if changed || loadedDrift || observation.Properties["NeedDaemonReload"] != "no" { if err = view.Unit.Reload(ctx); err != nil { return fail(err) } @@ -272,7 +323,7 @@ func (connector *connector) Install(parent context.Context) (string, error) { if reloaded.Class == localdaemon.UnknownService { return fail(reloaded.MutationError()) } - if after.File != "owned" || after.Problem != "" || after.Properties["LoadState"] != "loaded" || after.Properties["NeedDaemonReload"] != "no" { + if after.File != loginservice.OwnedFile || after.Problem != "" || after.Properties["LoadState"] != "loaded" || after.Properties["NeedDaemonReload"] != "no" { if after.Properties["LoadState"] != "loaded" { return fail(fmt.Errorf("user manager did not load %s; check its unit search path", view.Unit.Path())) } @@ -316,6 +367,9 @@ func (connector *connector) Install(parent context.Context) (string, error) { } func (connector *connector) Uninstall(parent context.Context) (string, error) { + if err := connector.serviceOwnershipPreflight(); err != nil { + return "", err + } if runtime.GOOS == "darwin" { return connector.uninstallLaunchd(parent) } @@ -333,6 +387,9 @@ func (connector *connector) Uninstall(parent context.Context) (string, error) { if err != nil { return "", err } + if view.Observation.File != loginservice.OwnedFile && view.Observation.File != loginservice.AbsentFile { + return "", view.Observation.FileOwnershipError() + } if view.Class == localdaemon.NoService { return "no daemon service is installed", nil } @@ -348,7 +405,7 @@ func (connector *connector) Uninstall(parent context.Context) (string, error) { if err != nil { return "", err } - if after.Problem != "" || after.File != "owned" || after.Properties["MainPID"] != "0" || after.Properties["Job"] != "" || after.Properties["NeedDaemonReload"] == "yes" || !view.Unit.Unchanged(view.Observation.Info, view.Observation.Data) { + if after.Problem != "" || after.File != loginservice.OwnedFile || after.Properties["MainPID"] != "0" || after.Properties["Job"] != "" || after.Properties["NeedDaemonReload"] == "yes" || !view.Unit.Unchanged(view.Observation.Info, view.Observation.Data) { return "", errors.New("service changed during uninstall; registration left intact") } if err = view.Unit.Run(ctx, "disable"); err != nil { @@ -358,7 +415,7 @@ func (connector *connector) Uninstall(parent context.Context) (string, error) { if err != nil { return "", err } - if after.Problem != "" || after.File != "owned" || after.Properties["NeedDaemonReload"] == "yes" || after.Properties["MainPID"] != "0" || after.Properties["Job"] != "" || !view.Unit.Unchanged(view.Observation.Info, view.Observation.Data) { + if after.Problem != "" || after.File != loginservice.OwnedFile || after.Properties["NeedDaemonReload"] == "yes" || after.Properties["MainPID"] != "0" || after.Properties["Job"] != "" || !view.Unit.Unchanged(view.Observation.Info, view.Observation.Data) { return "", errors.New("service changed after disable; file left intact") } if err = os.Remove(view.Unit.Path()); err != nil { @@ -369,3 +426,14 @@ func (connector *connector) Uninstall(parent context.Context) (string, error) { } return "removed daemon service; kernels are kept and the next albedo starts standalone", nil } + +func (connector *connector) serviceOwnershipPreflight() error { + if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + return nil + } + unit, err := loginservice.ForDaemon(connector.options.HomeDir) + if err != nil { + return err + } + return unit.CheckFileOwnership() +} diff --git a/cli/cmd/albedo/daemon_service_launchd_policy.go b/cli/cmd/albedo/daemon_service_launchd_policy.go index 6748ef4b2..505d3db86 100644 --- a/cli/cmd/albedo/daemon_service_launchd_policy.go +++ b/cli/cmd/albedo/daemon_service_launchd_policy.go @@ -26,10 +26,14 @@ func launchdStatus(view localdaemon.ServiceView) localdaemon.ServiceStatus { notes = append(notes, "GUI domain absent; service lifecycle unavailable") } if job.Disabled { - notes = append(notes, "disabled override; operator command: launchctl enable "+view.Unit.Target()) + notes = append(notes, "disabled override; to enable it, run launchctl enable "+view.Unit.Target()) } if localdaemon.LaunchdDrift(view.Observation) { - notes = append(notes, "loaded definition differs from file; reconcile with albedo daemon uninstall, then albedo daemon install") + advice := "reconcile with albedo daemon uninstall, then albedo daemon install" + if view.Observation.File == loginservice.DeclaredFile { + advice = localdaemon.ServiceAdvice(view.Observation) + } + notes = append(notes, "loaded definition differs from file; "+advice) } if view.Class == localdaemon.ServiceRetrying { notes = append(notes, fmt.Sprintf("launchd may retry; runs=%d%s", job.Runs, launchdExit(job))) @@ -89,9 +93,30 @@ func (connector *connector) startLaunchd(ctx context.Context) (*daemon.Connectio if localdaemon.HomeHeld(connector.options.HomeDir) { return nil, errors.New("home is held; service start refused") } - if !view.Unit.Unchanged(view.Observation.Info, view.Observation.Data) { + if !unchangedLaunchdFile(view) { return nil, errors.New("service file changed before start; left in place") } + current, observeErr := localdaemon.ObserveService(ctx, connector.options.HomeDir) + if observeErr != nil { + return nil, observeErr + } + if !localdaemon.RevalidateDeclaration(view.Unit, view.Observation, current.Observation) || !sameLaunchdContract(view.Observation, current.Observation) || !unchangedLaunchdFile(view) || !localdaemon.SameServiceDefinition(view.Observation.Definition, current.Observation.Definition) { + return nil, errors.New("service changed before start; configuration left in place") + } + if err = current.LaunchdStartError(); err != nil { + return nil, err + } + if current.Class == localdaemon.ManagedService { + return daemon.Attach(ctx, current.Discovery.Snapshot, func(ctx context.Context) (daemon.ConnectionSnapshot, error) { + return localdaemon.Rediscover(ctx, connector.options.HomeDir) + }) + } + if current.Class != view.Class { + return localdaemon.AwaitLaunchd(ctx, connector.options.HomeDir, view.Observation, false) + } + if localdaemon.HomeHeld(connector.options.HomeDir) { + return nil, errors.New("home is held; service start refused") + } if err = ctx.Err(); err != nil { return nil, err } @@ -128,7 +153,8 @@ func (connector *connector) stopLaunchd(ctx context.Context, view localdaemon.Se switch view.Class { case localdaemon.NoService, localdaemon.StandaloneBeside, localdaemon.ManagedService, localdaemon.ServiceIdle, localdaemon.UnloadedService: case localdaemon.ServiceRetrying: - return fmt.Errorf("no ready daemon stopped; launchd may retry%s; albedo daemon uninstall removes the registration", launchdExit(view.Observation.Launchd)) + advice := localdaemon.ServiceAdvice(view.Observation) + return fmt.Errorf("no ready daemon stopped; launchd may retry%s; %s", launchdExit(view.Observation.Launchd), advice) default: return view.MutationError() } @@ -150,6 +176,15 @@ func (connector *connector) stopLaunchd(ctx context.Context, view localdaemon.Se if err = ctx.Err(); err != nil { return err } + if view.Observation.File == loginservice.DeclaredFile { + after, observeErr := view.Unit.Observe(ctx) + if observeErr != nil { + return observeErr + } + if !localdaemon.RevalidateDeclaration(view.Unit, view.Observation, after) || !sameLaunchdContract(view.Observation, after) || after.Launchd.PID != view.Observation.Launchd.PID || after.Launchd.Runs != view.Observation.Launchd.Runs { + return errors.New("service declaration changed before shutdown; no mutation performed") + } + } if err = daemon.StopDaemon(ctx, connection, kernels); err != nil { return err } @@ -172,7 +207,7 @@ func (connector *connector) stopLaunchd(ctx context.Context, view localdaemon.Se return err } job := after.Launchd - if after.Problem != "" || after.File != "owned" || !sameLaunchdContract(view.Observation, after) || job.Runs != view.Observation.Launchd.Runs || (job.PID != 0 && job.PID != view.Observation.Launchd.PID) || job.Signal != nil { + if after.Problem != "" || (after.File != loginservice.OwnedFile && after.File != loginservice.DeclaredFile) || !localdaemon.RevalidateDeclaration(view.Unit, view.Observation, after) || !unchangedLaunchdFile(view) || !sameLaunchdContract(view.Observation, after) || job.Runs != view.Observation.Launchd.Runs || (job.PID != 0 && job.PID != view.Observation.Launchd.PID) || job.Signal != nil { return errors.New("target stopped; service changed during shutdown; no further mutation performed") } if job.State == "not running" && job.PID == 0 && job.ExitCode != nil && *job.ExitCode == 0 { @@ -197,6 +232,9 @@ func launchdPoll(ctx context.Context) error { } func unchangedLaunchdFile(view localdaemon.ServiceView) bool { + if view.Observation.File == loginservice.DeclaredFile { + return view.Unit.DeclarationUnchanged(view.Observation.Snapshot) + } if view.Observation.Info != nil { return view.Unit.Unchanged(view.Observation.Info, view.Observation.Data) } @@ -205,11 +243,14 @@ func unchangedLaunchdFile(view localdaemon.ServiceView) bool { } func launchdInstallAllowed(view localdaemon.ServiceView) error { + if view.Observation.File != loginservice.OwnedFile && view.Observation.File != loginservice.AbsentFile { + return view.Observation.FileOwnershipError() + } if view.Problem != "" || !view.Observation.Available || view.Observation.Launchd == nil { return view.MutationError() } if view.Observation.Launchd.Disabled { - return fmt.Errorf("service is disabled; operator command: launchctl enable %s", view.Unit.Target()) + return fmt.Errorf("service is disabled; Albedo leaves the override unchanged; to enable it, run launchctl enable %s", view.Unit.Target()) } switch view.Class { case localdaemon.NoService, localdaemon.UnloadedService, localdaemon.ManagedService, localdaemon.ServiceIdle, localdaemon.ServiceRetrying, localdaemon.StandaloneBeside: @@ -248,6 +289,9 @@ func (connector *connector) installLaunchd(parent context.Context) (string, erro if err != nil { return "", err } + if view.Observation.File != loginservice.OwnedFile && view.Observation.File != loginservice.AbsentFile { + return "", view.Observation.FileOwnershipError() + } } if err = launchdInstallAllowed(view); err != nil { return "", err @@ -267,7 +311,7 @@ func (connector *connector) installLaunchd(parent context.Context) (string, erro if err = launchdInstallAllowed(current); err != nil { return "", err } - if !sameLaunchdContract(view.Observation, current.Observation) || !unchangedLaunchdFile(view) { + if !localdaemon.RevalidateDeclaration(view.Unit, view.Observation, current.Observation) || !sameLaunchdContract(view.Observation, current.Observation) || !unchangedLaunchdFile(view) { return "", errors.New("service changed before publication") } if !current.Observation.Launchd.Loaded && localdaemon.HomeHeld(connector.options.HomeDir) { @@ -285,7 +329,7 @@ func (connector *connector) installLaunchd(parent context.Context) (string, erro if err != nil { return "", launchdPartial(view.Unit, "publication", err) } - if after.Observation.File != "owned" || !bytes.Equal(after.Observation.Data, data) { + if after.Observation.File != loginservice.OwnedFile || !bytes.Equal(after.Observation.Data, data) { return "", errors.New("file changed after publication; left in place") } if view.Observation.Launchd.Loaded { @@ -342,9 +386,9 @@ func (connector *connector) uninstallLaunchd(parent context.Context) (string, er return "", err } safe := func(observation loginservice.Observation) bool { - return observation.Problem == "" && observation.File == "owned" && observation.Available && observation.Launchd != nil + return observation.Problem == "" && observation.File == loginservice.OwnedFile && observation.Available && observation.Launchd != nil } - if original.File == "absent" && original.Problem == "" && original.Launchd != nil && !original.Launchd.Loaded { + if original.File == loginservice.AbsentFile && original.Problem == "" && original.Launchd != nil && !original.Launchd.Loaded { return "no daemon service is installed", nil } if !safe(original) { diff --git a/cli/internal/localdaemon/service.go b/cli/internal/localdaemon/service.go index d5be39720..71542f09f 100644 --- a/cli/internal/localdaemon/service.go +++ b/cli/internal/localdaemon/service.go @@ -41,16 +41,16 @@ func ClassifyService(observation loginservice.Observation, found Discovery) Serv return classifyLaunchd(observation, found) } p := observation.Properties - if observation.File == "absent" && (!observation.Available || p["LoadState"] == "not-found") { + if observation.Problem == "" && observation.File == loginservice.AbsentFile && (!observation.Available || p["LoadState"] == "not-found") { return NoService } - if observation.File != "owned" || observation.Problem != "" || p["LoadState"] != "loaded" { - if observation.File == "owned" && observation.Problem == "" && p["LoadState"] == "not-found" { + if (observation.File != loginservice.OwnedFile && observation.File != loginservice.DeclaredFile) || observation.Problem != "" || p["LoadState"] != "loaded" { + if observation.File == loginservice.OwnedFile && observation.Problem == "" && p["LoadState"] == "not-found" { return UnloadedService } return UnsafeService } - if p["NeedDaemonReload"] != "no" { + if p["NeedDaemonReload"] != "no" || (observation.LoadedDefinition.Executable != "" && !SameServiceDefinition(observation.Definition, observation.LoadedDefinition)) { return UnsafeService } if found.Kind == Stopping || p["ActiveState"] == "activating" || p["ActiveState"] == "deactivating" || p["ActiveState"] == "reloading" || strings.HasPrefix(p["SubState"], "auto-restart") || p["Job"] != "" { @@ -86,12 +86,7 @@ func ObserveService(ctx context.Context, home string) (ServiceView, error) { var before loginservice.Observation var managerErr error if runtime.GOOS == "linux" || runtime.GOOS == "darwin" { - var err error - unit, err = loginservice.ForDaemon(home) - if err != nil { - return ServiceView{}, err - } - before, managerErr = unit.Observe(ctx) + unit, before, managerErr = loginservice.FindDaemon(ctx, home) } found, err := Discover(ctx, home) var compatibility *daemon.CompatibilityError @@ -113,17 +108,28 @@ func ObserveService(ctx context.Context, home string) (ServiceView, error) { } view.Class = ClassifyService(before, found) view.Problem = before.Problem + if before.Problem == "" && before.LoadedDefinition.Executable != "" && !SameServiceDefinition(before.Definition, before.LoadedDefinition) { + view.Problem = "loaded service definition differs from file; " + ServiceAdvice(before) + } if before.Problem == "" && before.Properties["NeedDaemonReload"] == "yes" { - view.Problem = "unit needs daemon-reload; run albedo daemon install to reconcile its definition" + view.Problem = "unit needs daemon-reload; " + ServiceAdvice(before) } - if view.Class == ManagedService { + if before.File == loginservice.DeclaredFile || view.Class == ManagedService { after, err := unit.Observe(ctx) if err != nil { view.Class = UnknownService view.Problem = err.Error() - } else if after.Properties["MainPID"] != before.Properties["MainPID"] || after.Properties["InvocationID"] != before.Properties["InvocationID"] || ClassifyService(after, found) != ManagedService { + } else if !RevalidateDeclaration(unit, before, after) { + view.Class = UnsafeService + view.Problem = "service declaration changed while checking daemon identity" + } else if view.Class == ManagedService && (after.Properties["MainPID"] != before.Properties["MainPID"] || after.Properties["InvocationID"] != before.Properties["InvocationID"] || ClassifyService(after, found) != ManagedService) { view.Class = ServiceTransition view.Problem = "service changed while checking daemon identity" + } else if before.File == loginservice.DeclaredFile { + // The manager may have started an idle declaration during discovery. + // Use its latest eligibility instead of submitting a redundant start. + view.Class = ClassifyService(after, found) + view.Observation = after } } return view, nil @@ -147,11 +153,7 @@ func checkDirectLaunch(ctx context.Context, home string) error { if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { return nil } - unit, err := loginservice.ForDaemon(home) - if err != nil { - return err - } - observation, err := unit.Observe(ctx) + _, observation, err := loginservice.FindDaemon(ctx, home) if err != nil || ClassifyService(observation, Discovery{}) != NoService { return &ServicePolicyChanged{} } @@ -163,6 +165,14 @@ func LockLauncher(ctx context.Context, home string) (*os.File, error) { } func AwaitManaged(ctx context.Context, home string, dead daemon.ConnectionSnapshot) (*daemon.Connection, error) { + return awaitManaged(ctx, home, dead, nil) +} + +func AwaitManagedService(ctx context.Context, home string, initial ServiceView) (*daemon.Connection, error) { + return awaitManaged(ctx, home, initial.Discovery.Snapshot, &initial) +} + +func awaitManaged(ctx context.Context, home string, dead daemon.ConnectionSnapshot, initial *ServiceView) (*daemon.Connection, error) { progress := watchStartup(home) for { view, err := ObserveService(ctx, home) @@ -173,6 +183,9 @@ func AwaitManaged(ctx context.Context, home string, dead daemon.ConnectionSnapsh } view.Class = ServiceTransition } + if initial != nil && !RevalidateDeclaration(initial.Unit, initial.Observation, view.Observation) { + return nil, errors.New("service declaration changed during startup; replacement left untouched") + } if view.Class == ManagedService { return daemon.Attach(ctx, view.Discovery.Snapshot, func(ctx context.Context) (daemon.ConnectionSnapshot, error) { return Rediscover(ctx, home) }) } @@ -209,3 +222,34 @@ type ServiceStatus struct { Pid int `json:"pid"` MainPID int `json:"main_pid"` } + +// RevalidateDeclaration compares an external operation's original source and loaded +// contract with a later observation, then rereads the filesystem to catch replacements +// during the manager reply. Nondeclared originals only reject becoming declared; +// owned services retain their separate ownership checks. +func RevalidateDeclaration(unit loginservice.DaemonUnit, before, after loginservice.Observation) bool { + if before.File != loginservice.DeclaredFile { + return after.File != loginservice.DeclaredFile + } + if before.Problem != "" || after.Problem != "" || after.File != loginservice.DeclaredFile || !before.Snapshot.Same(after.Snapshot) || !unit.DeclarationUnchanged(before.Snapshot) || !SameServiceDefinition(before.Definition, after.Definition) { + return false + } + if before.Launchd != nil { + return after.Launchd != nil && before.Launchd.Loaded == after.Launchd.Loaded && SameServiceDefinition(before.Launchd.Definition, after.Launchd.Definition) + } + return SameServiceDefinition(before.LoadedDefinition, after.LoadedDefinition) +} + +func ServiceAdvice(observation loginservice.Observation) string { + if observation.File == loginservice.DeclaredFile { + return "reconcile or remove through the declaration owner, such as Home Manager" + } + return "reconcile with albedo daemon install, or remove with albedo daemon uninstall" +} + +func ServiceOwnershipNote(observation loginservice.Observation) string { + if observation.File == loginservice.DeclaredFile { + return "externally managed by its declaration owner, such as Home Manager" + } + return "" +} diff --git a/cli/internal/localdaemon/service_launchd_policy.go b/cli/internal/localdaemon/service_launchd_policy.go index 90fc135fa..4a48f166e 100644 --- a/cli/internal/localdaemon/service_launchd_policy.go +++ b/cli/internal/localdaemon/service_launchd_policy.go @@ -16,7 +16,7 @@ import ( ) func SameServiceDefinition(left, right loginservice.Definition) bool { - return left.Executable == right.Executable && maps.Equal(left.Environment, right.Environment) + return left.Executable == right.Executable && left.CommandShape == right.CommandShape && maps.Equal(left.Environment, right.Environment) } func LaunchdDrift(observation loginservice.Observation) bool { @@ -25,10 +25,13 @@ func LaunchdDrift(observation loginservice.Observation) bool { func classifyLaunchd(observation loginservice.Observation, found Discovery) ServiceClass { job := observation.Launchd - if observation.File == "absent" && !job.Loaded && observation.Problem == "" { + if observation.File == loginservice.AbsentFile && !job.Loaded && observation.Problem == "" { return NoService } - if observation.Problem != "" || observation.File != "owned" { + if observation.Problem != "" || (observation.File != loginservice.OwnedFile && observation.File != loginservice.DeclaredFile) { + return UnsafeService + } + if observation.File == loginservice.DeclaredFile && !job.Loaded { return UnsafeService } if found.Kind == Running { @@ -60,24 +63,26 @@ func classifyLaunchd(observation loginservice.Observation, found Discovery) Serv func observeLaunchdIdentity(ctx context.Context, home string, view ServiceView) (ServiceView, error) { view.Class = ClassifyService(view.Observation, view.Discovery) view.Problem = view.Observation.Problem - if view.Class != ManagedService { - return view, nil - } - record, recordErr := os.Open(filepath.Join(home, "daemon.json")) - if recordErr != nil { - view.Class = ServiceTransition - view.Problem = "daemon record changed while checking daemon identity" + if view.Class != ManagedService && view.Observation.File != loginservice.DeclaredFile { return view, nil } - data, recordErr := io.ReadAll(io.LimitReader(record, 64*1024+1)) - _ = record.Close() - var snapshot daemon.ConnectionSnapshot - // daemon.json carries no instance ID; discovery authenticated it through /server. - found := view.Discovery.Snapshot - if recordErr != nil || len(data) > 64*1024 || json.Unmarshal(data, &snapshot) != nil || snapshot.Pid != found.Pid || snapshot.Token != found.Token || snapshot.Port != found.Port || (snapshot.InstanceID != "" && snapshot.InstanceID != found.InstanceID) { - view.Class = ServiceTransition - view.Problem = "daemon record changed while checking daemon identity" - return view, nil + if view.Class == ManagedService { + record, recordErr := os.Open(filepath.Join(home, "daemon.json")) + if recordErr != nil { + view.Class = ServiceTransition + view.Problem = "daemon record changed while checking daemon identity" + return view, nil + } + data, recordErr := io.ReadAll(io.LimitReader(record, 64*1024+1)) + _ = record.Close() + var snapshot daemon.ConnectionSnapshot + // daemon.json carries no instance ID; discovery authenticated it through /server. + found := view.Discovery.Snapshot + if recordErr != nil || len(data) > 64*1024 || json.Unmarshal(data, &snapshot) != nil || snapshot.Pid != found.Pid || snapshot.Token != found.Token || snapshot.Port != found.Port || (snapshot.InstanceID != "" && snapshot.InstanceID != found.InstanceID) { + view.Class = ServiceTransition + view.Problem = "daemon record changed while checking daemon identity" + return view, nil + } } after, err := view.Unit.Observe(ctx) if err != nil { @@ -86,7 +91,7 @@ func observeLaunchdIdentity(ctx context.Context, home string, view ServiceView) return view, nil } beforeJob, afterJob := view.Observation.Launchd, after.Launchd - if afterJob == nil || ClassifyService(after, view.Discovery) != ManagedService || beforeJob.Path != afterJob.Path || beforeJob.PID != afterJob.PID || beforeJob.Runs != afterJob.Runs || !SameServiceDefinition(beforeJob.Definition, afterJob.Definition) { + if !RevalidateDeclaration(view.Unit, view.Observation, after) || afterJob == nil || ClassifyService(after, view.Discovery) != view.Class || beforeJob.Path != afterJob.Path || beforeJob.PID != afterJob.PID || beforeJob.Runs != afterJob.Runs || !SameServiceDefinition(beforeJob.Definition, afterJob.Definition) { view.Class = ServiceTransition view.Problem = "service changed while checking daemon identity" } @@ -100,10 +105,13 @@ func (view ServiceView) LaunchdStartError() error { return view.MutationError() } if job := view.Observation.Launchd; job != nil && job.Disabled { - return fmt.Errorf("service is disabled; an operator can run launchctl enable %s", view.Unit.Target()) + return fmt.Errorf("service is disabled; Albedo leaves the override unchanged; to enable it, run launchctl enable %s", view.Unit.Target()) } if LaunchdDrift(view.Observation) { - return fmt.Errorf("loaded service differs from its file; run albedo daemon uninstall, then albedo daemon install") + if view.Observation.File == loginservice.DeclaredFile { + return fmt.Errorf("loaded service differs from its file; %s", ServiceAdvice(view.Observation)) + } + return errors.New("loaded service differs from its file; run albedo daemon uninstall, then albedo daemon install") } return nil } @@ -127,6 +135,9 @@ func AwaitLaunchd(ctx context.Context, home string, initial loginservice.Observa if err != nil { return nil, err } + if !RevalidateDeclaration(view.Unit, initial, view.Observation) { + return nil, errors.New("service declaration changed during startup; reconcile through its owner") + } if err = view.LaunchdStartError(); err != nil { return nil, err } @@ -134,7 +145,7 @@ func AwaitLaunchd(ctx context.Context, home string, initial loginservice.Observa if job == nil || !job.Loaded { return nil, errors.New("service disappeared during startup; configuration left in place") } - if initial.File == "owned" && !SameServiceDefinition(initial.Definition, job.Definition) { + if (initial.File == loginservice.OwnedFile || initial.File == loginservice.DeclaredFile) && !SameServiceDefinition(initial.Definition, job.Definition) { return nil, errors.New("loaded service definition changed during startup; file retained") } if baseline != nil && (baseline.Path != job.Path || !SameServiceDefinition(baseline.Definition, job.Definition)) { @@ -151,7 +162,7 @@ func AwaitLaunchd(ctx context.Context, home string, initial loginservice.Observa if job.ExitCode != nil && *job.ExitCode == 75 { reason = "home in use (exit 75)" } - return nil, fmt.Errorf("%s%s; launchd may retry; check %s/daemon.log; albedo daemon uninstall removes the registration", reason, launchdHistory(job), home) + return nil, fmt.Errorf("%s%s; launchd may retry; check %s/daemon.log; %s", reason, launchdHistory(job), home, ServiceAdvice(initial)) } if view.Class == ServiceIdle && (attempted || !submitted) { return nil, fmt.Errorf("service exited before becoming ready; inspect %s/daemon.log; configuration left in place", home) @@ -160,7 +171,7 @@ func AwaitLaunchd(ctx context.Context, home string, initial loginservice.Observa return nil, view.MutationError() } if progress.stalled() { - return nil, fmt.Errorf("service startup made no log progress; last state=%s; inspect %s/daemon.log and use albedo daemon uninstall to remove the registration", job.State, home) + return nil, fmt.Errorf("service startup made no log progress; last state=%s; inspect %s/daemon.log and %s", job.State, home, ServiceAdvice(initial)) } timer := time.NewTimer(100 * time.Millisecond) select { diff --git a/cli/internal/localdaemon/service_launchd_policy_test.go b/cli/internal/localdaemon/service_launchd_policy_test.go index ec4f44e44..2411d5584 100644 --- a/cli/internal/localdaemon/service_launchd_policy_test.go +++ b/cli/internal/localdaemon/service_launchd_policy_test.go @@ -23,10 +23,36 @@ func TestLaunchdHolderAndRetryPrecedence(t *testing.T) { {name: "missing authenticated pid", state: "running", pid: 22, found: Discovery{Kind: Running, Snapshot: daemon.ConnectionSnapshot{Pid: 22, InstanceID: "current"}}, want: UnsafeService}, } { t.Run(test.name, func(t *testing.T) { - observation := loginservice.Observation{File: "owned", Available: true, Launchd: &loginservice.LaunchdObservation{Loaded: true, State: test.state, PID: test.pid, ExitCode: test.exit}} + observation := loginservice.Observation{File: loginservice.OwnedFile, Available: true, Launchd: &loginservice.LaunchdObservation{Loaded: true, State: test.state, PID: test.pid, ExitCode: test.exit}} if got := ClassifyService(observation, test.found); got != test.want { t.Fatalf("got %s, want %s", got, test.want) } }) } } + +func TestLaunchdDeclarationControlPreservesHolderAndStop(t *testing.T) { + found := Discovery{Kind: Running, Server: daemon.ServerInfo{Pid: 22, InstanceID: "current"}, Snapshot: daemon.ConnectionSnapshot{Pid: 22, InstanceID: "current"}} + source := loginservice.Definition{Executable: "/opt/albedo/bin/albedo", Environment: map[string]string{"PATH": "/bin"}} + loaded := source + loaded.CommandShape = loginservice.WaitForPathCommand + observation := loginservice.Observation{File: loginservice.DeclaredFile, Definition: source, Launchd: &loginservice.LaunchdObservation{Loaded: true, State: "running", PID: 22, Definition: loaded, Disabled: true}} + if got := ClassifyService(observation, found); got != ManagedService { + t.Fatalf("disabled drifted authenticated daemon: %s", got) + } + if !LaunchdDrift(observation) { + t.Fatal("wrapper change was not drift") + } + view := ServiceView{Class: ManagedService, Observation: observation} + if view.LaunchdStartError() == nil { + t.Fatal("disabled declaration allowed start") + } + observation.Launchd.PID = 33 + if got := ClassifyService(observation, found); got != StandaloneBeside { + t.Fatalf("independent holder: %s", got) + } + observation.Launchd.Loaded = false + if got := ClassifyService(observation, found); got != UnsafeService { + t.Fatalf("unloaded declaration granted holder lifecycle: %s", got) + } +} diff --git a/cli/test/e2e/daemon_service_darwin_test.go b/cli/test/e2e/daemon_service_darwin_test.go index 4821b9af0..555fd6694 100644 --- a/cli/test/e2e/daemon_service_darwin_test.go +++ b/cli/test/e2e/daemon_service_darwin_test.go @@ -7,6 +7,7 @@ import ( "context" "crypto/sha256" "encoding/json" + "encoding/xml" "fmt" "os" "os/exec" @@ -28,11 +29,12 @@ type launchdHome struct { t *testing.T home, path, loadedPath string env []string + declared bool } func launchdFixture(t *testing.T) *launchdHome { t.Helper() - home := filepath.Join(t.TempDir(), "home % $ &") + home := filepath.Join(t.TempDir(), "home % $ &", ".albedo") userHome := t.TempDir() if err := os.MkdirAll(home, 0700); err != nil { t.Fatal(err) @@ -55,7 +57,16 @@ func launchdFixture(t *testing.T) *launchdHome { t.Errorf("cleanup stop: %v %s", err, output) } } - if _, err := os.Lstat(fixture.path); err == nil { + if fixture.declared { + // These are this fixture's private stub files, never native registrations. + if snapshot.Pid <= 0 || awaitExit(snapshot.Pid, 5*time.Second) { + for _, path := range []string{fixture.path, fixture.loadedPath} { + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + t.Errorf("cleanup private declaration: %v", err) + } + } + } + } else if _, err := os.Lstat(fixture.path); err == nil { if output, err := fixture.run("daemon", "uninstall"); err != nil { t.Errorf("cleanup uninstall: %v %s", err, output) } @@ -534,3 +545,94 @@ func TestDaemonServiceDarwinUnsafeObservationAllowsOnlyAttachment(t *testing.T) t.Fatal("unsafe observation removed registration") } } + +// Direct form deliberately avoids wait4path and any dependency on a Nix store. +func TestDaemonServiceDarwinDeclaredLifecycle(t *testing.T) { + fixture := launchdFixture(t) + fixture.must("daemon", "install") + fixture.must("daemon", "--stop") + original := fixture.read(fixture.path) + var document struct { + Arguments []string `xml:"dict>array>string"` + } + if err := xml.Unmarshal(original, &document); err != nil || len(document.Arguments) != 3 { + t.Fatalf("installed arguments: %+v %v", document, err) + } + executable := filepath.Join(t.TempDir(), "bin", "albedo") + if err := os.MkdirAll(filepath.Dir(executable), 0700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(suite.cli, executable); err != nil { + t.Fatal(err) + } + var before, after bytes.Buffer + if err := xml.EscapeText(&before, []byte(document.Arguments[0])); err != nil { + t.Fatal(err) + } + if err := xml.EscapeText(&after, []byte(executable)); err != nil { + t.Fatal(err) + } + declaration := bytes.Replace(original, []byte("\n"), nil, 1) + declaration = bytes.Replace(declaration, before.Bytes(), after.Bytes(), 1) + oldLabel := strings.TrimSuffix(filepath.Base(fixture.path), ".plist") + declaration = bytes.ReplaceAll(declaration, []byte(oldLabel), []byte("systems.albedo.daemon")) + if err := os.Remove(fixture.path); err != nil { + t.Fatal(err) + } + userHome := filepath.Dir(fixture.home) + for index, entry := range fixture.env { + if strings.HasPrefix(entry, "HOME=") { + fixture.env[index] = "HOME=" + userHome + } + } + fixture.path = filepath.Join(userHome, "Library/LaunchAgents/systems.albedo.daemon.plist") + if err := os.MkdirAll(filepath.Dir(fixture.path), 0700); err != nil { + t.Fatal(err) + } + fixture.writeFile(fixture.path, declaration) + fixture.writeFile(fixture.loadedPath, declaration) + fixture.declared = true + beforeInfo, err := os.Stat(fixture.path) + if err != nil { + t.Fatal(err) + } + bootstraps, bootouts := fixture.verbs("bootstrap"), fixture.verbs("bootout") + fixture.must("daemon") + first := fixture.status() + if first.Class != localdaemon.ManagedService || !strings.Contains(first.Note, "externally managed") { + t.Fatalf("declared daemon: %+v", first) + } + fixture.refuses("daemon", "install") + fixture.refuses("daemon", "uninstall") + if current := fixture.status(); current.Pid != first.Pid || current.Class != localdaemon.ManagedService { + t.Fatalf("refusal changed daemon: %+v", current) + } + drifted := bytes.Replace(declaration, after.Bytes(), []byte(filepath.Join(t.TempDir(), "bin", "albedo")), 1) + fixture.writeFile(fixture.path, drifted) + fixture.writeFile(filepath.Join(fixture.home, "launchd-disabled"), nil) + fixture.must("daemon", "--stop") + fixture.refuses("daemon") + if err = os.Remove(filepath.Join(fixture.home, "launchd-disabled")); err != nil { + t.Fatal(err) + } + fixture.writeFile(fixture.path, declaration) + fixture.must("daemon") + if current := fixture.status(); current.Class != localdaemon.ManagedService || current.Pid == first.Pid { + t.Fatalf("declared restart: %+v", current) + } + fixture.must("daemon", "--stop") + afterInfo, err := os.Stat(fixture.path) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(beforeInfo, afterInfo) || !bytes.Equal(fixture.read(fixture.path), declaration) || !bytes.Equal(fixture.read(fixture.loadedPath), declaration) || fixture.verbs("bootstrap") != bootstraps || fixture.verbs("bootout") != bootouts { + t.Fatal("external lifecycle mutated declaration or registration") + } + if err := os.Remove(fixture.loadedPath); err != nil { + t.Fatal(err) + } + fixture.refuses("daemon") + if fixture.verbs("bootstrap") != bootstraps { + t.Fatal("unloaded declaration was bootstrapped") + } +} diff --git a/cli/test/e2e/daemon_service_test.go b/cli/test/e2e/daemon_service_test.go index 3daae2f27..dd28ae3ce 100644 --- a/cli/test/e2e/daemon_service_test.go +++ b/cli/test/e2e/daemon_service_test.go @@ -113,6 +113,29 @@ func TestDaemonServiceLifecycle(t *testing.T) { if status().Pid != first.Pid { t.Fatal("attach/refresh replaced managed daemon") } + // A stale loaded definition can need reconciliation even without the reload flag. + loadedFile := filepath.Join(home, "daemon-unit-loaded") + loaded, readErr := os.ReadFile(loadedFile) + if readErr != nil { + t.Fatal(readErr) + } + if err := os.WriteFile(loadedFile, bytes.ReplaceAll(loaded, []byte(suite.cli), []byte("/old/bin/albedo")), 0600); err != nil { + t.Fatal(err) + } + properties := filepath.Join(home, "daemon-properties.json") + if err := os.WriteFile(properties, []byte(`{"NeedDaemonReload":"no"}`), 0600); err != nil { + t.Fatal(err) + } + if status().Class != localdaemon.UnsafeService { + t.Fatal("loaded drift was accepted") + } + must("daemon", "install") + if status().Class != localdaemon.ManagedService || status().Pid != first.Pid { + t.Fatal("install did not reconcile the loaded definition without a restart") + } + if err := os.Remove(properties); err != nil { + t.Fatal(err) + } must("daemon", "--stop", "--kernels") if stopped := status(); stopped.Class != localdaemon.ServiceIdle || stopped.Pid != 0 { t.Fatal("HTTP stop did not leave unit idle") @@ -121,7 +144,37 @@ func TestDaemonServiceLifecycle(t *testing.T) { if status().Class != localdaemon.ServiceIdle { t.Fatal("refresh started a stopped service") } - must("daemon") + // Connect must wait for a stop in progress, then start the idle service. + if err := os.WriteFile(properties, []byte(`{"ActiveState":"deactivating"}`), 0600); err != nil { + t.Fatal(err) + } + _ = os.Remove(filepath.Join(home, "show-count")) + connected := make(chan error, 1) + go func() { + output, err := run("daemon") + if err != nil { + err = fmt.Errorf("connect during stop: %w: %s", err, output) + } + connected <- err + }() + deadline := time.Now().Add(10 * time.Second) + for { + data, _ := os.ReadFile(filepath.Join(home, "show-count")) + count, _ := strconv.Atoi(string(data)) + if count >= 3 { + break + } + if time.Now().After(deadline) { + t.Fatal("Connect did not observe the stopping service") + } + time.Sleep(10 * time.Millisecond) + } + if err := os.Remove(properties); err != nil { + t.Fatal(err) + } + if err := <-connected; err != nil { + t.Fatal(err) + } if status().Pid == first.Pid { t.Fatal("service did not start again") } @@ -201,8 +254,16 @@ func TestDaemonServiceForeignSymlinkIsNeverReplaced(t *testing.T) { if err = os.Symlink(target, unit.Path()); err != nil { t.Fatal(err) } - if output, err := run("daemon", "install"); err == nil { - t.Fatalf("foreign symlink accepted: %s", output) + if err = os.Remove(home); err != nil { + t.Fatal(err) + } + for _, verb := range []string{"install", "uninstall"} { + if output, runErr := run("daemon", verb); runErr == nil { + t.Fatalf("foreign symlink accepted: %s", output) + } + } + if _, err = os.Stat(home); !os.IsNotExist(err) { + t.Fatal("foreign refusal created daemon home") } if value, err := os.Readlink(unit.Path()); err != nil || value != target { t.Fatalf("foreign symlink changed: %q %v", value, err) @@ -605,3 +666,288 @@ func TestDaemonServiceFailedRunningRefreshRestoresItsDefinition(t *testing.T) { t.Fatal("running refresh replaced the daemon") } } + +// declaredDaemonFixture uses a real generated HM sample and a private symlink. +// Cleanup owns that exact stub registration; production uninstall must refuse it. +func declaredDaemonFixture(t *testing.T) (string, string, string, func(...string) (string, error)) { + t.Helper() + home, env, run := daemonServiceFixture(t) + var config string + for index, entry := range env { + if strings.HasPrefix(entry, "HOME=") { + env[index] = "HOME=" + filepath.Dir(home) + } + if value, ok := strings.CutPrefix(entry, "XDG_CONFIG_HOME="); ok { + config = value + } + } + path := filepath.Join(config, "systemd/user/albedo.service") + if err := os.WriteFile(filepath.Join(home, "daemon-unit-name"), []byte("albedo.service"), 0600); err != nil { + t.Fatal(err) + } + target := filepath.Join(t.TempDir(), "daemon.service") + data, err := os.ReadFile(filepath.Join(suite.root, "cli/internal/loginservice/testdata/home-manager/daemon.service")) + if err != nil { + t.Fatal(err) + } + // The CLI is the fixture's actual bin/albedo; the renderer sample stays independent. + quote := func(value string) string { return strings.NewReplacer(`\`, `\\`, `"`, `\"`, "%", "%%").Replace(value) } + data = []byte(strings.NewReplacer("@HOME@", quote(home), "@EXECUTABLE@", quote(suite.cli), "@PATH@", quote(os.Getenv("PATH"))).Replace(string(data))) + if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil { + t.Fatal(err) + } + if err = os.WriteFile(target, data, 0600); err != nil { + t.Fatal(err) + } + if err = os.Symlink(target, path); err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(home, "daemon-unit-loaded"), data, 0600); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + for _, name := range []string{"daemon-properties.json", "show-hook.json", "reset-failed-replace-link", "start-replace-link"} { + _ = os.Remove(filepath.Join(home, name)) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if snapshot, readErr := readDaemonSnapshot(home); readErr == nil { + connection, attachErr := daemon.Attach(ctx, snapshot, nil) + if attachErr == nil { + stopErr := daemon.StopDaemon(ctx, connection, true) + connection.HTTPClient().CloseIdleConnections() + if stopErr != nil { + t.Errorf("declared cleanup shutdown: %v", stopErr) + } + if waitErr := daemon.WaitForExit(ctx, snapshot.Pid); waitErr != nil { + t.Errorf("declared cleanup wait: %v", waitErr) + } + } else if !awaitExit(snapshot.Pid, time.Second) { + t.Errorf("declared cleanup attach: %v", attachErr) + } + } + // Exact private stub state, never a manager operation against a user service. + for _, name := range []string{path, filepath.Join(home, "daemon-unit-loaded"), filepath.Join(home, "daemon-service-stub.json")} { + _ = os.Remove(name) + } + }) + return home, path, target, run +} + +func TestDaemonServiceDeclaredLifecycleAndReadOnlyRefusal(t *testing.T) { + home, path, target, run := declaredDaemonFixture(t) + must := func(args ...string) string { + t.Helper() + output, err := run(args...) + if err != nil { + t.Fatalf("%v: %v %s", args, err, output) + } + return output + } + must("daemon") + var first localdaemon.ServiceStatus + if err := json.Unmarshal([]byte(must("daemon", "status", "--json")), &first); err != nil { + t.Fatal(err) + } + if first.Class != localdaemon.ManagedService || first.Pid == 0 || first.Pid != first.MainPID || !strings.Contains(first.Note, "externally managed") { + t.Fatalf("declared identity: %+v", first) + } + // Two registrations are ambiguous even when they name the same home. + digest := sha256.Sum256([]byte(home)) + legacyPath := filepath.Join(filepath.Dir(path), fmt.Sprintf("systems.albedo.daemon-%x.service", digest[:8])) + declaration, conflictErr := os.ReadFile(target) + if conflictErr != nil { + t.Fatal(conflictErr) + } + if conflictErr = os.WriteFile(legacyPath, declaration, 0600); conflictErr != nil { + t.Fatal(conflictErr) + } + t.Cleanup(func() { _ = os.Remove(legacyPath) }) + var conflict localdaemon.ServiceStatus + if conflictErr = json.Unmarshal([]byte(must("daemon", "status", "--json")), &conflict); conflictErr != nil || conflict.Class != localdaemon.UnsafeService || !strings.Contains(conflict.Problem, "both") { + t.Fatalf("competing registrations: %+v %v", conflict, conflictErr) + } + must("daemon") // Authenticated attachment remains available. + if output, stopErr := run("daemon", "--stop", "--kernels"); stopErr == nil { + t.Fatalf("conflicting registrations permitted shutdown: %s", output) + } + found, discoveryErr := localdaemon.Discover(t.Context(), home) + if discoveryErr != nil || found.Kind != localdaemon.Running || found.Snapshot.Pid != first.Pid { + t.Fatalf("refused shutdown changed the authenticated daemon: %+v %v", found, discoveryErr) + } + if conflictErr = os.Remove(legacyPath); conflictErr != nil { + t.Fatal(conflictErr) + } + linkInfo, _ := os.Lstat(path) + targetInfo, _ := os.Stat(target) + before, _ := os.ReadFile(target) + // Both commands must refuse before taking launcher.lock or talking to the manager, + // including when the service is transitioning. + for _, transition := range []bool{false, true} { + if transition { + if err := os.WriteFile(filepath.Join(home, "daemon-properties.json"), []byte(`{"ActiveState":"activating","Job":"1 job"}`), 0600); err != nil { + t.Fatal(err) + } + } + if err := os.Remove(filepath.Join(home, "launcher.lock")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(home, "service-stub.log"), nil, 0600); err != nil { + t.Fatal(err) + } + for _, verb := range []string{"install", "uninstall"} { + if output, err := run("daemon", verb); err == nil { + t.Fatalf("%s accepted external ownership: %s", verb, output) + } + } + if _, err := os.Stat(filepath.Join(home, "launcher.lock")); !os.IsNotExist(err) { + t.Fatal("refusal created launcher lock") + } + log, _ := os.ReadFile(filepath.Join(home, "service-stub.log")) + if len(log) != 0 { + t.Fatalf("refusal contacted manager: %s", log) + } + afterLink, _ := os.Lstat(path) + afterTarget, _ := os.Stat(target) + after, _ := os.ReadFile(target) + if !os.SameFile(linkInfo, afterLink) || !os.SameFile(targetInfo, afterTarget) || !bytes.Equal(before, after) { + t.Fatal("refusal changed declaration") + } + // Recreate only fixture lock so each refusal iteration starts without it. + if err := os.WriteFile(filepath.Join(home, "launcher.lock"), nil, 0600); err != nil { + t.Fatal(err) + } + } + _ = os.Remove(filepath.Join(home, "daemon-properties.json")) + must("daemon", "--stop", "--kernels") + must("daemon") + var second localdaemon.ServiceStatus + if err := json.Unmarshal([]byte(must("daemon", "status", "--json")), &second); err != nil || second.Class != localdaemon.ManagedService || second.Pid == first.Pid { + t.Fatalf("declared restart: %+v %v", second, err) + } + must("daemon", "--stop", "--kernels") + if unlinkErr := os.Remove(path); unlinkErr != nil { + t.Fatal(unlinkErr) + } + t.Cleanup(func() { + if _, readErr := os.Lstat(path); os.IsNotExist(readErr) { + _ = os.Symlink(target, path) + } + }) + mutationsBefore := daemonServiceMutations(t, home) + if output, startErr := run("daemon"); startErr == nil { + t.Fatalf("loaded declaration without its file allowed direct launch: %s", output) + } + if !slices.Equal(mutationsBefore, daemonServiceMutations(t, home)) { + t.Fatal("missing source refusal mutated the manager") + } + found, discoveryErr = localdaemon.Discover(t.Context(), home) + if discoveryErr != nil || (found.Kind != localdaemon.Absent && found.Kind != localdaemon.Stale) { + t.Fatalf("missing source refusal started a daemon: %+v %v", found, discoveryErr) + } + if linkErr := os.Symlink(target, path); linkErr != nil { + t.Fatal(linkErr) + } + +} + +func TestDaemonServiceDeclaredReplacementBoundaries(t *testing.T) { + for boundary, refusal := range map[string]string{ + "failed manager reply": "service declaration changed while checking daemon identity", + "after reset": "service declaration changed before start", + "readiness": "service declaration changed during startup", + "transition manager reply": "service declaration changed while checking daemon identity", + } { + t.Run(boundary, func(t *testing.T) { + home, path, target, run := declaredDaemonFixture(t) + write := func(name, contents string) { + t.Helper() + if err := os.WriteFile(filepath.Join(home, name), []byte(contents), 0600); err != nil { + t.Fatal(err) + } + } + args := []string{"daemon"} + switch boundary { + case "failed manager reply": + write("daemon-properties.json", `{"ActiveState":"failed"}`) + // Replace an intermediate directory link with the same target and bytes. + middle := filepath.Join(t.TempDir(), "middle") + if err := os.Symlink(filepath.Dir(target), middle); err != nil { + t.Fatal(err) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(middle, filepath.Base(target)), path); err != nil { + t.Fatal(err) + } + hook, _ := json.Marshal(map[string]any{"state": "failed", "replace_path": middle, "replace_link": filepath.Dir(target)}) + write("show-hook.json", string(hook)) + case "after reset": + write("daemon-properties.json", `{"ActiveState":"failed"}`) + write("reset-failed-replace-link", target) + case "readiness": + write("start-replace-link", target) + case "transition manager reply": + write("daemon-properties.json", `{"ActiveState":"activating","Job":"1 job"}`) + hook, _ := json.Marshal(map[string]any{"state": "activating", "replace_link": target}) + write("show-hook.json", string(hook)) + args = []string{"daemon", "--stop"} + } + output, err := run(args...) + if err == nil || !strings.Contains(output, refusal) { + t.Fatalf("replacement at %s accepted: %v %s", boundary, err, output) + } + log, err := os.ReadFile(filepath.Join(home, "service-stub.log")) + if err != nil { + t.Fatal(err) + } + if boundary != "readiness" && strings.Contains(string(log), `["start",`) { + t.Fatalf("replacement permitted start: %s", log) + } + if boundary == "failed manager reply" && strings.Contains(string(log), `["reset-failed",`) { + t.Fatalf("replacement permitted reset: %s", log) + } + if boundary == "after reset" && strings.Count(string(log), `["reset-failed",`) != 1 { + t.Fatalf("replacement did not follow exactly one reset: %s", log) + } + }) + } +} + +func TestDaemonServiceDeclaredLoadedDriftCannotStart(t *testing.T) { + home, _, target, run := declaredDaemonFixture(t) + original, err := os.ReadFile(target) + if err != nil { + t.Fatal(err) + } + changed := bytes.Replace(original, []byte("[Service]"), []byte("[Service]\nEnvironment=\"ALBEDO_ROOT=/another/root\""), 1) + if err = os.WriteFile(target, changed, 0600); err != nil { + t.Fatal(err) + } + // Even an apparently fresh manager cannot authorize a different source contract. + if err = os.WriteFile(filepath.Join(home, "daemon-properties.json"), []byte(`{"NeedDaemonReload":"no"}`), 0600); err != nil { + t.Fatal(err) + } + output, err := run("daemon", "status", "--json") + if err != nil { + t.Fatalf("status: %v %s", err, output) + } + var status localdaemon.ServiceStatus + if err = json.Unmarshal([]byte(output), &status); err != nil || status.Class != localdaemon.UnsafeService { + t.Fatalf("drift classification: %+v %v", status, err) + } + if output, err = run("daemon"); err == nil { + t.Fatalf("drift allowed start: %s", output) + } + log, err := os.ReadFile(filepath.Join(home, "service-stub.log")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(log), `["start",`) || strings.Contains(string(log), `["daemon-reload"`) { + t.Fatal("drift triggered service mutation") + } + if _, err = os.Stat(filepath.Join(home, "daemon.json")); !os.IsNotExist(err) { + t.Fatal("drift fell through to direct launch") + } +} diff --git a/docs/daemon-lifecycle.md b/docs/daemon-lifecycle.md index eef18184a..4d308bea1 100644 --- a/docs/daemon-lifecycle.md +++ b/docs/daemon-lifecycle.md @@ -49,6 +49,24 @@ The current client does not call older API routes. ## Daemon service +Home Manager and other declaration owners can supply a supported native service. +For the default home, declarative services use `albedo.service` on Linux or +`systems.albedo.daemon` on macOS. CLI-installed services retain their per-home +names. If both are registered, clients may attach but refuse service mutations +until the registrations are reconciled. Custom homes retain their per-home names. +Albedo validates its source, loaded configuration, and file identity before +control. A supported loaded idle declaration can start through its manager; +an authenticated matching daemon can stop through HTTP. Albedo never installs, +rewrites, reloads, enables, disables, bootstraps, or uninstalls an external +declaration. Reconcile or remove it through its owner. + +Declaration checks retain symlink-chain and target identity across waits. +They detect observed replacement but cannot lock another same-user writer or +make the final check and native start atomic. A change after the final check can +affect what the manager starts. Albedo reports uncertainty and does not roll back +an unidentified replacement. Unsupported service control still permits compatible +authenticated attachment. + On Linux, the first `albedo daemon install` creates, starts and enables a systemd user service. Running it again refreshes the definition without restarting the daemon or starting a stopped service. Installation requires a packaged daemon selected @@ -93,15 +111,18 @@ It never asks launchd to end the service. The agent stays loaded and idle, and kernels survive for the next start. `--kernels` ends the kernels too, and it needs a running daemon to ask. A daemon that keeps failing at startup stays in a retry loop. Status reports it as retrying, and stop cannot end it because no -daemon is ready to ask. Uninstall removes the registration instead. The agent -lives in the GUI user domain. Without a GUI session, a home that has a service +daemon is ready to ask. For a CLI-owned agent, `albedo daemon uninstall` removes +the registration. For a Home Manager agent, disable `services.albedo.enable` +and activate the configuration. The agent lives in the GUI user domain. +Without a GUI session, a home that has a service file refuses service changes. A home without one still runs standalone. Running `install` again on a loaded agent rewrites only its file. There is no reload step. The loaded registration keeps its old definition, a running daemon keeps running, and an idle agent stays stopped. When the file and the loaded definition differ, attach still works but start refuses. Run -`uninstall`, then `install`, to reconcile a supported difference. An edited +`uninstall`, then `install`, to reconcile a supported difference in a CLI-owned +agent. For an external declaration, reconcile through its owner. An edited file, a different loaded path, or a definition outside the supported shape refuses every service change. Inspect those by hand instead. A disabled override blocks install and start, and Albedo never changes it. Status prints