From cc390256a40183fd646a1290f2e9b9436aeb2003 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 19 Sep 2026 01:50:25 +1000 Subject: [PATCH] fix(config): enforce the service context at registration ServiceSpec.Context documented which addresses a service must end up with, but nothing read it, so a typo'd context was accepted and meant nothing. Review caught it as scaffolding that looked load-bearing. RegisterService now validates it: an unknown context, or a hosted (server/both) service registered with no default listen address, panics. Registrations come from this repository's own init(), never from operator input, so an invalid one is a programming error with no caller positioned to handle an error return, and failing at process start beats a service binding where nobody dials. Services.RequireTarget replaces the same check and message hand-written in composeStateStoreClient and composeChatContract. An empty registered default target is what declares a target operator-supplied, so the requirement belongs to the registry rather than to each consumer. It stays a lazy check at composition time rather than becoming load-time validation: a process that never dials a service must still load a configuration that omits it. The review's stated failure mode does not occur. A hosted service with an empty listen does not reach net.Listen as an ephemeral port; resolveServiceListen returns "no listen address" and archied refuses to start. The defect was the inert field, not a silent bind. Refs: archie-core-u23g --- docs/prds/service-registry.md | 7 +- internal/app/archied/chat_service.go | 11 +-- internal/app/archied/state_store_client.go | 9 +-- internal/config/services.go | 21 +++++ internal/config/services_test.go | 92 ++++++++++++++++++++++ internal/config/servicespec.go | 24 ++++++ 6 files changed, 149 insertions(+), 15 deletions(-) diff --git a/docs/prds/service-registry.md b/docs/prds/service-registry.md index 19d5dcd2b..6afe622fc 100644 --- a/docs/prds/service-registry.md +++ b/docs/prds/service-registry.md @@ -60,8 +60,11 @@ Positional, five strings, as the story specifies. Each argument is data the curr states in prose or in a branch: - `context` is `client`, `server`, or `both`, and decides which fields must resolve - non-empty. A `server` or `both` service must end with a `listen`; a `client` or `both` - service must end with a `target`. + non-empty. `RegisterService` enforces it: an unknown context, or a hosted service with + no default `listen`, panics at registration. Registrations come from this repository's + own `init()`, never from operator input, so an invalid one is a programming error with + no caller positioned to handle an error return. A documented-but-unread `Context` would + be worse than no field at all. - `target` is the **default**, and an empty default means the operator must supply one. That single convention replaces the `state.target` required / `gateway.target` defaulted asymmetry with no branch: `state` registers `""`, `gateway` registers an address. diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go index 5b56b6eb7..0fd194303 100644 --- a/internal/app/archied/chat_service.go +++ b/internal/app/archied/chat_service.go @@ -1,9 +1,6 @@ package archied import ( - "fmt" - "strings" - "google.golang.org/grpc" "github.com/samcharles93/archie-core/internal/config" @@ -18,14 +15,14 @@ import ( // itself and the fail-closed non-loopback rule belong to the transport, so // they come from gatewayrpc.Dial. func composeChatContract(services config.Services, secrets *secret.Registry, options ...grpc.DialOption) (gateway.ChatContract, func(), error) { - settings := services.Get(config.ServiceNameGateway) - if strings.TrimSpace(settings.Target) == "" { - return nil, nil, fmt.Errorf("services.gateway.target is required") + target, err := services.RequireTarget(config.ServiceNameGateway) + if err != nil { + return nil, nil, err } // Assigned through a typed variable rather than returned directly: a // direct forward would hand a failed dial's nil *Client back as a // non-nil ChatContract interface. - client, cleanup, err := gatewayrpc.Dial(settings.Target, services.ResolvedToken(config.ServiceNameGateway, secrets.Getenv), options...) + client, cleanup, err := gatewayrpc.Dial(target, services.ResolvedToken(config.ServiceNameGateway, secrets.Getenv), options...) if err != nil { return nil, nil, err } diff --git a/internal/app/archied/state_store_client.go b/internal/app/archied/state_store_client.go index 61820b122..d8e8e4a96 100644 --- a/internal/app/archied/state_store_client.go +++ b/internal/app/archied/state_store_client.go @@ -1,9 +1,6 @@ package archied import ( - "fmt" - "strings" - "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/secret" @@ -15,9 +12,9 @@ import ( // fail-closed non-loopback rule (ยง9) belong to the transport, so they come // from staterpc.Dial. func composeStateStoreClient(services config.Services, secrets *secret.Registry) (*staterpc.Client, func(), error) { - target := strings.TrimSpace(services.Get(config.ServiceNameState).Target) - if target == "" { - return nil, nil, fmt.Errorf("services.state.target is required") + target, err := services.RequireTarget(config.ServiceNameState) + if err != nil { + return nil, nil, err } return staterpc.Dial(target, services.ResolvedToken(config.ServiceNameState, secrets.Getenv)) } diff --git a/internal/config/services.go b/internal/config/services.go index c8d753d26..eda25ffb2 100644 --- a/internal/config/services.go +++ b/internal/config/services.go @@ -1,5 +1,10 @@ package config +import ( + "fmt" + "strings" +) + // Services maps a registered service name to its connection settings, keyed by // the [services.] section it was decoded from. // @@ -35,6 +40,22 @@ func (s Services) ResolvedToken(name string, getenv func(string) string) string return getenv(spec.TokenEnv) } +// RequireTarget returns the dial address for name, or an error naming the +// config key when the operator has not supplied one. +// +// A service registered with an empty default target is one the operator must +// configure, so this is the registry's own contract rather than a consumer's +// private rule. It stays a lazy check at composition time, not a load-time +// validation: a process that never dials a given service must still be able to +// load a configuration that omits it. +func (s Services) RequireTarget(name string) (string, error) { + target := strings.TrimSpace(s[name].Target) + if target == "" { + return "", fmt.Errorf("services.%s.target is required", name) + } + return target, nil +} + // ServiceConnection is a service's gRPC addresses plus the bearer token a // client presents when the target is non-loopback. A client reads only Target // and TargetToken; Listen belongs to the process that owns the service. The diff --git a/internal/config/services_test.go b/internal/config/services_test.go index 9cf877f0a..10325fbbe 100644 --- a/internal/config/services_test.go +++ b/internal/config/services_test.go @@ -1,6 +1,8 @@ package config_test import ( + "fmt" + "strings" "testing" "github.com/samcharles93/archie-core/internal/config" @@ -131,3 +133,93 @@ func TestResolvedTokenOfUnregisteredServiceHasNoEnvFallback(t *testing.T) { t.Errorf("ResolvedToken = %q, want empty", got) } } + +// mustPanic runs fn and returns the recovered value, or fails if fn returned +// normally. Registration errors are programming errors in this repository's +// own init(), not operator input, so they abort the process rather than +// returning an error nobody is positioned to handle. +func mustPanic(t *testing.T, fn func()) (recovered any) { + t.Helper() + defer func() { recovered = recover() }() + fn() + t.Fatal("RegisterService returned normally, want a panic") + return nil +} + +// TestRegisterServiceRejectsAnUnknownContext makes Context load-bearing. It +// documented which addresses a service must end up with, but nothing read it, +// so a typo'd context was accepted and silently meant nothing. +func TestRegisterServiceRejectsAnUnknownContext(t *testing.T) { + got := mustPanic(t, func() { + config.RegisterService("clientt", "widget-badcontext", "", "127.0.0.1:7005", "T") + }) + if !strings.Contains(fmt.Sprint(got), "clientt") { + t.Errorf("panic = %v, want it to name the invalid context", got) + } +} + +// TestRegisterServiceRejectsAHostedServiceWithNoListen pins the requirement +// Context exists to express: a service this repository hosts must have a +// default bind address, because an empty one reaches net.Listen as "any free +// port". +func TestRegisterServiceRejectsAHostedServiceWithNoListen(t *testing.T) { + for _, hosted := range []string{config.ServiceServer, config.ServiceBoth} { + t.Run(hosted, func(t *testing.T) { + got := mustPanic(t, func() { + config.RegisterService(hosted, "widget-nolisten-"+hosted, "127.0.0.1:1", "", "T") + }) + if !strings.Contains(fmt.Sprint(got), "listen") { + t.Errorf("panic = %v, want it to name the missing listen address", got) + } + }) + } +} + +// TestRegisterServiceAcceptsAClientWithNoTargetDefault keeps the State Store's +// own shape legal: a dialled-only service may register an empty target, which +// is how "the operator must supply this" is stated. +func TestRegisterServiceAcceptsAClientWithNoTargetDefault(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("RegisterService panicked on a legal client registration: %v", r) + } + }() + config.RegisterService(config.ServiceClient, "widget-clientok", "", "127.0.0.1:7006", "T") +} + +// TestRequireTargetReportsAnAbsentOperatorSuppliedTarget moves the "target is +// required" check off two hand-written consumer copies and onto the registry, +// which is what declared the target operator-supplied in the first place. +func TestRequireTargetReportsAnAbsentOperatorSuppliedTarget(t *testing.T) { + for _, tt := range []struct { + name string + target string + want string + wantErr bool + }{ + {name: "absent", wantErr: true}, + {name: "blank", target: " \t\n", wantErr: true}, + {name: "set", target: "10.0.0.1:9090", want: "10.0.0.1:9090"}, + {name: "set with padding", target: " 10.0.0.1:9090 ", want: "10.0.0.1:9090"}, + } { + t.Run(tt.name, func(t *testing.T) { + services := config.Services{config.ServiceNameState: {Target: tt.target}} + got, err := services.RequireTarget(config.ServiceNameState) + if tt.wantErr { + if err == nil { + t.Fatal("RequireTarget returned no error for an empty target") + } + if !strings.Contains(err.Error(), "services.state.target") { + t.Errorf("error = %v, want it to name the config key", err) + } + return + } + if err != nil { + t.Fatalf("RequireTarget: %v", err) + } + if got != tt.want { + t.Errorf("RequireTarget = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/internal/config/servicespec.go b/internal/config/servicespec.go index 0b6816458..900aebf01 100644 --- a/internal/config/servicespec.go +++ b/internal/config/servicespec.go @@ -1,7 +1,9 @@ package config import ( + "fmt" "sort" + "strings" "sync" ) @@ -60,7 +62,29 @@ var ( // // Re-registering a name replaces the previous spec, so a test can install a // throwaway service without disturbing the built-ins. +// +// It panics on a registration that cannot be honoured. Registrations come from +// this repository's own init(), never from operator input, so an invalid one is +// a programming error: there is no caller positioned to handle an error return, +// and failing at process start is better than a service that binds somewhere +// nobody dials. Context is enforced here rather than merely documented, so +// "hosted" genuinely implies a bind address. func RegisterService(context, name, target, listen, tokenEnv string) { + switch context { + case ServiceClient, ServiceServer, ServiceBoth: + default: + panic(fmt.Sprintf( + "config.RegisterService(%q): unknown context %q, want %q, %q or %q", + name, context, ServiceClient, ServiceServer, ServiceBoth, + )) + } + if context != ServiceClient && strings.TrimSpace(listen) == "" { + panic(fmt.Sprintf( + "config.RegisterService(%q): a %q service needs a default listen address; "+ + "an empty one reaches net.Listen as \"any free port\"", + name, context, + )) + } serviceRegistryMu.Lock() defer serviceRegistryMu.Unlock() serviceRegistry[name] = ServiceSpec{