diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 6d02ab9..7d90255 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -4,19 +4,28 @@ on: push: branches: [main] pull_request: + workflow_dispatch: permissions: contents: read + packages: read + +concurrency: + group: e2e-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }} + cancel-in-progress: true jobs: e2e: runs-on: ubuntu-latest + timeout-minutes: 60 + env: + GOTOOLCHAIN: local steps: - name: Checkout uses: actions/checkout@v4 - name: Provision cluster - uses: agynio/bootstrap/.github/actions/provision@main + uses: agynio/e2e/.github/actions/provision-vm@main - name: Setup DevSpace uses: agynio/e2e/.github/actions/setup-devspace@main diff --git a/.gitignore b/.gitignore index 97c5c28..f6a10b3 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ .gen/ +Dockerfile.localtest +Dockerfile.localtest.dockerignore diff --git a/Dockerfile b/Dockerfile index 9b1de5a..aeddf5a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -22,12 +22,8 @@ RUN --mount=type=cache,target=/go/pkg/mod \ go mod download COPY buf.gen.yaml buf.yaml ./ -RUN buf generate buf.build/agynio/api \ - --path agynio/api/apps/v1 \ - --path agynio/api/authorization/v1 \ - --path agynio/api/identity/v1 \ - --path agynio/api/ziti_management/v1 \ - --path agynio/api/groups/v1 +# The module and paths come from buf.gen.yaml, so the list lives in one place. +RUN buf generate COPY . . diff --git a/buf.gen.yaml b/buf.gen.yaml index 33834db..c93132e 100644 --- a/buf.gen.yaml +++ b/buf.gen.yaml @@ -28,3 +28,6 @@ inputs: - agynio/api/identity/v1 - agynio/api/ziti_management/v1 - agynio/api/groups/v1 + # Agents and LLM own the entities an x-agyn-ref names. + - agynio/api/agents/v1 + - agynio/api/llm/v1 diff --git a/cmd/apps-service/main.go b/cmd/apps-service/main.go index cfdc5d9..d0f8b2c 100644 --- a/cmd/apps-service/main.go +++ b/cmd/apps-service/main.go @@ -10,10 +10,12 @@ import ( "os/signal" "syscall" + agentsv1 "github.com/agynio/apps/.gen/go/agynio/api/agents/v1" appsv1 "github.com/agynio/apps/.gen/go/agynio/api/apps/v1" authorizationv1 "github.com/agynio/apps/.gen/go/agynio/api/authorization/v1" groupsv1 "github.com/agynio/apps/.gen/go/agynio/api/groups/v1" identityv1 "github.com/agynio/apps/.gen/go/agynio/api/identity/v1" + llmv1 "github.com/agynio/apps/.gen/go/agynio/api/llm/v1" zitimanagementv1 "github.com/agynio/apps/.gen/go/agynio/api/ziti_management/v1" "github.com/jackc/pgx/v5/pgxpool" "google.golang.org/grpc" @@ -78,6 +80,18 @@ func run() error { } defer groupsConn.Close() + agentsConn, err := grpc.NewClient(cfg.AgentsGRPCTarget, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return fmt.Errorf("connect to agents: %w", err) + } + defer agentsConn.Close() + + llmConn, err := grpc.NewClient(cfg.LLMGRPCTarget, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return fmt.Errorf("connect to llm: %w", err) + } + defer llmConn.Close() + grpcServer := grpc.NewServer() serverInstance := server.NewWithGroups( store.New(pool), @@ -86,6 +100,12 @@ func run() error { zitimanagementv1.NewZitiManagementServiceClient(zitiConn), groupsv1.NewGroupsServiceClient(groupsConn), ) + // Without a resolver an installation carrying an x-agyn-ref is refused + // rather than stored unvalidated. + serverInstance.SetReferenceResolver(server.NewServiceReferenceResolver( + agentsv1.NewAgentsServiceClient(agentsConn), + llmv1.NewLLMServiceClient(llmConn), + )) appsv1.RegisterAppsServiceServer(grpcServer, serverInstance) serverInstance.StartGroupMembershipConsumerLoop(ctx, cfg.NATSURL, cfg.GroupSyncDurable) diff --git a/devspace.yaml b/devspace.yaml index df4c5cd..2417221 100644 --- a/devspace.yaml +++ b/devspace.yaml @@ -1,7 +1,7 @@ version: v2beta1 vars: - APPS_NAMESPACE: platform + APPS_NAMESPACE: agyn-platform functions: patch_deployment: |- @@ -101,12 +101,7 @@ pipelines: echo "Using go: ${GO_BIN}" "${GO_BIN}" version cd /opt/app/data - buf generate buf.build/agynio/api \ - --path agynio/api/apps/v1 \ - --path agynio/api/authorization/v1 \ - --path agynio/api/identity/v1 \ - --path agynio/api/ziti_management/v1 \ - --path agynio/api/groups/v1 + buf generate nohup "${GO_BIN}" run ./cmd/apps-service >/tmp/apps-service.log 2>&1 & ' echo "Waiting for apps to be healthy on :50051..." diff --git a/internal/config/config.go b/internal/config/config.go index 4713175..f844f20 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -13,9 +13,12 @@ type Config struct { AuthorizationGRPCTarget string ZitiManagementGRPCTarget string GroupsGRPCTarget string - NATSURL string - GroupSyncDurable string - ReconciliationInterval time.Duration + // Agents and LLM own the entities an x-agyn-ref names. + AgentsGRPCTarget string + LLMGRPCTarget string + NATSURL string + GroupSyncDurable string + ReconciliationInterval time.Duration } func FromEnv() (Config, error) { @@ -44,6 +47,14 @@ func FromEnv() (Config, error) { if cfg.GroupsGRPCTarget == "" { cfg.GroupsGRPCTarget = "groups:50051" } + cfg.AgentsGRPCTarget = os.Getenv("AGENTS_GRPC_TARGET") + if cfg.AgentsGRPCTarget == "" { + cfg.AgentsGRPCTarget = "agents:50051" + } + cfg.LLMGRPCTarget = os.Getenv("LLM_GRPC_TARGET") + if cfg.LLMGRPCTarget == "" { + cfg.LLMGRPCTarget = "llm:50051" + } cfg.NATSURL = os.Getenv("NATS_URL") if cfg.NATSURL == "" { cfg.NATSURL = "nats://nats:4222" diff --git a/internal/schema/compatibility.go b/internal/schema/compatibility.go new file mode 100644 index 0000000..bb5a687 --- /dev/null +++ b/internal/schema/compatibility.go @@ -0,0 +1,145 @@ +package schema + +import "fmt" + +// CarriedCount reports how many installations of the app hold a value for a +// configuration key. A deprecated property may be removed only once nothing +// carries it, which is a question only the Apps Service can answer because it +// spans organizations the reporting app cannot see. +type CarriedCount func(key string) (int, error) + +// CheckCompatible reports whether s still accepts every configuration prev +// accepted. A schema is a contract with configuration that already exists in +// organizations the app's author cannot reach and cannot migrate, so narrowing +// it is refused rather than discovered one organization at a time. +func (s *Schema) CheckCompatible(prev *Schema, carried CarriedCount) error { + if prev == nil { + return nil // first report: nothing to be compatible with + } + + for _, name := range prev.Names { + before := prev.Properties[name] + after, kept := s.Properties[name] + if !kept { + if !before.Deprecated { + return fmt.Errorf("property %q was removed; mark it deprecated instead", name) + } + n, err := carried(name) + if err != nil { + return fmt.Errorf("property %q: cannot check whether installations still carry it: %w", name, err) + } + if n > 0 { + return fmt.Errorf("deprecated property %q cannot be removed: %d installation(s) still carry it", name, n) + } + continue + } + if err := compareProperty(before, after); err != nil { + return err + } + } + + for _, name := range s.Required { + if _, existed := prev.Properties[name]; !existed { + continue // a brand new property may be required; nothing stored lacks it + } + if !prev.isRequired(name) { + return fmt.Errorf("property %q became required; configurations written without it would stop validating", name) + } + } + return nil +} + +func compareProperty(before, after *Property) error { + name := before.Name + if before.Type != after.Type { + return fmt.Errorf("property %q changed type from %s to %s; add a new property and deprecate this one", name, before.Type, after.Type) + } + if before.ItemsType != after.ItemsType { + return fmt.Errorf("property %q changed its item type from %s to %s", name, before.ItemsType, after.ItemsType) + } + if before.Ref != after.Ref && after.Ref != "" { + if before.Ref == "" { + return fmt.Errorf("property %q gained x-agyn-ref %q; values that name nothing would stop validating", name, after.Ref) + } + return fmt.Errorf("property %q changed x-agyn-ref from %q to %q", name, before.Ref, after.Ref) + } + if err := compareEnum(before, after); err != nil { + return err + } + if before.Pattern != after.Pattern && after.Pattern != "" { + return fmt.Errorf("property %q narrowed its pattern", name) + } + if before.Format != after.Format && after.Format != "" && !isDisplayFormat(after.Format) { + return fmt.Errorf("property %q narrowed its format to %q", name, after.Format) + } + if err := compareBound(name, "minLength", before.MinLength, after.MinLength, true); err != nil { + return err + } + if err := compareBound(name, "maxLength", before.MaxLength, after.MaxLength, false); err != nil { + return err + } + if err := compareBound(name, "minItems", before.MinItems, after.MinItems, true); err != nil { + return err + } + if err := compareBound(name, "maxItems", before.MaxItems, after.MaxItems, false); err != nil { + return err + } + if err := compareFloatBound(name, "minimum", before.Minimum, after.Minimum, true); err != nil { + return err + } + return compareFloatBound(name, "maximum", before.Maximum, after.Maximum, false) +} + +func compareEnum(before, after *Property) error { + if len(after.Enum) == 0 { + return nil // dropping an enum widens + } + if len(before.Enum) == 0 { + return fmt.Errorf("property %q gained an enum; values outside it would stop validating", before.Name) + } + allowed := make(map[any]struct{}, len(after.Enum)) + for _, v := range after.Enum { + allowed[v] = struct{}{} + } + for _, v := range before.Enum { + if _, ok := allowed[v]; !ok { + return fmt.Errorf("property %q dropped enum value %v", before.Name, v) + } + } + return nil +} + +// compareBound rejects a narrowed integer bound. A lower bound narrows by +// rising or by appearing; an upper bound narrows by falling or by appearing. +func compareBound(name, key string, before, after *int, lower bool) error { + if after == nil { + return nil + } + if before == nil { + return fmt.Errorf("property %q gained %s", name, key) + } + if (lower && *after > *before) || (!lower && *after < *before) { + return fmt.Errorf("property %q narrowed %s from %d to %d", name, key, *before, *after) + } + return nil +} + +func compareFloatBound(name, key string, before, after *float64, lower bool) error { + if after == nil { + return nil + } + if before == nil { + return fmt.Errorf("property %q gained %s", name, key) + } + if (lower && *after > *before) || (!lower && *after < *before) { + return fmt.Errorf("property %q narrowed %s from %v to %v", name, key, *before, *after) + } + return nil +} + +// isDisplayFormat reports whether a format only changes how a client draws the +// field. Gaining one narrows nothing, so it is an ordinary compatible change. +func isDisplayFormat(format string) bool { + _, ok := displayFormats[format] + return ok +} diff --git a/internal/schema/configuration.go b/internal/schema/configuration.go new file mode 100644 index 0000000..ebaa705 --- /dev/null +++ b/internal/schema/configuration.go @@ -0,0 +1,160 @@ +package schema + +import ( + "fmt" + "math" + "net/mail" + "net/url" + "sort" + "strings" + + "github.com/google/uuid" +) + +// PropertyError is one failure, named by the property it belongs to so the +// Console can attach it to that input rather than showing one message for the +// whole form. +type PropertyError struct { + Property string + Message string +} + +func (e PropertyError) Error() string { return e.Property + ": " + e.Message } + +// ValidationError carries every property that failed. +type ValidationError struct { + Errors []PropertyError +} + +func (e *ValidationError) Error() string { + parts := make([]string, 0, len(e.Errors)) + for _, err := range e.Errors { + parts = append(parts, err.Error()) + } + return "invalid configuration: " + strings.Join(parts, "; ") +} + +// ValidateConfiguration checks a submitted configuration against the schema. +// Deprecated properties are still validated when present: they stay valid so +// that an admin editing an unrelated field is not blocked by one the app has +// stopped wanting. +func (s *Schema) ValidateConfiguration(config map[string]any) error { + var errs []PropertyError + + var undeclared []string + for key := range config { + if _, ok := s.Properties[key]; !ok { + undeclared = append(undeclared, key) + } + } + sort.Strings(undeclared) + for _, key := range undeclared { + errs = append(errs, PropertyError{Property: key, Message: "not declared by the app"}) + } + + for _, name := range s.Required { + if v, ok := config[name]; !ok || v == nil { + errs = append(errs, PropertyError{Property: name, Message: "is required"}) + } + } + + for _, name := range s.Names { + value, ok := config[name] + if !ok || value == nil { + continue + } + if err := s.Properties[name].validate(value); err != nil { + errs = append(errs, PropertyError{Property: name, Message: err.Error()}) + } + } + + if len(errs) == 0 { + return nil + } + sort.SliceStable(errs, func(i, j int) bool { return errs[i].Property < errs[j].Property }) + return &ValidationError{Errors: errs} +} + +func (p *Property) validate(value any) error { + if !valueMatchesType(value, p.Type) { + return fmt.Errorf("must be %s", p.Type) + } + if len(p.Enum) > 0 && !containsValue(p.Enum, value) { + return fmt.Errorf("must be one of %v", p.Enum) + } + + switch p.Type { + case TypeString: + s := value.(string) + if p.MinLength != nil && len(s) < *p.MinLength { + return fmt.Errorf("must be at least %d characters", *p.MinLength) + } + if p.MaxLength != nil && len(s) > *p.MaxLength { + return fmt.Errorf("must be at most %d characters", *p.MaxLength) + } + if p.pattern != nil && !p.pattern.MatchString(s) { + return fmt.Errorf("must match %s", p.Pattern) + } + if err := checkFormat(p.Format, s); err != nil { + return err + } + case TypeInteger, TypeNumber: + f, _ := toFloat(value) + if p.Minimum != nil && f < *p.Minimum { + return fmt.Errorf("must be at least %v", *p.Minimum) + } + if p.Maximum != nil && f > *p.Maximum { + return fmt.Errorf("must be at most %v", *p.Maximum) + } + case TypeArray: + items := value.([]any) + if p.MinItems != nil && len(items) < *p.MinItems { + return fmt.Errorf("must have at least %d items", *p.MinItems) + } + if p.MaxItems != nil && len(items) > *p.MaxItems { + return fmt.Errorf("must have at most %d items", *p.MaxItems) + } + for i, item := range items { + if _, ok := item.(string); !ok { + return fmt.Errorf("item %d must be a string", i) + } + } + } + return nil +} + +func checkFormat(format, value string) error { + switch format { + case "", "password": + // password says how to draw the field, not what the value must be. + return nil + case "uuid": + if _, err := uuid.Parse(value); err != nil { + return fmt.Errorf("must be a UUID") + } + case "email": + if _, err := mail.ParseAddress(value); err != nil { + return fmt.Errorf("must be an email address") + } + case "uri": + u, err := url.Parse(value) + if err != nil || u.Scheme == "" { + return fmt.Errorf("must be an absolute URI") + } + } + return nil +} + +func containsValue(list []any, value any) bool { + for _, item := range list { + if item == value { + return true + } + a, aok := toFloat(item) + b, bok := toFloat(value) + if aok && bok && math.Abs(a-b) == 0 { + return true + } + } + return false +} diff --git a/internal/schema/schema.go b/internal/schema/schema.go new file mode 100644 index 0000000..680851e --- /dev/null +++ b/internal/schema/schema.go @@ -0,0 +1,353 @@ +// Package schema implements the configuration schema an app reports for its +// installations: parsing the honored subset of JSON Schema, checking that a +// newly reported schema still accepts what the previous one accepted, and +// validating an installation configuration against it. +package schema + +import ( + "fmt" + "math" + "regexp" + "sort" +) + +// Type is a property type in the honored subset. +type Type string + +const ( + TypeString Type = "string" + TypeInteger Type = "integer" + TypeNumber Type = "number" + TypeBoolean Type = "boolean" + TypeArray Type = "array" +) + +// Ref kinds are a closed vocabulary: each costs a picker in the Console and an +// existence check against the owning service. +const ( + RefAgent = "agent" + RefEnvironment = "environment" + RefModel = "model" +) + +var ( + validTypes = map[Type]struct{}{TypeString: {}, TypeInteger: {}, TypeNumber: {}, TypeBoolean: {}, TypeArray: {}} + validRefs = map[string]struct{}{RefAgent: {}, RefEnvironment: {}, RefModel: {}} + // password is a display hint — obscure the input — and validates nothing. + // The others constrain the value. + validFormats = map[string]struct{}{"uri": {}, "email": {}, "uuid": {}, "password": {}} + displayFormats = map[string]struct{}{"password": {}} + + // Reserved for the Secrets integration, where a property will name a + // Secret instead of carrying a value. Rejected rather than ignored so no + // app adopts it meaning something weaker in the meantime. + reservedKeywords = map[string]string{ + "x-agyn-secret": "reserved for a future Secrets integration; use \"format\": \"password\" to mask the field", + } + + rootKeywords = map[string]struct{}{ + "type": {}, "properties": {}, "required": {}, "additionalProperties": {}, + "title": {}, "description": {}, "$schema": {}, + } + propKeywords = map[string]struct{}{ + "type": {}, "title": {}, "description": {}, "default": {}, "deprecated": {}, + "enum": {}, "pattern": {}, "format": {}, "minLength": {}, "maxLength": {}, + "minimum": {}, "maximum": {}, "minItems": {}, "maxItems": {}, "items": {}, + "x-agyn-ref": {}, + } +) + +// Property is one entry in the schema's flat properties map. +type Property struct { + Name string + Type Type + ItemsType Type // set when Type is TypeArray + Title string + Description string + Default any + Deprecated bool + Enum []any + Pattern string + Format string + MinLength *int + MaxLength *int + Minimum *float64 + Maximum *float64 + MinItems *int + MaxItems *int + Ref string + + pattern *regexp.Regexp +} + +// Schema is a parsed configuration schema. +type Schema struct { + Properties map[string]*Property + Names []string // declaration order, for stable messages + Required []string +} + +// Parse validates a reported document against the honored subset and returns +// it parsed. Every rejection names the keyword or property at fault: the app +// author is the one who can fix it, and they only see this message. +func Parse(doc map[string]any) (*Schema, error) { + if doc == nil { + return nil, fmt.Errorf("schema must be an object") + } + for k := range doc { + if _, ok := rootKeywords[k]; !ok { + return nil, fmt.Errorf("unsupported keyword %q at the root of the schema", k) + } + } + if t, ok := doc["type"]; ok { + if s, _ := t.(string); s != "object" { + return nil, fmt.Errorf(`root "type" must be "object"`) + } + } + if ap, ok := doc["additionalProperties"]; ok { + if b, _ := ap.(bool); b { + return nil, fmt.Errorf(`root "additionalProperties" must be false`) + } + } + + s := &Schema{Properties: map[string]*Property{}} + + rawProps, _ := doc["properties"].(map[string]any) + if doc["properties"] != nil && rawProps == nil { + return nil, fmt.Errorf(`"properties" must be an object`) + } + for name := range rawProps { + s.Names = append(s.Names, name) + } + sort.Strings(s.Names) + for _, name := range s.Names { + raw, ok := rawProps[name].(map[string]any) + if !ok { + return nil, fmt.Errorf("property %q must be an object", name) + } + p, err := parseProperty(name, raw) + if err != nil { + return nil, err + } + s.Properties[name] = p + } + + if req, ok := doc["required"]; ok { + list, ok := req.([]any) + if !ok { + return nil, fmt.Errorf(`"required" must be an array`) + } + for _, item := range list { + name, ok := item.(string) + if !ok { + return nil, fmt.Errorf(`"required" must contain strings`) + } + if _, ok := s.Properties[name]; !ok { + return nil, fmt.Errorf("required property %q is not declared", name) + } + s.Required = append(s.Required, name) + } + sort.Strings(s.Required) + } + return s, nil +} + +func parseProperty(name string, raw map[string]any) (*Property, error) { + for k := range raw { + if reason, reserved := reservedKeywords[k]; reserved { + return nil, fmt.Errorf("property %q uses %q, which is %s", name, k, reason) + } + if _, ok := propKeywords[k]; !ok { + return nil, fmt.Errorf("property %q uses unsupported keyword %q", name, k) + } + } + + typeStr, _ := raw["type"].(string) + if typeStr == "" { + return nil, fmt.Errorf("property %q must declare a type", name) + } + p := &Property{Name: name, Type: Type(typeStr)} + if _, ok := validTypes[p.Type]; !ok { + return nil, fmt.Errorf("property %q has unsupported type %q", name, typeStr) + } + + if p.Type == TypeArray { + items, ok := raw["items"].(map[string]any) + if !ok { + return nil, fmt.Errorf("property %q must declare items", name) + } + if it, _ := items["type"].(string); it != string(TypeString) { + return nil, fmt.Errorf("property %q must declare items of type string", name) + } + p.ItemsType = TypeString + } else if _, ok := raw["items"]; ok { + return nil, fmt.Errorf("property %q declares items but is not an array", name) + } + + p.Title, _ = raw["title"].(string) + p.Description, _ = raw["description"].(string) + p.Default = raw["default"] + p.Deprecated, _ = raw["deprecated"].(bool) + + if v, ok := raw["x-agyn-ref"]; ok { + ref, ok := v.(string) + if !ok { + return nil, fmt.Errorf("property %q: x-agyn-ref must be a string", name) + } + if _, ok := validRefs[ref]; !ok { + return nil, fmt.Errorf("property %q: unknown x-agyn-ref kind %q", name, ref) + } + if p.Type != TypeString { + return nil, fmt.Errorf("property %q: x-agyn-ref applies to string properties only", name) + } + p.Ref = ref + } + + if v, ok := raw["enum"]; ok { + list, ok := v.([]any) + if !ok || len(list) == 0 { + return nil, fmt.Errorf("property %q: enum must be a non-empty array", name) + } + for _, item := range list { + if !valueMatchesType(item, p.Type) { + return nil, fmt.Errorf("property %q: enum value %v does not match type %s", name, item, p.Type) + } + } + p.Enum = list + } + if v, ok := raw["pattern"]; ok { + pat, ok := v.(string) + if !ok { + return nil, fmt.Errorf("property %q: pattern must be a string", name) + } + if p.Type != TypeString { + return nil, fmt.Errorf("property %q: pattern applies to string properties only", name) + } + re, err := regexp.Compile(pat) + if err != nil { + return nil, fmt.Errorf("property %q: pattern does not compile: %w", name, err) + } + p.Pattern, p.pattern = pat, re + } + if v, ok := raw["format"]; ok { + f, ok := v.(string) + if !ok { + return nil, fmt.Errorf("property %q: format must be a string", name) + } + if _, ok := validFormats[f]; !ok { + return nil, fmt.Errorf("property %q: unsupported format %q", name, f) + } + if p.Type != TypeString { + return nil, fmt.Errorf("property %q: format applies to string properties only", name) + } + p.Format = f + } + + var err error + if p.MinLength, err = intKeyword(raw, "minLength", name, p.Type, TypeString); err != nil { + return nil, err + } + if p.MaxLength, err = intKeyword(raw, "maxLength", name, p.Type, TypeString); err != nil { + return nil, err + } + if p.MinItems, err = intKeyword(raw, "minItems", name, p.Type, TypeArray); err != nil { + return nil, err + } + if p.MaxItems, err = intKeyword(raw, "maxItems", name, p.Type, TypeArray); err != nil { + return nil, err + } + if p.Minimum, err = numKeyword(raw, "minimum", name, p.Type); err != nil { + return nil, err + } + if p.Maximum, err = numKeyword(raw, "maximum", name, p.Type); err != nil { + return nil, err + } + return p, nil +} + +func intKeyword(raw map[string]any, key, name string, actual, want Type) (*int, error) { + v, ok := raw[key] + if !ok { + return nil, nil + } + if actual != want { + return nil, fmt.Errorf("property %q: %s applies to %s properties only", name, key, want) + } + f, ok := toFloat(v) + if !ok || f < 0 || f != math.Trunc(f) { + return nil, fmt.Errorf("property %q: %s must be a non-negative integer", name, key) + } + i := int(f) + return &i, nil +} + +func numKeyword(raw map[string]any, key, name string, actual Type) (*float64, error) { + v, ok := raw[key] + if !ok { + return nil, nil + } + if actual != TypeInteger && actual != TypeNumber { + return nil, fmt.Errorf("property %q: %s applies to numeric properties only", name, key) + } + f, ok := toFloat(v) + if !ok { + return nil, fmt.Errorf("property %q: %s must be a number", name, key) + } + return &f, nil +} + +func toFloat(v any) (float64, bool) { + switch n := v.(type) { + case float64: + return n, true + case float32: + return float64(n), true + case int: + return float64(n), true + case int64: + return float64(n), true + default: + return 0, false + } +} + +func valueMatchesType(v any, t Type) bool { + switch t { + case TypeString: + _, ok := v.(string) + return ok + case TypeBoolean: + _, ok := v.(bool) + return ok + case TypeNumber: + _, ok := toFloat(v) + return ok + case TypeInteger: + f, ok := toFloat(v) + return ok && f == math.Trunc(f) + case TypeArray: + _, ok := v.([]any) + return ok + } + return false +} + +// Refs returns the properties carrying an x-agyn-ref, in declaration order. +func (s *Schema) Refs() []*Property { + var out []*Property + for _, name := range s.Names { + if p := s.Properties[name]; p.Ref != "" { + out = append(out, p) + } + } + return out +} + +func (s *Schema) isRequired(name string) bool { + for _, r := range s.Required { + if r == name { + return true + } + } + return false +} diff --git a/internal/schema/schema_test.go b/internal/schema/schema_test.go new file mode 100644 index 0000000..3307432 --- /dev/null +++ b/internal/schema/schema_test.go @@ -0,0 +1,230 @@ +package schema + +import ( + "encoding/json" + "strings" + "testing" +) + +func mustParse(t *testing.T, doc string) *Schema { + t.Helper() + s, err := parse(t, doc) + if err != nil { + t.Fatalf("Parse(%s) returned %v", doc, err) + } + return s +} + +func parse(t *testing.T, doc string) (*Schema, error) { + t.Helper() + var raw map[string]any + if err := json.Unmarshal([]byte(doc), &raw); err != nil { + t.Fatalf("test document is not JSON: %v", err) + } + return Parse(raw) +} + +func config(t *testing.T, doc string) map[string]any { + t.Helper() + var raw map[string]any + if err := json.Unmarshal([]byte(doc), &raw); err != nil { + t.Fatalf("test configuration is not JSON: %v", err) + } + return raw +} + +const telegram = `{ + "type": "object", + "properties": { + "bot_token": {"type": "string", "title": "Bot token", "format": "password"}, + "agent_id": {"type": "string", "format": "uuid", "x-agyn-ref": "agent"} + }, + "required": ["bot_token", "agent_id"] +}` + +func TestParseRejectsOutsideTheHonoredSubset(t *testing.T) { + cases := map[string]string{ + "nested object": `{"type":"object","properties":{"a":{"type":"object"}}}`, + "oneOf": `{"type":"object","oneOf":[]}`, + "ref": `{"type":"object","properties":{"a":{"$ref":"#/x"}}}`, + "tuple items": `{"type":"object","properties":{"a":{"type":"array","items":[{"type":"string"}]}}}`, + "array of number": `{"type":"object","properties":{"a":{"type":"array","items":{"type":"number"}}}}`, + "non-object root": `{"type":"array"}`, + "open root": `{"type":"object","additionalProperties":true}`, + "unknown type": `{"type":"object","properties":{"a":{"type":"null"}}}`, + "reserved keyword": `{"type":"object","properties":{"a":{"type":"string","x-agyn-secret":true}}}`, + "unknown ref": `{"type":"object","properties":{"a":{"type":"string","x-agyn-ref":"sandbox"}}}`, + "bad pattern": `{"type":"object","properties":{"a":{"type":"string","pattern":"["}}}`, + "undeclared req": `{"type":"object","properties":{},"required":["a"]}`, + } + for name, doc := range cases { + t.Run(name, func(t *testing.T) { + if _, err := parse(t, doc); err == nil { + t.Fatalf("Parse accepted %s", name) + } + }) + } +} + +func TestParseAcceptsTheTelegramSchema(t *testing.T) { + s := mustParse(t, telegram) + if s.Properties["bot_token"].Format != "password" { + t.Fatal("bot_token should be a password-formatted field") + } + refs := s.Refs() + if len(refs) != 1 || refs[0].Ref != RefAgent { + t.Fatalf("Refs() = %v, want one agent reference", refs) + } +} + +func TestValidateConfiguration(t *testing.T) { + s := mustParse(t, `{ + "type": "object", + "properties": { + "url": {"type": "string", "format": "uri"}, + "port": {"type": "integer", "minimum": 1, "maximum": 65535}, + "mode": {"type": "string", "enum": ["a", "b"]}, + "tags": {"type": "array", "items": {"type": "string"}, "maxItems": 2}, + "on": {"type": "boolean"} + }, + "required": ["url"] + }`) + + if err := s.ValidateConfiguration(config(t, `{"url":"https://x.test","port":8080,"mode":"a","tags":["x"],"on":true}`)); err != nil { + t.Fatalf("valid configuration rejected: %v", err) + } + + err := s.ValidateConfiguration(config(t, `{"port":70000,"mode":"c","tags":["a","b","c"],"nope":1}`)) + if err == nil { + t.Fatal("invalid configuration accepted") + } + var v *ValidationError + if !asValidationError(err, &v) { + t.Fatalf("error is not a ValidationError: %v", err) + } + got := map[string]bool{} + for _, e := range v.Errors { + got[e.Property] = true + } + for _, want := range []string{"url", "port", "mode", "tags", "nope"} { + if !got[want] { + t.Errorf("missing error for %q; got %v", want, v.Errors) + } + } +} + +func TestValidateConfigurationKeepsDeprecatedPropertiesValid(t *testing.T) { + s := mustParse(t, `{"type":"object","properties":{"old":{"type":"string","deprecated":true}}}`) + if err := s.ValidateConfiguration(config(t, `{"old":"still here"}`)); err != nil { + t.Fatalf("deprecated property rejected: %v", err) + } + if err := s.ValidateConfiguration(config(t, `{"old":7}`)); err == nil { + t.Fatal("deprecated property skipped type checking") + } +} + +func asValidationError(err error, target **ValidationError) bool { + v, ok := err.(*ValidationError) + if ok { + *target = v + } + return ok +} + +func never(string) (int, error) { return 0, nil } + +func TestCheckCompatibleAllowsWidening(t *testing.T) { + prev := mustParse(t, `{ + "type":"object", + "properties":{ + "a":{"type":"string","minLength":5,"pattern":"^x","enum":["xa","xb"]}, + "b":{"type":"integer","minimum":10} + }, + "required":["a","b"] + }`) + next := mustParse(t, `{ + "type":"object", + "properties":{ + "a":{"type":"string","minLength":2,"enum":["xa","xb","xc"]}, + "b":{"type":"integer","minimum":1}, + "c":{"type":"string","title":"new and optional"}, + "d":{"type":"string","format":"password"} + }, + "required":["a","b","d"] + }`) + if err := next.CheckCompatible(prev, never); err != nil { + t.Fatalf("widening rejected: %v", err) + } +} + +func TestCheckCompatibleRejectsNarrowing(t *testing.T) { + base := `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string"}},"required":["a"]}` + cases := map[string]string{ + "removal": `{"type":"object","properties":{"a":{"type":"string"}},"required":["a"]}`, + "type change": `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"integer"}},"required":["a"]}`, + "newly required": `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string"}},"required":["a","b"]}`, + "gained pattern": `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string","pattern":"^x"}},"required":["a"]}`, + "gained enum": `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string","enum":["x"]}},"required":["a"]}`, + "gained min": `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string","minLength":3}},"required":["a"]}`, + "gained ref": `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string","x-agyn-ref":"agent"}},"required":["a"]}`, + "gained format": `{"type":"object","properties":{"a":{"type":"string"},"b":{"type":"string","format":"uuid"}},"required":["a"]}`, + } + prev := mustParse(t, base) + for name, doc := range cases { + t.Run(name, func(t *testing.T) { + if err := mustParse(t, doc).CheckCompatible(prev, never); err == nil { + t.Fatalf("accepted a narrowing change: %s", name) + } + }) + } +} + +// A display format narrows nothing, so gaining one is compatible — unlike +// gaining uuid or email, which start rejecting values that used to validate. +func TestCheckCompatibleAllowsGainingADisplayFormat(t *testing.T) { + prev := mustParse(t, `{"type":"object","properties":{"t":{"type":"string"}}}`) + next := mustParse(t, `{"type":"object","properties":{"t":{"type":"string","format":"password"}}}`) + if err := next.CheckCompatible(prev, never); err != nil { + t.Fatalf("gaining format password rejected: %v", err) + } + + constrained := mustParse(t, `{"type":"object","properties":{"t":{"type":"string","format":"uuid"}}}`) + if err := constrained.CheckCompatible(prev, never); err == nil { + t.Fatal("gaining a validating format was accepted") + } +} + +// The keyword is reserved for the Secrets integration. Rejecting it now keeps +// apps from adopting it to mean something weaker in the meantime. +func TestParseRejectsReservedSecretKeyword(t *testing.T) { + _, err := parse(t, `{"type":"object","properties":{"t":{"type":"string","x-agyn-secret":true}}}`) + if err == nil { + t.Fatal("x-agyn-secret was accepted") + } + if !strings.Contains(err.Error(), "reserved") || !strings.Contains(err.Error(), "password") { + t.Fatalf("error should say it is reserved and point at the alternative: %v", err) + } +} + +func TestDeprecatedPropertyRemovableOnlyWhenNothingCarriesIt(t *testing.T) { + prev := mustParse(t, `{"type":"object","properties":{"old":{"type":"string","deprecated":true}}}`) + next := mustParse(t, `{"type":"object","properties":{}}`) + + if err := next.CheckCompatible(prev, func(string) (int, error) { return 0, nil }); err != nil { + t.Fatalf("removal of an uncarried deprecated property rejected: %v", err) + } + + err := next.CheckCompatible(prev, func(string) (int, error) { return 3, nil }) + if err == nil { + t.Fatal("removed a deprecated property three installations still carry") + } + if !strings.Contains(err.Error(), "3 installation") { + t.Fatalf("error does not name the count: %v", err) + } +} + +func TestCheckCompatibleFirstReport(t *testing.T) { + if err := mustParse(t, telegram).CheckCompatible(nil, never); err != nil { + t.Fatalf("first report rejected: %v", err) + } +} diff --git a/internal/server/configuration.go b/internal/server/configuration.go new file mode 100644 index 0000000..60c5dbc --- /dev/null +++ b/internal/server/configuration.go @@ -0,0 +1,185 @@ +package server + +import ( + "context" + "errors" + "fmt" + "log" + + appsv1 "github.com/agynio/apps/.gen/go/agynio/api/apps/v1" + "github.com/agynio/apps/internal/schema" + "github.com/agynio/apps/internal/store" + "github.com/google/uuid" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// ReferenceResolver answers whether the entity an x-agyn-ref property names +// exists in the installing organization. Each kind is owned by another service, +// so this is the Apps Service's only outbound call on an installation write. +type ReferenceResolver interface { + ResolveExists(ctx context.Context, kind string, id uuid.UUID, organizationID uuid.UUID) (bool, error) +} + +// appSchema parses the schema the app reported, or returns nil when it has +// reported none. +// +// A stored schema that no longer parses is treated as absent rather than as an +// error. It was valid against the honored subset when it was written, so the +// subset has since tightened — and refusing to read it would strand the app: +// every report would be rejected for the state of the schema it is trying to +// replace, and every installation write would fail against a schema nobody can +// evaluate. The compatibility guarantee lapses for that one transition, which +// is the cost of ever narrowing the subset. +func appSchema(app store.App) (*schema.Schema, error) { + if app.ConfigurationSchema == nil { + return nil, nil + } + parsed, err := schema.Parse(app.ConfigurationSchema) + if err != nil { + log.Printf("WARN: stored configuration schema for app %s is no longer expressible, treating as absent: %v", app.Meta.ID, err) + return nil, nil + } + return parsed, nil +} + +func (s *Server) installationSchema(ctx context.Context, appID uuid.UUID) (*schema.Schema, error) { + app, err := s.store.GetApp(ctx, appID) + if err != nil { + return nil, toStatusError(err) + } + return appSchema(app) +} + +// validateConfiguration checks a submitted configuration against the app's +// schema and resolves every reference it carries. An app that has reported no +// schema is not validated — its configuration is stored as submitted. +func (s *Server) validateConfiguration( + ctx context.Context, + appSchema *schema.Schema, + configuration map[string]any, + organizationID uuid.UUID, +) error { + if appSchema == nil { + return nil + } + if err := appSchema.ValidateConfiguration(configuration); err != nil { + var invalid *schema.ValidationError + if errors.As(err, &invalid) { + return propertyErrors(invalid) + } + return status.Errorf(codes.InvalidArgument, "configuration: %v", err) + } + return s.resolveReferences(ctx, appSchema, configuration, organizationID) +} + +func (s *Server) resolveReferences( + ctx context.Context, + appSchema *schema.Schema, + configuration map[string]any, + organizationID uuid.UUID, +) error { + for _, property := range appSchema.Refs() { + raw, ok := configuration[property.Name] + if !ok || raw == nil { + continue + } + value, _ := raw.(string) + id, err := uuid.Parse(value) + if err != nil { + return propertyError(property.Name, "must be a UUID") + } + if s.references == nil { + // An unvalidated reference is one the app discovers is wrong at + // runtime, where there is no form to correct it. + return status.Errorf(codes.Unavailable, + "cannot validate %s reference on %q: no resolver configured", property.Ref, property.Name) + } + exists, err := s.references.ResolveExists(ctx, property.Ref, id, organizationID) + if err != nil { + return status.Errorf(codes.Unavailable, + "cannot validate %s reference on %q: %v", property.Ref, property.Name, err) + } + if !exists { + // A UUID naming an entity in another organization fails exactly as + // a nonexistent one does: the difference is not something the + // installing admin is entitled to learn. + return propertyError(property.Name, fmt.Sprintf("no such %s in this organization", property.Ref)) + } + } + return nil +} + +func propertyError(property, message string) error { + return propertyErrors(&schema.ValidationError{ + Errors: []schema.PropertyError{{Property: property, Message: message}}, + }) +} + +// propertyErrors reports each failure against the property it belongs to, so +// the Console can attach it to that input instead of showing one message for +// the whole form. +func propertyErrors(invalid *schema.ValidationError) error { + st := status.New(codes.InvalidArgument, invalid.Error()) + violations := make([]*appsv1.ConfigurationPropertyError, 0, len(invalid.Errors)) + for _, e := range invalid.Errors { + violations = append(violations, &appsv1.ConfigurationPropertyError{ + Property: e.Property, + Message: e.Message, + }) + } + detailed, err := st.WithDetails(&appsv1.ConfigurationValidationFailure{Errors: violations}) + if err != nil { + return st.Err() + } + return detailed.Err() +} + +// ReportConfigurationSchema replaces the app's stored schema with the reported +// document. The app reports its own schema because the schema is a property of +// the deployed binary: a copy held anywhere else goes stale on the next deploy. +func (s *Server) ReportConfigurationSchema(ctx context.Context, req *appsv1.ReportConfigurationSchemaRequest) (*appsv1.ReportConfigurationSchemaResponse, error) { + callerID, err := identityFromMetadata(ctx) + if err != nil { + return nil, status.Errorf(codes.Unauthenticated, "unauthenticated: %v", err) + } + appID, err := parseUUID(req.GetAppId()) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "app_id: %v", err) + } + app, err := s.store.GetApp(ctx, appID) + if err != nil { + return nil, toStatusError(err) + } + if app.IdentityID != callerID { + return nil, status.Error(codes.PermissionDenied, "an app may only report its own configuration schema") + } + + document := protoStructToMap(req.GetConfigurationSchema()) + if document == nil { + return nil, status.Error(codes.InvalidArgument, "configuration_schema must be provided") + } + next, err := schema.Parse(document) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "configuration_schema: %v", err) + } + + previous, err := appSchema(app) + if err != nil { + return nil, err + } + carried := func(key string) (int, error) { + return s.store.CountInstallationsWithConfigurationKey(ctx, appID, key) + } + if err := next.CheckCompatible(previous, carried); err != nil { + // The report is the unit: the previous schema stands whole, including + // the compatible changes in the same document. + return nil, status.Errorf(codes.FailedPrecondition, "configuration_schema: %v", err) + } + + updated, err := s.store.SetAppConfigurationSchema(ctx, appID, document) + if err != nil { + return nil, toStatusError(err) + } + return &appsv1.ReportConfigurationSchemaResponse{App: toProtoApp(updated)}, nil +} diff --git a/internal/server/configuration_test.go b/internal/server/configuration_test.go new file mode 100644 index 0000000..c92b73d --- /dev/null +++ b/internal/server/configuration_test.go @@ -0,0 +1,264 @@ +package server + +import ( + "context" + "encoding/json" + "strings" + "testing" + + appsv1 "github.com/agynio/apps/.gen/go/agynio/api/apps/v1" + authorizationv1 "github.com/agynio/apps/.gen/go/agynio/api/authorization/v1" + "github.com/agynio/apps/internal/schema" + storepkg "github.com/agynio/apps/internal/store" + "github.com/google/uuid" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" +) + +func jsonMap(t *testing.T, doc string) map[string]any { + t.Helper() + var raw map[string]any + if err := json.Unmarshal([]byte(doc), &raw); err != nil { + t.Fatalf("test document is not JSON: %v", err) + } + return raw +} + +func jsonStruct(t *testing.T, doc string) *structpb.Struct { + t.Helper() + value, err := structpb.NewStruct(jsonMap(t, doc)) + if err != nil { + t.Fatalf("structpb.NewStruct: %v", err) + } + return value +} + +const maskedSchema = `{ + "type": "object", + "properties": { + "bot_token": {"type": "string", "format": "password"}, + "channel": {"type": "string"} + }, + "required": ["bot_token"] +}` + +// reportingApp wires a fake store where the app identity in ctx owns the app. +func reportingApp(t *testing.T, schemaDoc string) (*fakeStore, uuid.UUID, uuid.UUID, context.Context) { + t.Helper() + ctx, identityID := newAdminContext() + appID := uuid.New() + store := &fakeStore{} + var stored map[string]any + if schemaDoc != "" { + stored = jsonMap(t, schemaDoc) + } + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{ + Meta: storepkg.EntityMeta{ID: id}, + IdentityID: identityID, + ConfigurationSchema: stored, + }, nil + } + store.setConfigurationSchemaFn = func(_ context.Context, id uuid.UUID, doc map[string]any) (storepkg.App, error) { + return storepkg.App{ + Meta: storepkg.EntityMeta{ID: id}, + Visibility: storepkg.AppVisibilityInternal, + ConfigurationSchema: doc, + }, nil + } + return store, appID, identityID, ctx +} + +func newServer(store *fakeStore) *Server { + return New(store, &fakeIdentityClient{}, &fakeAuthorizationClient{}, &fakeZitiManagementClient{}) +} + +func TestReportConfigurationSchemaStoresFirstReport(t *testing.T) { + store, appID, _, ctx := reportingApp(t, "") + srv := newServer(store) + + _, err := srv.ReportConfigurationSchema(ctx, &appsv1.ReportConfigurationSchemaRequest{ + AppId: appID.String(), + ConfigurationSchema: jsonStruct(t, maskedSchema), + }) + if err != nil { + t.Fatalf("first report rejected: %v", err) + } + if len(store.setConfigurationSchemaCalls) != 1 { + t.Fatalf("schema not stored: %v", store.setConfigurationSchemaCalls) + } +} + +func TestReportConfigurationSchemaRejectsOutsideSubset(t *testing.T) { + store, appID, _, ctx := reportingApp(t, "") + srv := newServer(store) + + _, err := srv.ReportConfigurationSchema(ctx, &appsv1.ReportConfigurationSchemaRequest{ + AppId: appID.String(), + ConfigurationSchema: jsonStruct(t, `{"type":"object","properties":{"a":{"type":"object"}}}`), + }) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("want InvalidArgument, got %v", err) + } + if len(store.setConfigurationSchemaCalls) != 0 { + t.Fatal("a rejected schema was stored") + } +} + +func TestReportConfigurationSchemaRejectsIncompatibleAndKeepsPrevious(t *testing.T) { + store, appID, _, ctx := reportingApp(t, maskedSchema) + srv := newServer(store) + + // Drops bot_token and adds a compatible property in the same document. + _, err := srv.ReportConfigurationSchema(ctx, &appsv1.ReportConfigurationSchemaRequest{ + AppId: appID.String(), + ConfigurationSchema: jsonStruct(t, `{ + "type":"object", + "properties":{"channel":{"type":"string"},"extra":{"type":"string"}} + }`), + }) + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("want FailedPrecondition, got %v", err) + } + if len(store.setConfigurationSchemaCalls) != 0 { + t.Fatal("the compatible half of a rejected report was stored") + } +} + +func TestReportConfigurationSchemaRequiresOwnIdentity(t *testing.T) { + store, appID, _, ctx := reportingApp(t, "") + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}, IdentityID: uuid.New()}, nil + } + srv := newServer(store) + + _, err := srv.ReportConfigurationSchema(ctx, &appsv1.ReportConfigurationSchemaRequest{ + AppId: appID.String(), + ConfigurationSchema: jsonStruct(t, maskedSchema), + }) + if status.Code(err) != codes.PermissionDenied { + t.Fatalf("want PermissionDenied, got %v", err) + } +} + +func TestValidateConfigurationReportsEachProperty(t *testing.T) { + srv := newServer(&fakeStore{}) + parsed := mustServerSchema(t, `{ + "type":"object", + "properties":{"a":{"type":"string"},"n":{"type":"integer","minimum":10}}, + "required":["a"] + }`) + + err := srv.validateConfiguration(context.Background(), parsed, jsonMap(t, `{"n":1,"other":true}`), uuid.New()) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("want InvalidArgument, got %v", err) + } + for _, want := range []string{"a", "n", "other"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error does not name property %q: %v", want, err) + } + } +} + +func TestValidateConfigurationRefusesUnresolvableReference(t *testing.T) { + srv := newServer(&fakeStore{}) + parsed := mustServerSchema(t, `{"type":"object","properties":{"agent_id":{"type":"string","x-agyn-ref":"agent"}}}`) + + // No resolver configured: an unvalidated reference is one the app finds + // wrong at runtime, so the write fails instead. + err := srv.validateConfiguration(context.Background(), parsed, + jsonMap(t, `{"agent_id":"8f14e45f-ceea-467a-9575-6f2f0f1f0f0f"}`), uuid.New()) + if status.Code(err) != codes.Unavailable { + t.Fatalf("want Unavailable, got %v", err) + } + + srv.SetReferenceResolver(resolverFunc(func(context.Context, string, uuid.UUID, uuid.UUID) (bool, error) { + return false, nil + })) + err = srv.validateConfiguration(context.Background(), parsed, + jsonMap(t, `{"agent_id":"8f14e45f-ceea-467a-9575-6f2f0f1f0f0f"}`), uuid.New()) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("want InvalidArgument for a reference that resolves to nothing, got %v", err) + } + + srv.SetReferenceResolver(resolverFunc(func(context.Context, string, uuid.UUID, uuid.UUID) (bool, error) { + return true, nil + })) + if err := srv.validateConfiguration(context.Background(), parsed, + jsonMap(t, `{"agent_id":"8f14e45f-ceea-467a-9575-6f2f0f1f0f0f"}`), uuid.New()); err != nil { + t.Fatalf("resolvable reference rejected: %v", err) + } +} + +type resolverFunc func(ctx context.Context, kind string, id uuid.UUID, organizationID uuid.UUID) (bool, error) + +func (f resolverFunc) ResolveExists(ctx context.Context, kind string, id, organizationID uuid.UUID) (bool, error) { + return f(ctx, kind, id, organizationID) +} + +// A property marked x-agyn-secret is a hint to the Console to mask the field. +// The platform does not withhold the value: it is stored in plain text and +// returned like any other. Pretending otherwise would be a promise the Apps +// Service cannot keep while the value round-trips through its own API. +func TestGetInstallationReturnsConfigurationWhole(t *testing.T) { + ctx, _ := newAdminContext() + store := &fakeStore{} + installationID := uuid.New() + + store.getInstallationFn = func(_ context.Context, _ uuid.UUID) (storepkg.Installation, error) { + return storepkg.Installation{ + Meta: storepkg.EntityMeta{ID: installationID}, + AppID: uuid.New(), + OrganizationID: uuid.New(), + Configuration: jsonMap(t, `{"bot_token":"123:secret","channel":"#ops"}`), + }, nil + } + authorizationClient := &fakeAuthorizationClient{} + authorizationClient.checkFn = func(context.Context, *authorizationv1.CheckRequest) (*authorizationv1.CheckResponse, error) { + return &authorizationv1.CheckResponse{Allowed: true}, nil + } + srv := New(store, &fakeIdentityClient{}, authorizationClient, &fakeZitiManagementClient{}) + + resp, err := srv.GetInstallation(ctx, &appsv1.GetInstallationRequest{Id: installationID.String()}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + fields := resp.GetInstallation().GetConfiguration().GetFields() + if fields["bot_token"].GetStringValue() != "123:secret" { + t.Fatalf("configuration did not round-trip whole: %v", fields) + } +} + +func mustServerSchema(t *testing.T, doc string) *schema.Schema { + t.Helper() + parsed, err := schema.Parse(jsonMap(t, doc)) + if err != nil { + t.Fatalf("Parse: %v", err) + } + return parsed +} + +// Narrowing the honored subset must not strand an app. A schema stored before +// the narrowing no longer parses, and if that were an error the app could never +// report the replacement that would fix it. +func TestReportConfigurationSchemaWhenStoredSchemaIsNoLongerExpressible(t *testing.T) { + // x-agyn-secret was honored when this was written and is reserved now. + store, appID, _, ctx := reportingApp(t, `{ + "type":"object", + "properties":{"bot_token":{"type":"string","x-agyn-secret":true}}, + "required":["bot_token"] + }`) + srv := newServer(store) + + _, err := srv.ReportConfigurationSchema(ctx, &appsv1.ReportConfigurationSchemaRequest{ + AppId: appID.String(), + ConfigurationSchema: jsonStruct(t, maskedSchema), + }) + if err != nil { + t.Fatalf("app stranded by a schema it cannot replace: %v", err) + } + if len(store.setConfigurationSchemaCalls) != 1 { + t.Fatal("the replacement schema was not stored") + } +} diff --git a/internal/server/converter.go b/internal/server/converter.go index 4e6bcf2..5de2c3d 100644 --- a/internal/server/converter.go +++ b/internal/server/converter.go @@ -18,7 +18,7 @@ func toProtoEntityMeta(meta store.EntityMeta) *appsv1.EntityMeta { } func toProtoApp(app store.App) *appsv1.App { - return &appsv1.App{ + proto := &appsv1.App{ Meta: toProtoEntityMeta(app.Meta), Slug: app.Slug, Name: app.Name, @@ -31,6 +31,15 @@ func toProtoApp(app store.App) *appsv1.App { Visibility: toProtoVisibility(app.Visibility), Permissions: app.Permissions, } + if app.ConfigurationSchema != nil { + if schemaStruct, err := mapToProtoStruct(app.ConfigurationSchema); err == nil { + proto.ConfigurationSchema = schemaStruct + } + } + if app.SchemaReportedAt != nil { + proto.SchemaReportedAt = timestamppb.New(*app.SchemaReportedAt) + } + return proto } func toProtoInstallation(installation store.Installation) (*appsv1.Installation, error) { diff --git a/internal/server/references.go b/internal/server/references.go new file mode 100644 index 0000000..55aaf0d --- /dev/null +++ b/internal/server/references.go @@ -0,0 +1,68 @@ +package server + +import ( + "context" + "fmt" + + agentsv1 "github.com/agynio/apps/.gen/go/agynio/api/agents/v1" + llmv1 "github.com/agynio/apps/.gen/go/agynio/api/llm/v1" + "github.com/agynio/apps/internal/schema" + "github.com/google/uuid" + "google.golang.org/grpc" +) + +type agentsReferenceClient interface { + ResolveAgentExists(context.Context, *agentsv1.ResolveAgentExistsRequest, ...grpc.CallOption) (*agentsv1.ResolveAgentExistsResponse, error) + ResolveEnvironmentExists(context.Context, *agentsv1.ResolveEnvironmentExistsRequest, ...grpc.CallOption) (*agentsv1.ResolveEnvironmentExistsResponse, error) +} + +type llmReferenceClient interface { + ResolveModelExists(context.Context, *llmv1.ResolveModelExistsRequest, ...grpc.CallOption) (*llmv1.ResolveModelExistsResponse, error) +} + +// ServiceReferenceResolver answers an x-agyn-ref by asking the service that +// owns the kind. Each kind is a closed vocabulary entry precisely because it +// costs one of these calls; an unknown kind is a programming error rather than +// something to resolve leniently, so it errors and fails the write. +type ServiceReferenceResolver struct { + agents agentsReferenceClient + llm llmReferenceClient +} + +func NewServiceReferenceResolver(agents agentsReferenceClient, llm llmReferenceClient) *ServiceReferenceResolver { + return &ServiceReferenceResolver{agents: agents, llm: llm} +} + +func (r *ServiceReferenceResolver) ResolveExists(ctx context.Context, kind string, id, organizationID uuid.UUID) (bool, error) { + switch kind { + case schema.RefAgent: + resp, err := r.agents.ResolveAgentExists(ctx, &agentsv1.ResolveAgentExistsRequest{ + AgentId: id.String(), + OrganizationId: organizationID.String(), + }) + if err != nil { + return false, err + } + return resp.GetExists(), nil + case schema.RefEnvironment: + resp, err := r.agents.ResolveEnvironmentExists(ctx, &agentsv1.ResolveEnvironmentExistsRequest{ + EnvironmentId: id.String(), + OrganizationId: organizationID.String(), + }) + if err != nil { + return false, err + } + return resp.GetExists(), nil + case schema.RefModel: + resp, err := r.llm.ResolveModelExists(ctx, &llmv1.ResolveModelExistsRequest{ + ModelId: id.String(), + OrganizationId: organizationID.String(), + }) + if err != nil { + return false, err + } + return resp.GetExists(), nil + default: + return false, fmt.Errorf("no resolver for reference kind %q", kind) + } +} diff --git a/internal/server/references_test.go b/internal/server/references_test.go new file mode 100644 index 0000000..bcc263a --- /dev/null +++ b/internal/server/references_test.go @@ -0,0 +1,86 @@ +package server + +import ( + "context" + "errors" + "testing" + + agentsv1 "github.com/agynio/apps/.gen/go/agynio/api/agents/v1" + llmv1 "github.com/agynio/apps/.gen/go/agynio/api/llm/v1" + "github.com/agynio/apps/internal/schema" + "github.com/google/uuid" + "google.golang.org/grpc" +) + +type fakeAgentsReferenceClient struct { + agentExists bool + environmentExists bool + err error + agentRequests []*agentsv1.ResolveAgentExistsRequest +} + +func (f *fakeAgentsReferenceClient) ResolveAgentExists(_ context.Context, req *agentsv1.ResolveAgentExistsRequest, _ ...grpc.CallOption) (*agentsv1.ResolveAgentExistsResponse, error) { + f.agentRequests = append(f.agentRequests, req) + if f.err != nil { + return nil, f.err + } + return &agentsv1.ResolveAgentExistsResponse{Exists: f.agentExists}, nil +} + +func (f *fakeAgentsReferenceClient) ResolveEnvironmentExists(_ context.Context, _ *agentsv1.ResolveEnvironmentExistsRequest, _ ...grpc.CallOption) (*agentsv1.ResolveEnvironmentExistsResponse, error) { + if f.err != nil { + return nil, f.err + } + return &agentsv1.ResolveEnvironmentExistsResponse{Exists: f.environmentExists}, nil +} + +type fakeLLMReferenceClient struct{ exists bool } + +func (f *fakeLLMReferenceClient) ResolveModelExists(_ context.Context, _ *llmv1.ResolveModelExistsRequest, _ ...grpc.CallOption) (*llmv1.ResolveModelExistsResponse, error) { + return &llmv1.ResolveModelExistsResponse{Exists: f.exists}, nil +} + +func TestServiceReferenceResolverRoutesByKind(t *testing.T) { + agents := &fakeAgentsReferenceClient{agentExists: true, environmentExists: false} + llm := &fakeLLMReferenceClient{exists: true} + resolver := NewServiceReferenceResolver(agents, llm) + + id, organizationID := uuid.New(), uuid.New() + + for _, tc := range []struct { + kind string + want bool + }{ + {schema.RefAgent, true}, + {schema.RefEnvironment, false}, + {schema.RefModel, true}, + } { + got, err := resolver.ResolveExists(context.Background(), tc.kind, id, organizationID) + if err != nil { + t.Fatalf("%s: %v", tc.kind, err) + } + if got != tc.want { + t.Errorf("%s: got %v, want %v", tc.kind, got, tc.want) + } + } + + // The organization travels with the question, so the check and the scoping + // cannot disagree. + if len(agents.agentRequests) != 1 || agents.agentRequests[0].GetOrganizationId() != organizationID.String() { + t.Fatalf("organization not passed through: %v", agents.agentRequests) + } +} + +func TestServiceReferenceResolverPropagatesFailure(t *testing.T) { + resolver := NewServiceReferenceResolver(&fakeAgentsReferenceClient{err: errors.New("unreachable")}, &fakeLLMReferenceClient{}) + if _, err := resolver.ResolveExists(context.Background(), schema.RefAgent, uuid.New(), uuid.New()); err == nil { + t.Fatal("an unreachable service resolved successfully") + } +} + +func TestServiceReferenceResolverRejectsUnknownKind(t *testing.T) { + resolver := NewServiceReferenceResolver(&fakeAgentsReferenceClient{}, &fakeLLMReferenceClient{}) + if _, err := resolver.ResolveExists(context.Background(), "sandbox", uuid.New(), uuid.New()); err == nil { + t.Fatal("an unknown reference kind resolved instead of erroring") + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 71ccf9b..3543fa8 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -65,6 +65,8 @@ type AppStore interface { DeleteInstallation(ctx context.Context, id uuid.UUID) error AppendInstallationAuditLogEntry(ctx context.Context, input store.AppendInstallationAuditLogEntryInput) (store.InstallationAuditLogEntry, error) ListInstallationAuditLogEntries(ctx context.Context, installationID uuid.UUID, pageSize int, pageToken string) ([]store.InstallationAuditLogEntry, string, error) + SetAppConfigurationSchema(ctx context.Context, id uuid.UUID, schema map[string]any) (store.App, error) + CountInstallationsWithConfigurationKey(ctx context.Context, appID uuid.UUID, key string) (int, error) } type Server struct { @@ -74,6 +76,14 @@ type Server struct { authorizationClient authorizationv1.AuthorizationServiceClient zitiManagementClient zitiManagementClient groupsClient groupsClient + references ReferenceResolver +} + +// SetReferenceResolver wires the resolver used to validate x-agyn-ref +// properties. Without one, an installation carrying a reference is refused +// rather than stored unvalidated. +func (s *Server) SetReferenceResolver(resolver ReferenceResolver) { + s.references = resolver } type zitiManagementClient interface { @@ -463,6 +473,16 @@ func (s *Server) InstallApp(ctx context.Context, req *appsv1.InstallAppRequest) return nil, status.Errorf(codes.InvalidArgument, "slug: %v", err) } configuration := protoStructToMap(req.GetConfiguration()) + if configuration == nil { + configuration = map[string]any{} + } + installSchema, err := appSchema(app) + if err != nil { + return nil, err + } + if err := s.validateConfiguration(ctx, installSchema, configuration, organizationID); err != nil { + return nil, err + } installation, err := s.store.CreateInstallation(ctx, store.CreateInstallationInput{ ID: uuid.New(), @@ -637,8 +657,18 @@ func (s *Server) UpdateInstallation(ctx context.Context, req *appsv1.UpdateInsta } input.Slug = &slug } + updateSchema, err := s.installationSchema(ctx, installation.AppID) + if err != nil { + return nil, err + } if req.Configuration != nil { configuration := protoStructToMap(req.GetConfiguration()) + if configuration == nil { + configuration = map[string]any{} + } + if err := s.validateConfiguration(ctx, updateSchema, configuration, installation.OrganizationID); err != nil { + return nil, err + } input.Configuration = &configuration } diff --git a/internal/server/server_test.go b/internal/server/server_test.go index e0a7809..61c4ca9 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -40,6 +40,9 @@ type fakeStore struct { listInstallationsFn func(ctx context.Context, pageSize int, pageToken string, filter storepkg.ListInstallationsFilter) ([]storepkg.Installation, string, error) updateInstallationFn func(ctx context.Context, input storepkg.UpdateInstallationInput) (storepkg.Installation, error) updateInstallationStatusFn func(ctx context.Context, id uuid.UUID, status *string) (storepkg.Installation, error) + setConfigurationSchemaFn func(ctx context.Context, id uuid.UUID, schema map[string]any) (storepkg.App, error) + countInstallationsWithKeyFn func(ctx context.Context, appID uuid.UUID, key string) (int, error) + setConfigurationSchemaCalls []setConfigurationSchemaCall deleteInstallationFn func(ctx context.Context, id uuid.UUID) error appendInstallationAuditLogEntryFn func(ctx context.Context, input storepkg.AppendInstallationAuditLogEntryInput) (storepkg.InstallationAuditLogEntry, error) listInstallationAuditLogEntriesFn func(ctx context.Context, installationID uuid.UUID, pageSize int, pageToken string) ([]storepkg.InstallationAuditLogEntry, string, error) @@ -256,6 +259,11 @@ func (f *fakeStore) ListInstallations(ctx context.Context, pageSize int, pageTok return nil, "", errors.New("list installations not implemented") } +type setConfigurationSchemaCall struct { + id uuid.UUID + schema map[string]any +} + func (f *fakeStore) UpdateInstallation(ctx context.Context, input storepkg.UpdateInstallationInput) (storepkg.Installation, error) { f.updateInstallationInputs = append(f.updateInstallationInputs, input) if f.updateInstallationFn != nil { @@ -264,6 +272,21 @@ func (f *fakeStore) UpdateInstallation(ctx context.Context, input storepkg.Updat return storepkg.Installation{}, errors.New("update installation not implemented") } +func (f *fakeStore) SetAppConfigurationSchema(ctx context.Context, id uuid.UUID, schema map[string]any) (storepkg.App, error) { + f.setConfigurationSchemaCalls = append(f.setConfigurationSchemaCalls, setConfigurationSchemaCall{id: id, schema: schema}) + if f.setConfigurationSchemaFn != nil { + return f.setConfigurationSchemaFn(ctx, id, schema) + } + return storepkg.App{}, errors.New("set configuration schema not implemented") +} + +func (f *fakeStore) CountInstallationsWithConfigurationKey(ctx context.Context, appID uuid.UUID, key string) (int, error) { + if f.countInstallationsWithKeyFn != nil { + return f.countInstallationsWithKeyFn(ctx, appID, key) + } + return 0, nil +} + func (f *fakeStore) UpdateInstallationStatus(ctx context.Context, id uuid.UUID, status *string) (storepkg.Installation, error) { f.updateInstallationStatusCalls = append(f.updateInstallationStatusCalls, updateInstallationStatusCall{id: id, status: status}) if f.updateInstallationStatusFn != nil { @@ -301,6 +324,10 @@ type fakeIdentityClient struct { registerRequests []*identityv1.RegisterIdentityRequest } +func (f *fakeIdentityClient) DeleteOrganizationResources(context.Context, *identityv1.DeleteOrganizationResourcesRequest, ...grpc.CallOption) (*identityv1.DeleteOrganizationResourcesResponse, error) { + return &identityv1.DeleteOrganizationResourcesResponse{}, nil +} + func (f *fakeIdentityClient) RegisterIdentity(ctx context.Context, req *identityv1.RegisterIdentityRequest, _ ...grpc.CallOption) (*identityv1.RegisterIdentityResponse, error) { f.registerRequests = append(f.registerRequests, req) if f.registerFn != nil { @@ -1306,6 +1333,11 @@ func TestUpdateInstallationSuccess(t *testing.T) { t.Fatalf("unexpected config error: %v", err) } + // Reads strip secrets, which resolves the app's schema; this app has none. + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}}, nil + } + srv := New(store, identityClient, authorizationClient, zitiClient) resp, err := srv.UpdateInstallation(ctx, &appsv1.UpdateInstallationRequest{ Id: installationID.String(), @@ -1350,6 +1382,11 @@ func TestGetInstallationRequiresMember(t *testing.T) { }, nil } + // Reads strip secrets, which resolves the app's schema; this app has none. + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}}, nil + } + srv := New(store, identityClient, authorizationClient, zitiClient) _, err := srv.GetInstallation(ctx, &appsv1.GetInstallationRequest{Id: installationID.String()}) if err != nil { @@ -1419,6 +1456,11 @@ func TestGetInstallationBySlugRequiresMember(t *testing.T) { }, nil } + // Reads strip secrets, which resolves the app's schema; this app has none. + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}}, nil + } + srv := New(store, identityClient, authorizationClient, zitiClient) _, err := srv.GetInstallationBySlug(ctx, &appsv1.GetInstallationBySlugRequest{OrganizationId: organizationID.String(), Slug: "install"}) if err != nil { @@ -1513,6 +1555,11 @@ func TestListInstallationsAllowsAppIdentityWithAppID(t *testing.T) { }, "", nil } + // Reads strip secrets, which resolves the app's schema; this app has none. + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}}, nil + } + srv := New(store, identityClient, authorizationClient, zitiClient) resp, err := srv.ListInstallations(ctx, &appsv1.ListInstallationsRequest{AppId: appID.String()}) if err != nil { @@ -1595,6 +1642,11 @@ func TestListInstallationsFiltersByMembershipWithAppID(t *testing.T) { return &authorizationv1.CheckResponse{Allowed: false}, nil } + // Reads strip secrets, which resolves the app's schema; this app has none. + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}}, nil + } + srv := New(store, identityClient, authorizationClient, zitiClient) resp, err := srv.ListInstallations(ctx, &appsv1.ListInstallationsRequest{AppId: appID.String()}) if err != nil { @@ -1651,6 +1703,12 @@ func TestListInstallationsFiltersByMembership(t *testing.T) { return &authorizationv1.CheckResponse{Allowed: false}, nil } + // The list strips secrets per installation, which means resolving each + // app's schema; these apps have reported none. + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}}, nil + } + srv := New(store, identityClient, authorizationClient, zitiClient) resp, err := srv.ListInstallations(ctx, &appsv1.ListInstallationsRequest{}) if err != nil { @@ -1700,6 +1758,12 @@ func TestListInstallationsCachesMembershipChecks(t *testing.T) { }, "", nil } + // The list strips secrets per installation, which means resolving each + // app's schema; these apps have reported none. + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}}, nil + } + srv := New(store, identityClient, authorizationClient, zitiClient) resp, err := srv.ListInstallations(ctx, &appsv1.ListInstallationsRequest{}) if err != nil { diff --git a/internal/store/store.go b/internal/store/store.go index 6642e43..2704864 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -3,6 +3,7 @@ package store import ( "context" "encoding/base64" + "encoding/json" "errors" "fmt" "strings" @@ -16,7 +17,7 @@ import ( ) const ( - appColumns = `id, slug, name, description, icon, identity_id, service_token_hash, ziti_identity_id, ziti_service_id, organization_id, visibility, permissions, created_at, updated_at` + appColumns = `id, slug, name, description, icon, identity_id, service_token_hash, ziti_identity_id, ziti_service_id, organization_id, visibility, permissions, configuration_schema, schema_reported_at, created_at, updated_at` installationColumns = `id, app_id, organization_id, slug, configuration, status, created_at, updated_at` defaultListPageSize = 50 @@ -49,6 +50,10 @@ type App struct { OrganizationID uuid.UUID Visibility AppVisibility Permissions []string + // ConfigurationSchema is reported by the app itself, never set through + // CreateApp or UpdateApp. Nil until the first report. + ConfigurationSchema map[string]any + SchemaReportedAt *time.Time } type CreateAppInput struct { @@ -124,6 +129,8 @@ func nonNilStrings(values []string) []string { func scanApp(row pgx.Row) (App, error) { var app App + var schema []byte + var reportedAt pgtype.Timestamptz if err := row.Scan( &app.Meta.ID, &app.Slug, @@ -137,11 +144,22 @@ func scanApp(row pgx.Row) (App, error) { &app.OrganizationID, &app.Visibility, &app.Permissions, + &schema, + &reportedAt, &app.Meta.CreatedAt, &app.Meta.UpdatedAt, ); err != nil { return App{}, err } + if len(schema) > 0 { + if err := json.Unmarshal(schema, &app.ConfigurationSchema); err != nil { + return App{}, fmt.Errorf("decode configuration schema: %w", err) + } + } + if reportedAt.Valid { + at := reportedAt.Time + app.SchemaReportedAt = &at + } return app, nil } @@ -393,6 +411,45 @@ func (s *Store) UpdateApp(ctx context.Context, input UpdateAppInput) (App, error return app, nil } +// SetAppConfigurationSchema replaces the app's stored schema with the reported +// document. Declarative: the stored schema is replaced, never merged. +func (s *Store) SetAppConfigurationSchema(ctx context.Context, id uuid.UUID, schema map[string]any) (App, error) { + encoded, err := json.Marshal(schema) + if err != nil { + return App{}, fmt.Errorf("encode configuration schema: %w", err) + } + row := s.pool.QueryRow(ctx, + fmt.Sprintf(`UPDATE apps + SET configuration_schema = $1, schema_reported_at = NOW(), updated_at = NOW() + WHERE id = $2 + RETURNING %s`, appColumns), + encoded, id, + ) + app, err := scanApp(row) + if errors.Is(err, pgx.ErrNoRows) { + return App{}, NotFound("app") + } + if err != nil { + return App{}, err + } + return app, nil +} + +// CountInstallationsWithConfigurationKey reports how many installations of the +// app hold a value for a configuration key. It spans every organization the app +// is installed into, which is why only this service can answer it. +func (s *Store) CountInstallationsWithConfigurationKey(ctx context.Context, appID uuid.UUID, key string) (int, error) { + var count int + err := s.pool.QueryRow(ctx, + `SELECT COUNT(*) FROM app_installations WHERE app_id = $1 AND jsonb_exists(configuration, $2)`, + appID, key, + ).Scan(&count) + if err != nil { + return 0, err + } + return count, nil +} + func (s *Store) DeleteApp(ctx context.Context, id uuid.UUID) error { result, err := s.pool.Exec(ctx, `DELETE FROM apps WHERE id = $1`, id) if err != nil { diff --git a/migrations/0004_app_configuration_schema.sql b/migrations/0004_app_configuration_schema.sql new file mode 100644 index 0000000..54af759 --- /dev/null +++ b/migrations/0004_app_configuration_schema.sql @@ -0,0 +1,14 @@ +-- 0004_app_configuration_schema.sql + +-- The configuration schema an app reports for its installations. NULL until +-- the app first reports one; installations made before that carry an +-- unvalidated configuration object. +ALTER TABLE apps ADD COLUMN configuration_schema JSONB; +ALTER TABLE apps ADD COLUMN schema_reported_at TIMESTAMPTZ; + +-- Removing a deprecated property is allowed only once no installation of the +-- app carries a value for it, which is a lookup by app and by configuration key. +-- Default jsonb_ops rather than jsonb_path_ops: the lookup is jsonb_exists, +-- which jsonb_path_ops does not support. +CREATE INDEX app_installations_configuration_keys_idx + ON app_installations USING GIN (configuration);