diff --git a/internal/domain/identity/identity.go b/internal/domain/identity/identity.go index e2f84ec9f..5dd89b0ed 100644 --- a/internal/domain/identity/identity.go +++ b/internal/domain/identity/identity.go @@ -95,8 +95,25 @@ func New(id IdentityID, kind Kind, displayName string) (Identity, error) { return value, nil } +// FromLegacyName builds the bot identity a configured name denotes -- the +// identity a [[identities]] entry, or the single bot_user, seeds. It is the +// one place a configuration name becomes an identity, so the file path that +// seeds and the store path that creates cannot disagree: both derive through +// New, and therefore through ValidDisplayName. +func FromLegacyName(legacyName string) (Identity, error) { + return New(StableID(legacyName), KindBot, legacyName) +} + +// ValidDisplayName reports whether name can be an identity display name: the +// non-empty-after-trimming rule Validate applies. A configuration loader that +// seeds an identity from a name calls this so the values it accepts and the +// values the store accepts are the same set, rather than two rules on one +// string (a whitespace-only name passed the loader's empty-string test and +// then failed here). +func ValidDisplayName(name string) bool { return strings.TrimSpace(name) != "" } + func (i Identity) Validate() error { - if i.ID == "" || strings.TrimSpace(i.DisplayName) == "" { + if i.ID == "" || !ValidDisplayName(i.DisplayName) { return fmt.Errorf("%w: ID and display name are required", ErrInvalid) } switch i.Kind { diff --git a/internal/infrastructure/configuration/identity_agreement_test.go b/internal/infrastructure/configuration/identity_agreement_test.go new file mode 100644 index 000000000..52e2286bd --- /dev/null +++ b/internal/infrastructure/configuration/identity_agreement_test.go @@ -0,0 +1,83 @@ +package configuration + +import ( + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/identity" +) + +// TestIdentityNameRuleAgreesAcrossFileAndStore pins the one field both paths +// judge: a configured identity name becomes the store identity's display name +// (internal/app/archied.configuredIdentityNames -> +// postgres.Store.BootstrapIdentities -> identity.New), so a name the file +// loader accepts must be a name the store accepts, and a name it refuses must +// be refused on both sides. Two rule sets on the same string is how a name of +// spaces passed the file's `name == ""` check and then failed the store's +// trimmed check -- the file accepted a config the State Store could not boot +// with. +func TestIdentityNameRuleAgreesAcrossFileAndStore(t *testing.T) { + tests := []struct { + name string + configured string + wantReject bool + }{ + {name: "ordinary name", configured: "personal"}, + {name: "name padded with whitespace", configured: " personal "}, + {name: "whitespace-only name", configured: " ", wantReject: true}, + {name: "empty name", configured: "", wantReject: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := minimalValidConfig() + cfg.BotUser = "" + cfg.Identities = []config.IdentityConfig{{ + Name: tt.configured, + BotUser: "archie-personal", + Repos: []config.Repo{{Owner: "acme", Name: "app"}}, + Forge: config.Forge{Type: "none"}, + }} + fileErr := Validate(&cfg) + _, storeErr := identity.New(identity.StableID(tt.configured), identity.KindBot, tt.configured) + if (fileErr != nil) != tt.wantReject { + t.Fatalf("Validate(identities[0].name=%q) = %v, wantReject=%v", tt.configured, fileErr, tt.wantReject) + } + if (storeErr != nil) != tt.wantReject { + t.Fatalf("identity.New(%q) = %v, wantReject=%v", tt.configured, storeErr, tt.wantReject) + } + }) + } +} + +// TestBotUserNameRuleAgreesAcrossFileAndStore is the single-identity half of +// the same rule: configuredIdentityNames turns bot_user into the same display +// name, and BootstrapIdentities trims it the way identity.New does, so the +// file loader's `bot_user == ""` test must reject a name of spaces exactly as +// the store does. +func TestBotUserNameRuleAgreesAcrossFileAndStore(t *testing.T) { + tests := []struct { + name string + botUser string + wantReject bool + }{ + {name: "ordinary bot user", botUser: "archie-bot"}, + {name: "bot user padded with whitespace", botUser: " archie-bot "}, + {name: "whitespace-only bot user", botUser: " ", wantReject: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := minimalValidConfig() + cfg.BotUser = tt.botUser + fileErr := Validate(&cfg) + trimmed := strings.TrimSpace(tt.botUser) + _, storeErr := identity.New(identity.StableID(trimmed), identity.KindBot, trimmed) + if (fileErr != nil) != tt.wantReject { + t.Fatalf("Validate(bot_user=%q) = %v, wantReject=%v", tt.botUser, fileErr, tt.wantReject) + } + if (storeErr != nil) != tt.wantReject { + t.Fatalf("identity.New(bot_user=%q) = %v, wantReject=%v", tt.botUser, storeErr, tt.wantReject) + } + }) + } +} diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index 66d748e5f..efaa76ab1 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/identity" ) // Recognised enum values, named so validation and its error message cannot @@ -342,7 +343,10 @@ func validateIdentityStructure(cfg *config.Config) error { func validateIdentities(identities []config.IdentityConfig) error { for i, id := range identities { - if id.Name == "" { + // The name rule belongs to the identity feature, which the store path + // also applies (identity.New). Calling it here keeps a name the file + // accepts from being a name the store refuses. + if !identity.ValidDisplayName(id.Name) { return fmt.Errorf("%w: identities[%d].name is required", ErrInvalidInput, i) } if id.BotUser == "" { @@ -372,7 +376,10 @@ func ForgeDisabled(t string) bool { } func validateSingleIdentity(cfg *config.Config) error { - if cfg.BotUser == "" { + // bot_user becomes the seeded identity's display name + // (configuredIdentityNames -> identity.New), so it is judged by the same + // rule rather than a second empty-string test. + if !identity.ValidDisplayName(cfg.BotUser) { return fmt.Errorf("%w: bot_user is required (or define [[identities]])", ErrInvalidInput) } if !oneOf(cfg.Forge.Type, forgeTypes) { diff --git a/internal/infrastructure/postgres/identities.go b/internal/infrastructure/postgres/identities.go index 228601987..1830eb09f 100644 --- a/internal/infrastructure/postgres/identities.go +++ b/internal/infrastructure/postgres/identities.go @@ -232,47 +232,35 @@ func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject // BootstrapIdentities seeds the system identity and the configured legacy // names idempotently, migrating any forge tasks that still carry a legacy -// name to the stable id. +// name to the stable id. Each legacy name is derived through +// identity.FromLegacyName, so a name this store cannot turn into an identity is +// reported rather than silently skipped -- the file loader refuses the same +// names (configuration.validateIdentities). func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) error { - values := append([]struct { - id identity.IdentityID - kind identity.Kind - name string - }{{identity.SystemID, identity.KindSystem, "System"}}, make([]struct { - id identity.IdentityID - kind identity.Kind - name string - }, len(legacyNames))...) - for i, name := range legacyNames { - name = strings.TrimSpace(name) - values[i+1] = struct { - id identity.IdentityID - kind identity.Kind - name string - }{identity.StableID(name), identity.KindBot, name} - } - for _, seed := range values { - if seed.name == "" { - continue - } - value, err := identity.New(seed.id, seed.kind, seed.name) + values := make([]identity.Identity, 0, len(legacyNames)+1) + values = append(values, identity.System()) + for _, name := range legacyNames { + value, err := identity.FromLegacyName(name) if err != nil { - return err + return fmt.Errorf("bootstrap identity %q: %w", name, err) } - _, err = s.Create(ctx, value, identity.Audit{ - ActorID: identity.SystemID, Source: "legacy-config", RequestID: "identity-import:" + string(seed.id), + values = append(values, value) + } + for _, value := range values { + _, err := s.Create(ctx, value, identity.Audit{ + ActorID: identity.SystemID, Source: "legacy-config", RequestID: "identity-import:" + string(value.ID), }) if err != nil && !isUniqueViolation(err) { - return fmt.Errorf("bootstrap identity %q: %w", seed.name, err) + return fmt.Errorf("bootstrap identity %q: %w", value.DisplayName, err) } if err := s.queries().InsertIdentityAliasIgnoreConflict(ctx, postgresdb.InsertIdentityAliasIgnoreConflictParams{ - Alias: seed.name, IdentityID: string(seed.id), + Alias: value.DisplayName, IdentityID: string(value.ID), }); err != nil { return err } - if seed.kind != identity.KindSystem { + if value.Kind != identity.KindSystem { if err := s.queries().UpdateTaskIdentity(ctx, postgresdb.UpdateTaskIdentityParams{ - Identity: string(seed.id), Identity_2: seed.name, + Identity: string(value.ID), Identity_2: value.DisplayName, }); err != nil { return err } diff --git a/internal/infrastructure/staterpc/domain_validation_test.go b/internal/infrastructure/staterpc/domain_validation_test.go new file mode 100644 index 000000000..71f8bc639 --- /dev/null +++ b/internal/infrastructure/staterpc/domain_validation_test.go @@ -0,0 +1,126 @@ +package staterpc + +import ( + "context" + "log/slog" + "testing" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + "github.com/samcharles93/archie-core/internal/domain/binding" + "github.com/samcharles93/archie-core/internal/domain/mapping" + "github.com/samcharles93/archie-core/internal/domain/storecontract" +) + +// The two recorders embed the store interface so only the methods under test +// need an implementation; a call to any other method panics rather than +// silently succeeding, which is what a test exercising one RPC wants. +type mappingRecorder struct { + storecontract.MappingStore + inserted, updated int +} + +func (r *mappingRecorder) InsertMapping(context.Context, mapping.Mapping) (string, error) { + r.inserted++ + return "mapping-1", nil +} + +func (r *mappingRecorder) UpdateMapping(context.Context, mapping.Mapping) error { + r.updated++ + return nil +} + +type bindingRecorder struct { + storecontract.BindingStore + inserted, updated int +} + +func (r *bindingRecorder) InsertBinding(context.Context, binding.Binding) (string, error) { + r.inserted++ + return "binding-1", nil +} + +func (r *bindingRecorder) UpdateBinding(context.Context, binding.Binding) error { + r.updated++ + return nil +} + +func validationOnlyServer(mappings storecontract.MappingStore, bindings storecontract.BindingStore) *server { + return &server{deps: Deps{ + Mappings: mappings, Bindings: bindings, + Log: slog.New(slog.DiscardHandler), + }} +} + +// TestDomainManagedRPCsApplyTheFeatureValidation pins that the domain API the +// control-plane catalog advertises for capture-mappings and capture-bindings +// enforces the feature's own rule. The rule is owned by +// internal/domain/mapping and internal/domain/binding and applied by the +// dashboard today; a stored path that does not apply it accepts a value the +// feature refuses, which is the two-validators disagreement this closes. The +// refused value must not reach the store. +func TestDomainManagedRPCsApplyTheFeatureValidation(t *testing.T) { + t.Run("insert mapping", func(t *testing.T) { + if err := (mapping.Mapping{}).Validate(); err == nil { + t.Fatal("precondition: the mapping domain accepts an unnamed mapping") + } + recorder := &mappingRecorder{} + _, err := validationOnlyServer(recorder, nil).InsertMapping(t.Context(), &pb.InsertMappingRequest{Mapping: &pb.Mapping{}}) + if err == nil { + t.Fatal("InsertMapping accepted a mapping the mapping domain refuses") + } + if code := status.Code(err); code != codes.InvalidArgument { + t.Errorf("InsertMapping error code = %v, want %v (%v)", code, codes.InvalidArgument, err) + } + if recorder.inserted != 0 { + t.Errorf("invalid mapping reached the store %d time(s)", recorder.inserted) + } + }) + + t.Run("update mapping", func(t *testing.T) { + recorder := &mappingRecorder{} + _, err := validationOnlyServer(recorder, nil).UpdateMapping(t.Context(), &pb.UpdateMappingRequest{Mapping: &pb.Mapping{}}) + if err == nil { + t.Fatal("UpdateMapping accepted a mapping the mapping domain refuses") + } + if code := status.Code(err); code != codes.InvalidArgument { + t.Errorf("UpdateMapping error code = %v, want %v (%v)", code, codes.InvalidArgument, err) + } + if recorder.updated != 0 { + t.Errorf("invalid mapping reached the store %d time(s)", recorder.updated) + } + }) + + t.Run("insert binding", func(t *testing.T) { + if err := (binding.Binding{}).Validate(); err == nil { + t.Fatal("precondition: the binding domain accepts an unnamed binding") + } + recorder := &bindingRecorder{} + _, err := validationOnlyServer(nil, recorder).InsertBinding(t.Context(), &pb.InsertBindingRequest{Binding: &pb.Binding{}}) + if err == nil { + t.Fatal("InsertBinding accepted a binding the binding domain refuses") + } + if code := status.Code(err); code != codes.InvalidArgument { + t.Errorf("InsertBinding error code = %v, want %v (%v)", code, codes.InvalidArgument, err) + } + if recorder.inserted != 0 { + t.Errorf("invalid binding reached the store %d time(s)", recorder.inserted) + } + }) + + t.Run("update binding", func(t *testing.T) { + recorder := &bindingRecorder{} + _, err := validationOnlyServer(nil, recorder).UpdateBinding(t.Context(), &pb.UpdateBindingRequest{Binding: &pb.Binding{}}) + if err == nil { + t.Fatal("UpdateBinding accepted a binding the binding domain refuses") + } + if code := status.Code(err); code != codes.InvalidArgument { + t.Errorf("UpdateBinding error code = %v, want %v (%v)", code, codes.InvalidArgument, err) + } + if recorder.updated != 0 { + t.Errorf("invalid binding reached the store %d time(s)", recorder.updated) + } + }) +} diff --git a/internal/infrastructure/staterpc/server.go b/internal/infrastructure/staterpc/server.go index 5cfb2f957..27b1cb442 100644 --- a/internal/infrastructure/staterpc/server.go +++ b/internal/infrastructure/staterpc/server.go @@ -167,6 +167,17 @@ func (s *server) logErr(rpc string, err error) error { return mapError(err) } +// validationFailure answers a write the owning feature's own Validate refused. +// The domain-managed kinds (identities, captures, mappings, bindings) are +// advertised in the control-plane catalog but are not stored as generic +// documents, so it is these RPC handlers -- not the catalog -- that must apply +// the feature's rule. The rule itself stays in the domain package; this only +// translates its error for the wire, and it is deliberately not codes.Internal +// (an unjudged value is the caller's fault, not this process's). +func validationFailure(err error) error { + return status.Error(codes.InvalidArgument, err.Error()) +} + // Lifecycle func (s *server) EnqueueIssue(ctx context.Context, r *pb.EnqueueIssueRequest) (*pb.EnqueueIssueResponse, error) { @@ -642,7 +653,11 @@ func (s *server) InsertMapping(ctx context.Context, r *pb.InsertMappingRequest) if err != nil { return nil, err } - id, err := ms.InsertMapping(ctx, mappingValue(r.Mapping)) + value := mappingValue(r.Mapping) + if err := value.Validate(); err != nil { + return nil, validationFailure(err) + } + id, err := ms.InsertMapping(ctx, value) if err != nil { return nil, s.logErr("InsertMapping", err) } @@ -678,7 +693,11 @@ func (s *server) UpdateMapping(ctx context.Context, r *pb.UpdateMappingRequest) if err != nil { return nil, err } - if err := ms.UpdateMapping(ctx, mappingValue(r.Mapping)); err != nil { + value := mappingValue(r.Mapping) + if err := value.Validate(); err != nil { + return nil, validationFailure(err) + } + if err := ms.UpdateMapping(ctx, value); err != nil { return nil, s.logErr("UpdateMapping", err) } return &pb.UpdateMappingResponse{}, nil @@ -719,7 +738,11 @@ func (s *server) InsertBinding(ctx context.Context, r *pb.InsertBindingRequest) if err != nil { return nil, err } - id, err := bs.InsertBinding(ctx, bindingValue(r.Binding)) + value := bindingValue(r.Binding) + if err := value.Validate(); err != nil { + return nil, validationFailure(err) + } + id, err := bs.InsertBinding(ctx, value) if err != nil { return nil, s.logErr("InsertBinding", err) } @@ -755,7 +778,11 @@ func (s *server) UpdateBinding(ctx context.Context, r *pb.UpdateBindingRequest) if err != nil { return nil, err } - if err := bs.UpdateBinding(ctx, bindingValue(r.Binding)); err != nil { + value := bindingValue(r.Binding) + if err := value.Validate(); err != nil { + return nil, validationFailure(err) + } + if err := bs.UpdateBinding(ctx, value); err != nil { return nil, s.logErr("UpdateBinding", err) } return &pb.UpdateBindingResponse{}, nil