Send full host metadata on managed startup

This commit is contained in:
Dev Scribe authored and Cuong Manh Le committed 2026-10-08 15:00:04 +07:00
1 parent b0408e4d1c
commit be8c068fa9
15 files changed
+456 -56

No files matched your search

+34
View File
@@ -244,6 +244,40 @@ func waitForCondition(t *testing.T, what string, cond func() bool) {
t.Fatalf("timed out waiting for %s", what)
}
func TestApiConfigReloadUsesRuntimeMetadata(t *testing.T) {
originalFetch, originalUID := fetchResolverConfigFn, cdUID
t.Cleanup(func() {
fetchResolverConfigFn = originalFetch
cdUID = originalUID
})
cdUID = "test-uid"
captured := make(chan *controld.ResolverConfigRequest, 1)
fetchResolverConfigFn = func(_ context.Context, req *controld.ResolverConfigRequest, _ bool) (*controld.ResolverConfig, error) {
captured <- req
return &controld.ResolverConfig{}, nil
}
p := progForRefresh()
p.cfg = &ctrld.Config{}
p.stopCh = make(chan struct{})
p.apiForceReloadCh = make(chan struct{})
startRefreshLoop(t, p)
p.apiForceReloadCh <- struct{}{}
select {
case req := <-captured:
if _, ok := req.Metadata["username"]; ok {
t.Error("periodic/forced API refresh included username")
}
if req.IncludeHostnameHints {
t.Error("periodic/forced API refresh requested hostname hints")
}
case <-time.After(5 * time.Second):
t.Fatal("periodic/forced API refresh did not fetch resolver config")
}
}
// TestApiConfigReloadAppliesAllowedDestinations drives apiConfigReload itself -
// the loop that owns the refresh ticker and the forced-reload channel - rather
// than the handler it calls, so the wiring between them is covered too: removing
+41 -14
View File
@@ -823,7 +823,7 @@ type apiPreflight struct {
// with no stop channel - as an operator stop. Reading the stop channel directly is also
// independent of whether the context's watcher goroutine has been scheduled yet.
func runAPIPreflight(stopCh <-chan struct{}, cfg *ctrld.Config) apiPreflight {
rc, err := fetchCDConfigBoundedBy(stopCh, cfg)
rc, err := fetchCDConfigBoundedBy(stopCh, cfg, processCDFlagsFn)
return apiPreflight{rc: rc, err: err, stopRequested: stopRequested(stopCh)}
}
@@ -1000,25 +1000,32 @@ func handleAPIPreflightFailure(p *prog, err error, notify func()) {
failProvision(newProvisionResult(code, fmt.Sprintf("failed to fetch resolver config: %v", err), nil, provisionSecrets()...), notify)
}
// processCDFlagsFn is the API fetch, indirected so the lifetime binding around it can be
// tested without reaching the network.
var processCDFlagsFn = processCDFlags
// The startup (full metadata) and reload (runtime metadata) API fetches are indirected so
// their lifetime binding can be tested without reaching the network.
var (
processCDFlagsFn = processCDFlags
processCDFlagsRuntimeFn = processCDFlagsRuntime
)
// fetchCDConfigBoundedBy runs the API fetch bounded by stopCh, so a fetch that cannot
// reach the API stops when the service is asked to stop instead of working on behalf of a
// service the OS already considers stopped. The derived context is always cancelled, which
// fetchCDConfigBoundedBy runs fetch bounded by stopCh, so a fetch that cannot reach the
// API stops when the service is asked to stop instead of working on behalf of a service
// the OS already considers stopped. The derived context is always cancelled, which
// releases the goroutine watching stopCh.
func fetchCDConfigBoundedBy(stopCh <-chan struct{}, cfg *ctrld.Config) (*controld.ResolverConfig, error) {
func fetchCDConfigBoundedBy(
stopCh <-chan struct{},
cfg *ctrld.Config,
fetch func(context.Context, *ctrld.Config) (*controld.ResolverConfig, error),
) (*controld.ResolverConfig, error) {
ctx, cancel := contextFromStopCh(stopCh)
defer cancel()
return processCDFlagsFn(ctx, cfg)
return fetch(ctx, cfg)
}
// fetchCDConfigBoundedByLifetime is the reload path's fetch. Reload binds the same stop
// primitives as startup - it used to wire them up itself, where a dropped cancel or the
// wrong channel would have failed nothing.
func (p *prog) fetchCDConfigBoundedByLifetime(cfg *ctrld.Config) (*controld.ResolverConfig, error) {
return fetchCDConfigBoundedBy(p.stopCh, cfg)
return fetchCDConfigBoundedBy(p.stopCh, cfg, processCDFlagsRuntimeFn)
}
// stopRequested reports whether stopCh has been closed. A nil channel - mobile passes
@@ -1057,6 +1064,23 @@ func contextFromStopCh(stopCh <-chan struct{}) (context.Context, context.CancelF
// come up), so it must be cancellable: otherwise a stop request during preflight is
// ignored and the process keeps retrying after the service reports itself stopped.
func processCDFlags(ctx context.Context, cfg *ctrld.Config) (*controld.ResolverConfig, error) {
return processCDFlagsWithMetadata(ctx, cfg, startupMetadata, true)
}
// startupMetadata is the daemon-start metadata source, indirected so tests can
// prove that startup, and only startup, uses it.
var startupMetadata = ctrld.SystemMetadataStartup
func processCDFlagsRuntime(ctx context.Context, cfg *ctrld.Config) (*controld.ResolverConfig, error) {
return processCDFlagsWithMetadata(ctx, cfg, ctrld.SystemMetadataRuntime, false)
}
func processCDFlagsWithMetadata(
ctx context.Context,
cfg *ctrld.Config,
metadata func(context.Context) map[string]string,
includeHostnameHints bool,
) (*controld.ResolverConfig, error) {
logger := mainLog.Load().With().Str("mode", "cd")
logger.Info().Msgf("Fetching Controld D configuration from API: %s", cdUID)
bo := backoff.NewBackoff("processCDFlags", logf, 30*time.Second)
@@ -1066,9 +1090,10 @@ func processCDFlags(ctx context.Context, cfg *ctrld.Config) (*controld.ResolverC
}
ctx = ctrld.LoggerCtx(ctx, logger)
req := &controld.ResolverConfigRequest{
RawUID: cdUID,
Version: appVersion,
Metadata: ctrld.SystemMetadata(ctx),
RawUID: cdUID,
Version: appVersion,
Metadata: metadata(ctx),
IncludeHostnameHints: includeHostnameHints,
}
resolverConfig, err := fetchResolverConfig(ctx, req, cdDev)
@@ -2673,10 +2698,12 @@ func apiRejectionMessage(err error) string {
// itself, with no process exit.
func doValidateCdRemoteConfig(cdUID string, fatal bool) error {
loggerCtx := ctrld.LoggerCtx(context.Background(), mainLog.Load())
// Install and restart validation use runtime metadata. The daemon start
// that follows sends the full snapshot.
req := &controld.ResolverConfigRequest{
RawUID: cdUID,
Version: appVersion,
Metadata: ctrld.SystemMetadata(loggerCtx),
Metadata: ctrld.SystemMetadataRuntime(loggerCtx),
}
rc, err := fetchResolverConfig(loggerCtx, req, cdDev)
if err != nil {
+44 -5
View File
@@ -57,6 +57,44 @@ func TestContextFromStopCh(t *testing.T) {
})
}
func TestManagedConfigFetchMetadataScope(t *testing.T) {
oldFetch, oldStartup := fetchResolverConfig, startupMetadata
oldUID := cdUID
t.Cleanup(func() {
fetchResolverConfig, startupMetadata = oldFetch, oldStartup
cdUID = oldUID
})
cdUID = "testuid"
startupMetadata = func(context.Context) map[string]string {
return map[string]string{"username": "session-user"}
}
requests := make(chan *controld.ResolverConfigRequest, 2)
fetchResolverConfig = func(_ context.Context, req *controld.ResolverConfigRequest, _ bool) (*controld.ResolverConfig, error) {
requests <- req
return nil, errors.New("stop after capturing metadata")
}
_, _ = processCDFlags(context.Background(), &ctrld.Config{})
startup := <-requests
if got := startup.Metadata["username"]; got != "session-user" {
t.Errorf("managed startup username = %q, want the startup metadata source", got)
}
if !startup.IncludeHostnameHints {
t.Error("managed startup did not request hostname hints")
}
p := &prog{stopCh: make(chan struct{})}
_, _ = p.fetchCDConfigBoundedByLifetime(&ctrld.Config{})
runtime := <-requests
if _, ok := runtime.Metadata["username"]; ok {
t.Error("runtime reload metadata included username")
}
if runtime.IncludeHostnameHints {
t.Error("runtime reload requested hostname hints")
}
}
// retryableNetworkErr is the shape processCDFlags treats as "retry with bootstrap
// DNS": a url.Error wrapping a network failure.
func retryableNetworkErr() error {
@@ -353,17 +391,18 @@ func TestStopRequested(t *testing.T) {
// Reload fetches the ControlD config too, and it used to build the bounded context
// itself. Nothing tested that: the wrong channel, or a dropped cancel, would have left a
// reload retrying against an unreachable API after "Service stopped" was logged, and no
// test would have failed. Both paths now go through one bounded fetch, so this pins it.
// test would have failed. The reload path still binds its runtime-only metadata fetch to
// the service lifetime, so this pins both cancellation and watcher cleanup.
func TestReloadFetchIsBoundedByServiceLifetime(t *testing.T) {
original := processCDFlagsFn
t.Cleanup(func() { processCDFlagsFn = original })
original := processCDFlagsRuntimeFn
t.Cleanup(func() { processCDFlagsRuntimeFn = original })
t.Run("a stop request cancels the reload fetch", func(t *testing.T) {
stopCh := make(chan struct{})
close(stopCh)
var sawCancelled bool
processCDFlagsFn = func(ctx context.Context, _ *ctrld.Config) (*controld.ResolverConfig, error) {
processCDFlagsRuntimeFn = func(ctx context.Context, _ *ctrld.Config) (*controld.ResolverConfig, error) {
select {
case <-ctx.Done():
sawCancelled = true
@@ -385,7 +424,7 @@ func TestReloadFetchIsBoundedByServiceLifetime(t *testing.T) {
// stopCh stays open: the fetch's own cancel is what must end the watcher, or
// every reload leaks a goroutine.
var captured context.Context
processCDFlagsFn = func(ctx context.Context, _ *ctrld.Config) (*controld.ResolverConfig, error) {
processCDFlagsRuntimeFn = func(ctx context.Context, _ *ctrld.Config) (*controld.ResolverConfig, error) {
captured = ctx
return nil, nil
}
+1 -1
View File
@@ -1716,7 +1716,7 @@ func (p *prog) doSelfUninstall(pr *proxyResponse) {
req := &controld.ResolverConfigRequest{
RawUID: cdUID,
Version: appVersion,
Metadata: ctrld.SystemMetadata(loggerCtx),
Metadata: ctrld.SystemMetadataRuntime(loggerCtx),
}
_, err := fetchResolverConfig(loggerCtx, req, cdDev)
logger.Debug().Msg("Maximum number of refused queries reached, checking device status")
+82
View File
@@ -0,0 +1,82 @@
package cli
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/miekg/dns"
"github.com/Control-D-Inc/ctrld/internal/controld"
)
// requireRuntimeMetadata asserts the runtime half of the startup-versus-runtime
// wire contract in docs/username-detection.md: no username discovery and no
// hostname hints.
func requireRuntimeMetadata(t *testing.T, caller string, req *controld.ResolverConfigRequest) {
t.Helper()
if req == nil {
t.Fatalf("%s did not send a resolver config request", caller)
}
if _, ok := req.Metadata["username"]; ok {
t.Errorf("%s request included username", caller)
}
if req.IncludeHostnameHints {
t.Errorf("%s request asked for hostname hints", caller)
}
}
func TestDeactivationPinRefreshUsesRuntimeMetadata(t *testing.T) {
oldFetch, oldUID := fetchResolverConfig, cdUID
oldPin, oldKnown := cdDeactivationPin.Load(), deactivationPinKnown.Load()
t.Cleanup(func() {
fetchResolverConfig, cdUID = oldFetch, oldUID
cdDeactivationPin.Store(oldPin)
deactivationPinKnown.Store(oldKnown)
deactivationLockedUntil.Store(0)
})
cdUID = "test-uid"
deactivationLockedUntil.Store(0)
var captured *controld.ResolverConfigRequest
fetchResolverConfig = func(_ context.Context, req *controld.ResolverConfigRequest, _ bool) (*controld.ResolverConfig, error) {
captured = req
return &controld.ResolverConfig{}, nil
}
p := &prog{cs: &controlServer{mux: http.NewServeMux()}, pinCodeValidCh: make(chan struct{}, 1)}
p.logger.Store(discardLogger())
p.registerControlServerHandler()
body, _ := json.Marshal(&deactivationRequest{Pin: defaultDeactivationPin})
req := httptest.NewRequest(http.MethodPost, deactivationPath, strings.NewReader(string(body)))
p.cs.mux.ServeHTTP(httptest.NewRecorder(), req)
requireRuntimeMetadata(t, "deactivation-PIN refresh", captured)
}
func TestSelfUninstallCheckUsesRuntimeMetadata(t *testing.T) {
oldFetch, oldUID := fetchResolverConfig, cdUID
t.Cleanup(func() { fetchResolverConfig, cdUID = oldFetch, oldUID })
cdUID = "test-uid"
var captured *controld.ResolverConfigRequest
fetchResolverConfig = func(_ context.Context, req *controld.ResolverConfigRequest, _ bool) (*controld.ResolverConfig, error) {
captured = req
// A generic failure is not a device-deleted answer, so no uninstall runs.
return nil, errors.New("stop after capturing metadata")
}
p := &prog{}
p.logger.Store(discardLogger())
p.canSelfUninstall.Store(true)
p.refusedQueryCount = selfUninstallMaxQueries + 1
refused := new(dns.Msg)
refused.SetRcode(newDnsMsgWithHostname("example.com.", dns.TypeA), dns.RcodeRefused)
p.doSelfUninstall(&proxyResponse{answer: refused})
requireRuntimeMetadata(t, "self-uninstall check", captured)
}
+1 -1
View File
@@ -767,7 +767,7 @@ func (p *prog) apiConfigReload() {
req := &controld.ResolverConfigRequest{
RawUID: cdUID,
Version: appVersion,
Metadata: ctrld.SystemMetadata(loggerCtx),
Metadata: ctrld.SystemMetadataRuntime(loggerCtx),
}
resolverConfig, err := fetchResolverConfigFn(loggerCtx, req, cdDev)
if ctx.Err() != nil {