Add D&D location occurrence validators
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
// Package registry validates location occurrence identity against location grounding.
|
||||
package registry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
locationregistry "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/locations/registry"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
|
||||
occurrenceshape "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/locationoccurrences/shape"
|
||||
)
|
||||
|
||||
const (
|
||||
Key = "extract/dnd/location-occurrences/registry"
|
||||
ReasonCode = "invalid_location_occurrence_registry"
|
||||
policy = "dnd.location_occurrences.validator.registry.v1"
|
||||
)
|
||||
|
||||
type Options struct{}
|
||||
type Validator struct{ locationResolver *locationregistry.Resolver }
|
||||
|
||||
var _ contracts.TypedValidator[dnd.LocationOccurrenceList] = (*Validator)(nil)
|
||||
var _ contracts.ManifestMetadataProvider = (*Validator)(nil)
|
||||
var _ pipeline.CheckpointFingerprintProvider = (*Validator)(nil)
|
||||
|
||||
func New(_ Options, references ...contracts.ReferenceSet) (*Validator, error) {
|
||||
if len(references) > 1 {
|
||||
return nil, fmt.Errorf("location occurrence registry validator accepts at most one reference set")
|
||||
}
|
||||
var referenceSet contracts.ReferenceSet
|
||||
if len(references) == 1 {
|
||||
referenceSet = references[0]
|
||||
}
|
||||
resolver, err := locationregistry.NewResolver(referenceSet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("prepare location registry: %w", err)
|
||||
}
|
||||
return &Validator{locationResolver: resolver}, nil
|
||||
}
|
||||
|
||||
func (v *Validator) Name() string { return Key }
|
||||
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *Validator) ManifestMetadata() map[string]any {
|
||||
if v == nil || v.locationResolver == nil {
|
||||
return nil
|
||||
}
|
||||
metadata := map[string]any{"policy": policy}
|
||||
seeded := v.locationResolver.Seeded()
|
||||
if seeded.Bound() {
|
||||
metadata["location_registry_digest"] = seeded.Digest()
|
||||
metadata["location_count"] = seeded.Count()
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
func (v *Validator) CheckpointFingerprints() []pipeline.CheckpointFingerprint {
|
||||
if v == nil || v.locationResolver == nil {
|
||||
return nil
|
||||
}
|
||||
return []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}, {Name: "location_registry", Value: v.locationResolver.Seeded().ProjectionDigest()}}
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationRequest[dnd.LocationOccurrenceList]) (contracts.ValidationResult, error) {
|
||||
if occurrenceshape.Validate(req.Value) != nil {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
if v == nil || v.locationResolver == nil {
|
||||
return contracts.ValidationResult{}, fmt.Errorf("location occurrence registry validator must not be nil")
|
||||
}
|
||||
registry, err := v.locationResolver.Resolve(req.References)
|
||||
if err != nil {
|
||||
return contracts.ValidationResult{}, fmt.Errorf("resolve location registry: %w", err)
|
||||
}
|
||||
if !registry.Bound() {
|
||||
return rejection([]string{"location registry reference is required"}), nil
|
||||
}
|
||||
issues := make([]string, 0)
|
||||
for index, occurrence := range req.Value.Occurrences {
|
||||
location, ok := registry.Lookup(occurrence.LocationID)
|
||||
if !ok {
|
||||
issues = append(issues, fmt.Sprintf("occurrences[%d].location_id is not in the location registry: %s", index, diagnostics.Quote(occurrence.LocationID)))
|
||||
continue
|
||||
}
|
||||
if occurrence.Name != location.Name {
|
||||
issues = append(issues, fmt.Sprintf("occurrences[%d] does not match registry location %s", index, diagnostics.Quote(occurrence.LocationID)))
|
||||
}
|
||||
}
|
||||
if len(issues) == 0 {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
return rejection(issues), nil
|
||||
}
|
||||
|
||||
func rejection(issues []string) contracts.ValidationResult {
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: diagnostics.Aggregate("invalid location occurrence registry", issues)}
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
|
||||
}
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
return pipeline.RegisterTypedValidatorBuilder(registry, dnd.LocationOccurrenceListKind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[dnd.LocationOccurrenceList], error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(options, request.References)
|
||||
})
|
||||
}
|
||||
func DecodeOptions(options map[string]any) (Options, error) {
|
||||
if err := pipeline.RejectUnknownOptions(options); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
return Options{}, nil
|
||||
}
|
||||
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
||||
@@ -0,0 +1,109 @@
|
||||
package registry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
locationcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/locations"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/locations/identity"
|
||||
locationregistry "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/locations/registry"
|
||||
)
|
||||
|
||||
func TestValidatorDistinguishesSameNameLocationsByID(t *testing.T) {
|
||||
references, first, second := registryReferences(t)
|
||||
value := dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{
|
||||
occurrence(first.ID, first.Name), occurrence(second.ID, second.Name),
|
||||
}}
|
||||
validator := newValidator(t, references)
|
||||
before := cloneList(value)
|
||||
result, err := validator.Validate(context.Background(), request(references, value))
|
||||
if err != nil || !result.Approved || !reflect.DeepEqual(value, before) {
|
||||
t.Fatalf("matching IDs = %#v, %v", result, err)
|
||||
}
|
||||
value.Occurrences[0].Name = "Other Gate"
|
||||
result, err = validator.Validate(context.Background(), request(references, value))
|
||||
if err != nil || result.Approved || result.ReasonCode != ReasonCode || !strings.Contains(result.Message, "does not match registry location") {
|
||||
t.Fatalf("mismatched name = %#v, %v", result, err)
|
||||
}
|
||||
value.Occurrences[0].LocationID = "location:unknown"
|
||||
result, err = validator.Validate(context.Background(), request(references, value))
|
||||
if err != nil || result.Approved || !strings.Contains(result.Message, "is not in the location registry") {
|
||||
t.Fatalf("unknown ID = %#v, %v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatorRequiresAndSafelyPreparesRegistry(t *testing.T) {
|
||||
value := dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{occurrence("location:one", "Moon Gate")}}
|
||||
result, err := newValidator(t).Validate(context.Background(), request(contracts.ReferenceSet{}, value))
|
||||
if err != nil || result.Approved || !strings.Contains(result.Message, "required") {
|
||||
t.Fatalf("missing registry = %#v, %v", result, err)
|
||||
}
|
||||
malformed := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{locationregistry.ReferenceSlot: {Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte(`{"secret":"private"}`)}}}}}
|
||||
if _, err := New(Options{}, malformed); err == nil || strings.Contains(err.Error(), "private") {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
references, _, _ := registryReferences(t)
|
||||
metadata, err := json.Marshal(newValidator(t, references).ManifestMetadata())
|
||||
if err != nil || strings.Contains(string(metadata), "Moon Gate") {
|
||||
t.Fatalf("metadata = %s, %v", metadata, err)
|
||||
}
|
||||
if got := newValidator(t, references).CheckpointFingerprints(); len(got) != 2 || got[0].Value != policy || !strings.HasPrefix(got[1].Value, "sha256:") {
|
||||
t.Fatalf("fingerprints = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatorRegistersAndDefersShape(t *testing.T) {
|
||||
references, _, _ := registryReferences(t)
|
||||
result, err := newValidator(t, references).Validate(context.Background(), request(references, dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{{Name: "Missing"}}}))
|
||||
if err != nil || !result.Approved {
|
||||
t.Fatalf("shape deferral = %#v, %v", result, err)
|
||||
}
|
||||
registry := pipeline.NewValidatorRegistry()
|
||||
if err := Register(registry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, ok := registry.Spec(Key); !ok || got != Spec() || got.ExecutionClass != contracts.ExecutionClassDeterministic {
|
||||
t.Fatalf("registered spec = %#v, ok = %t", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func newValidator(t *testing.T, references ...contracts.ReferenceSet) *Validator {
|
||||
t.Helper()
|
||||
validator, err := New(Options{}, references...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return validator
|
||||
}
|
||||
func request(references contracts.ReferenceSet, value dnd.LocationOccurrenceList) contracts.TypedValidationRequest[dnd.LocationOccurrenceList] {
|
||||
return contracts.TypedValidationRequest[dnd.LocationOccurrenceList]{References: references, Value: value}
|
||||
}
|
||||
func occurrence(id, name string) dnd.LocationOccurrence {
|
||||
return dnd.LocationOccurrence{LocationID: id, Name: name, Kind: dnd.LocationOccurrenceKindVisited, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}
|
||||
}
|
||||
func cloneList(value dnd.LocationOccurrenceList) dnd.LocationOccurrenceList {
|
||||
cloned := dnd.LocationOccurrenceList{Occurrences: append([]dnd.LocationOccurrence(nil), value.Occurrences...)}
|
||||
for index := range cloned.Occurrences {
|
||||
cloned.Occurrences[index].SourceRefs = append([]source.SourceRef(nil), value.Occurrences[index].SourceRefs...)
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
func registryReferences(t *testing.T) (contracts.ReferenceSet, dnd.Location, dnd.Location) {
|
||||
t.Helper()
|
||||
firstRefs := []source.SourceRef{{SourceID: "source", StartUnitID: 1, EndUnitID: 1}}
|
||||
secondRefs := []source.SourceRef{{SourceID: "source", StartUnitID: 2, EndUnitID: 2}}
|
||||
first := dnd.Location{ID: identity.DeriveID("Moon Gate", firstRefs), Name: "Moon Gate", SourceRefs: firstRefs}
|
||||
second := dnd.Location{ID: identity.DeriveID("Moon Gate", secondRefs), Name: "Moon Gate", SourceRefs: secondRefs}
|
||||
content, err := locationcodec.New().Encode(dnd.LocationList{Locations: []dnd.Location{first, second}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{locationregistry.ReferenceSlot: {Slot: contracts.ReferenceSlot{Name: locationregistry.ReferenceSlot}, Items: []contracts.ReferenceItem{{SlotName: locationregistry.ReferenceSlot, MediaType: locationcodec.MediaType, Content: content, Origin: contracts.ReferenceOrigin{Type: "generated"}}}}}}, first, second
|
||||
}
|
||||
Reference in New Issue
Block a user