From adf3cecaa77b6975affa569448cd5c620f8a9e56 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 1 Sep 2026 08:03:32 +0400 Subject: [PATCH 01/11] Configuration schema parsing, compatibility, and validation Apps report a JSON Schema for their installation configuration. The honored subset is validated by hand rather than with a JSON Schema library: the subset is deliberately narrower than the standard, so a library would accept constructs the Console cannot render a form from. - Parse enforces the honored subset and rejects at report time, where the app author can fix it - CheckCompatible refuses a schema that would stop accepting what the previous one accepted; a deprecated property is removable once nothing carries it - StripSecrets omits x-agyn-secret values rather than masking them, so a read-modify-write round-trip cannot submit a placeholder as the credential --- internal/schema/compatibility.go | 141 +++++++ internal/schema/configuration.go | 200 ++++++++++ internal/schema/schema.go | 365 +++++++++++++++++++ internal/schema/schema_test.go | 241 ++++++++++++ migrations/0004_app_configuration_schema.sql | 12 + 5 files changed, 959 insertions(+) create mode 100644 internal/schema/compatibility.go create mode 100644 internal/schema/configuration.go create mode 100644 internal/schema/schema.go create mode 100644 internal/schema/schema_test.go create mode 100644 migrations/0004_app_configuration_schema.sql diff --git a/internal/schema/compatibility.go b/internal/schema/compatibility.go new file mode 100644 index 0000000..4c96fb6 --- /dev/null +++ b/internal/schema/compatibility.go @@ -0,0 +1,141 @@ +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 before.Secret && !after.Secret { + return fmt.Errorf("property %q cleared x-agyn-secret; values collected as credentials would become readable", name) + } + 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 != "" { + 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 +} diff --git a/internal/schema/configuration.go b/internal/schema/configuration.go new file mode 100644 index 0000000..c12d930 --- /dev/null +++ b/internal/schema/configuration.go @@ -0,0 +1,200 @@ +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 "": + 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 +} + +// StripSecrets returns the configuration without the values of properties +// marked x-agyn-secret, and the names of the ones that held a value. +// +// The key is omitted rather than masked: a placeholder in the value's position +// is a value, and a client that reads an installation, edits one field, and +// writes it back would submit the placeholder as the credential. +func (s *Schema) StripSecrets(config map[string]any) (map[string]any, []string) { + stripped := make(map[string]any, len(config)) + var set []string + for key, value := range config { + if p, ok := s.Properties[key]; ok && p.Secret { + if value != nil && value != "" { + set = append(set, key) + } + continue + } + stripped[key] = value + } + sort.Strings(set) + return stripped, set +} + +// MergeSecrets carries stored secret values into a submitted configuration +// that omits them, which is what an unchanged round-trip looks like once +// StripSecrets has removed them from every admin-facing read. +func (s *Schema) MergeSecrets(submitted, stored map[string]any) map[string]any { + merged := make(map[string]any, len(submitted)) + for key, value := range submitted { + merged[key] = value + } + for _, name := range s.SecretKeys() { + if _, submittedIt := merged[name]; submittedIt { + continue + } + if value, ok := stored[name]; ok { + merged[name] = value + } + } + return merged +} diff --git a/internal/schema/schema.go b/internal/schema/schema.go new file mode 100644 index 0000000..8fbb31e --- /dev/null +++ b/internal/schema/schema.go @@ -0,0 +1,365 @@ +// 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: {}} + validFormats = map[string]struct{}{"uri": {}, "email": {}, "uuid": {}} + + 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-secret": {}, "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 + Secret bool + 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 _, 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-secret"]; ok { + b, ok := v.(bool) + if !ok { + return nil, fmt.Errorf("property %q: x-agyn-secret must be a boolean", name) + } + if b && p.Type != TypeString { + return nil, fmt.Errorf("property %q: x-agyn-secret applies to string properties only", name) + } + p.Secret = b + } + 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 p.Secret && p.Ref != "" { + return nil, fmt.Errorf("property %q cannot be both a secret and a reference", name) + } + + 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 +} + +// SecretKeys returns the names of properties marked x-agyn-secret. +func (s *Schema) SecretKeys() []string { + var out []string + for _, name := range s.Names { + if s.Properties[name].Secret { + out = append(out, name) + } + } + return out +} + +// 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..ad40331 --- /dev/null +++ b/internal/schema/schema_test.go @@ -0,0 +1,241 @@ +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", "x-agyn-secret": true}, + "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"}}}`, + "secret on int": `{"type":"object","properties":{"a":{"type":"integer","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"]}`, + "secret and ref": `{"type":"object","properties":{"a":{"type":"string","x-agyn-secret":true,"x-agyn-ref":"agent"}}}`, + } + 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 got := s.SecretKeys(); len(got) != 1 || got[0] != "bot_token" { + t.Fatalf("SecretKeys() = %v, want [bot_token]", got) + } + 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 TestStripAndMergeSecretsRoundTrip(t *testing.T) { + s := mustParse(t, telegram) + stored := config(t, `{"bot_token":"123:secret","agent_id":"8f14e45f-ceea-467a-9575-6f2f0f1f0f0f"}`) + + stripped, set := s.StripSecrets(stored) + if _, present := stripped["bot_token"]; present { + t.Fatal("StripSecrets left the secret value in place") + } + if len(set) != 1 || set[0] != "bot_token" { + t.Fatalf("secret_keys_set = %v, want [bot_token]", set) + } + + // An unchanged round-trip: the client writes back what it read. + merged := s.MergeSecrets(stripped, stored) + if merged["bot_token"] != "123:secret" { + t.Fatalf("round-trip lost the stored secret: %v", merged["bot_token"]) + } + + // An explicit replacement wins over the stored value. + replaced := s.MergeSecrets(config(t, `{"bot_token":"new","agent_id":"8f14e45f-ceea-467a-9575-6f2f0f1f0f0f"}`), stored) + if replaced["bot_token"] != "new" { + t.Fatalf("replacement did not take: %v", replaced["bot_token"]) + } +} + +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","x-agyn-secret":true} + }, + "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) + } + }) + } +} + +func TestCheckCompatibleRejectsClearingSecret(t *testing.T) { + prev := mustParse(t, `{"type":"object","properties":{"t":{"type":"string","x-agyn-secret":true}}}`) + next := mustParse(t, `{"type":"object","properties":{"t":{"type":"string"}}}`) + err := next.CheckCompatible(prev, never) + if err == nil { + t.Fatal("clearing x-agyn-secret was accepted") + } + if !strings.Contains(err.Error(), "readable") { + t.Fatalf("error does not explain the disclosure: %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/migrations/0004_app_configuration_schema.sql b/migrations/0004_app_configuration_schema.sql new file mode 100644 index 0000000..80d7a8a --- /dev/null +++ b/migrations/0004_app_configuration_schema.sql @@ -0,0 +1,12 @@ +-- 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. +CREATE INDEX app_installations_app_id_configuration_idx + ON app_installations USING GIN (configuration jsonb_path_ops); From 453e1ce738981b92da29f0560aa3f9cd8f761e21 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 1 Sep 2026 08:14:01 +0400 Subject: [PATCH 02/11] Report, validate, and redact installation configuration ReportConfigurationSchema is authorized to the app's own identity and replaces the stored schema wholesale, rejecting a document outside the honored subset or one that would stop accepting what the previous schema accepted. A rejected report leaves the previous schema whole, including the compatible changes in the same document. Redaction is a property of toProtoInstallation rather than of a list of methods, so a read path cannot be added without deciding: it takes the app's schema and cannot build the message otherwise. Secret properties are omitted and named in secret_keys_set; UpdateInstallation carries stored values back in when a write omits them, which is what makes an unchanged round-trip safe. References are resolved through a ReferenceResolver. With none configured an installation carrying one is refused rather than stored unvalidated, since the app would otherwise discover it wrong at runtime with no form to correct it. --- internal/server/configuration.go | 177 +++++++++++++ internal/server/configuration_test.go | 247 +++++++++++++++++++ internal/server/converter.go | 29 ++- internal/server/server.go | 75 +++++- internal/server/server_test.go | 60 +++++ internal/store/store.go | 59 ++++- migrations/0004_app_configuration_schema.sql | 6 +- 7 files changed, 641 insertions(+), 12 deletions(-) create mode 100644 internal/server/configuration.go create mode 100644 internal/server/configuration_test.go diff --git a/internal/server/configuration.go b/internal/server/configuration.go new file mode 100644 index 0000000..85d2680 --- /dev/null +++ b/internal/server/configuration.go @@ -0,0 +1,177 @@ +package server + +import ( + "context" + "errors" + "fmt" + + 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 an internal +// inconsistency: it was validated against the honored subset when it was +// written. +func appSchema(app store.App) (*schema.Schema, error) { + if app.ConfigurationSchema == nil { + return nil, nil + } + parsed, err := schema.Parse(app.ConfigurationSchema) + if err != nil { + return nil, status.Errorf(codes.Internal, "stored configuration schema for app %s does not parse: %v", app.Meta.ID, err) + } + 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..e0d8376 --- /dev/null +++ b/internal/server/configuration_test.go @@ -0,0 +1,247 @@ +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 secretSchema = `{ + "type": "object", + "properties": { + "bot_token": {"type": "string", "x-agyn-secret": true}, + "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, secretSchema), + }) + 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, secretSchema) + 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, secretSchema), + }) + 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) +} + +func TestGetInstallationOmitsSecretValues(t *testing.T) { + ctx, _ := newAdminContext() + store := &fakeStore{} + appID := uuid.New() + organizationID := uuid.New() + installationID := uuid.New() + + store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { + return storepkg.App{Meta: storepkg.EntityMeta{ID: id}, ConfigurationSchema: jsonMap(t, secretSchema)}, nil + } + store.getInstallationFn = func(_ context.Context, _ uuid.UUID) (storepkg.Installation, error) { + return storepkg.Installation{ + Meta: storepkg.EntityMeta{ID: installationID}, + AppID: appID, + OrganizationID: organizationID, + 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 _, present := fields["bot_token"]; present { + t.Fatal("secret value was returned on the admin read path") + } + if fields["channel"].GetStringValue() != "#ops" { + t.Fatalf("non-secret value was stripped: %v", fields) + } + if got := resp.GetInstallation().GetSecretKeysSet(); len(got) != 1 || got[0] != "bot_token" { + t.Fatalf("secret_keys_set = %v, want [bot_token]", got) + } +} + +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 +} diff --git a/internal/server/converter.go b/internal/server/converter.go index 4e6bcf2..5a46cea 100644 --- a/internal/server/converter.go +++ b/internal/server/converter.go @@ -4,6 +4,7 @@ import ( "fmt" appsv1 "github.com/agynio/apps/.gen/go/agynio/api/apps/v1" + "github.com/agynio/apps/internal/schema" "github.com/agynio/apps/internal/store" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" @@ -18,7 +19,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,10 +32,31 @@ 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) { - configuration, err := mapToProtoStruct(installation.Configuration) +// toProtoInstallation renders an installation for a caller that is not the app. +// It takes the app's schema rather than looking it up so that redaction is a +// property of the conversion every read path goes through: a new read path +// cannot forget to redact, because it cannot build the message without deciding. +// +// appSchema is nil when the app has reported none, in which case nothing is +// marked secret and nothing is stripped. +func toProtoInstallation(installation store.Installation, appSchema *schema.Schema) (*appsv1.Installation, error) { + values := installation.Configuration + var secretKeysSet []string + if appSchema != nil { + values, secretKeysSet = appSchema.StripSecrets(values) + } + configuration, err := mapToProtoStruct(values) if err != nil { return nil, err } @@ -44,6 +66,7 @@ func toProtoInstallation(installation store.Installation) (*appsv1.Installation, OrganizationId: installation.OrganizationID.String(), Slug: installation.Slug, Configuration: configuration, + SecretKeysSet: secretKeysSet, } if installation.Status != nil { status := *installation.Status diff --git a/internal/server/server.go b/internal/server/server.go index 71ccf9b..4e8f0a0 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -15,6 +15,7 @@ import ( groupsv1 "github.com/agynio/apps/.gen/go/agynio/api/groups/v1" identityv1 "github.com/agynio/apps/.gen/go/agynio/api/identity/v1" zitimanagementv1 "github.com/agynio/apps/.gen/go/agynio/api/ziti_management/v1" + "github.com/agynio/apps/internal/schema" "github.com/agynio/apps/internal/store" "github.com/google/uuid" "google.golang.org/grpc" @@ -65,6 +66,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 +77,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 +474,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(), @@ -482,7 +503,7 @@ func (s *Server) InstallApp(ctx context.Context, req *appsv1.InstallAppRequest) return nil, err } - protoInstallation, err := toProtoInstallation(installation) + protoInstallation, err := toProtoInstallation(installation, installSchema) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -505,7 +526,11 @@ func (s *Server) GetInstallation(ctx context.Context, req *appsv1.GetInstallatio if err := s.requireOrgMember(ctx, callerID, installation.OrganizationID); err != nil { return nil, err } - protoInstallation, err := toProtoInstallation(installation) + readSchema, err := s.installationSchema(ctx, installation.AppID) + if err != nil { + return nil, err + } + protoInstallation, err := toProtoInstallation(installation, readSchema) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -532,7 +557,11 @@ func (s *Server) GetInstallationBySlug(ctx context.Context, req *appsv1.GetInsta if err := s.requireOrgMember(ctx, callerID, installation.OrganizationID); err != nil { return nil, err } - protoInstallation, err := toProtoInstallation(installation) + readSchema, err := s.installationSchema(ctx, installation.AppID) + if err != nil { + return nil, err + } + protoInstallation, err := toProtoInstallation(installation, readSchema) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -587,6 +616,9 @@ func (s *Server) ListInstallations(ctx context.Context, req *appsv1.ListInstalla return nil, status.Errorf(codes.Internal, "list installations: %v", err) } protoInstallations := make([]*appsv1.Installation, 0, len(installations)) + // One schema lookup per distinct app rather than per installation: a list + // filtered by app or organization repeats the same few apps. + schemasByApp := make(map[uuid.UUID]*schema.Schema) orgAccess := map[uuid.UUID]bool{} for _, installation := range installations { if filter.OrganizationID == nil && !allowAppIdentity { @@ -603,7 +635,15 @@ func (s *Server) ListInstallations(ctx context.Context, req *appsv1.ListInstalla continue } } - protoInstallation, err := toProtoInstallation(installation) + listSchema, ok := schemasByApp[installation.AppID] + if !ok { + listSchema, err = s.installationSchema(ctx, installation.AppID) + if err != nil { + return nil, err + } + schemasByApp[installation.AppID] = listSchema + } + protoInstallation, err := toProtoInstallation(installation, listSchema) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -637,8 +677,24 @@ 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 updateSchema != nil { + // A secret property the caller omitted keeps its stored value: the + // admin read path never returned it, so a round-trip cannot + // resubmit it. + configuration = updateSchema.MergeSecrets(configuration, installation.Configuration) + } + if err := s.validateConfiguration(ctx, updateSchema, configuration, installation.OrganizationID); err != nil { + return nil, err + } input.Configuration = &configuration } @@ -646,7 +702,7 @@ func (s *Server) UpdateInstallation(ctx context.Context, req *appsv1.UpdateInsta if err != nil { return nil, toStatusError(err) } - protoInstallation, err := toProtoInstallation(installation) + protoInstallation, err := toProtoInstallation(installation, updateSchema) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -724,7 +780,14 @@ func (s *Server) ReportInstallationStatus(ctx context.Context, req *appsv1.Repor if err != nil { return nil, toStatusError(err) } - protoInstallation, err := toProtoInstallation(installation) + // Stripped here too: the app reads its own configuration through + // GetInstallationConfiguration, and keeping the rule on the message means + // no read path has to remember it. + statusSchema, err := s.installationSchema(ctx, installation.AppID) + if err != nil { + return nil, err + } + protoInstallation, err := toProtoInstallation(installation, statusSchema) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } diff --git a/internal/server/server_test.go b/internal/server/server_test.go index e0a7809..88e9ea1 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 { @@ -1306,6 +1329,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 +1378,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 +1452,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 +1551,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 +1638,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 +1699,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 +1754,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 index 80d7a8a..54af759 100644 --- a/migrations/0004_app_configuration_schema.sql +++ b/migrations/0004_app_configuration_schema.sql @@ -8,5 +8,7 @@ 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. -CREATE INDEX app_installations_app_id_configuration_idx - ON app_installations USING GIN (configuration jsonb_path_ops); +-- 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); From be1eb37087bf641d946e39e981d4833a21550ed3 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 1 Sep 2026 08:49:07 +0400 Subject: [PATCH 03/11] Resolve x-agyn-ref properties against the owning services MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Routes each reference kind to the service that owns it: agent and environment to Agents, model to LLM. The organization travels with the question so the existence check and the scoping cannot disagree. An unknown kind errors rather than resolving leniently — the vocabulary is closed, so reaching this branch is a programming error, and failing the write is better than storing a reference nothing ever checked. --- cmd/apps-service/main.go | 20 +++++++ internal/config/config.go | 17 ++++-- internal/server/references.go | 68 +++++++++++++++++++++++ internal/server/references_test.go | 86 ++++++++++++++++++++++++++++++ 4 files changed, 188 insertions(+), 3 deletions(-) create mode 100644 internal/server/references.go create mode 100644 internal/server/references_test.go 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/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/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") + } +} From 7b2bdd1b1846bd13ebaece7bd7e1c9422aae2243 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Sat, 12 Sep 2026 18:42:33 +0200 Subject: [PATCH 04/11] Stop pretending a configuration value is secret MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit x-agyn-secret marked a property and the service then omitted it from every read but one. The value was still stored in plain text, still submitted in plain text, and still returned to the app — so the hiding was a promise the platform could not keep, and it bought a redaction path, a merge-on-write rule, and an app lookup on every installation read to keep up the appearance. The marker stays as what it honestly is: a hint that the Console should mask the field. Configuration round-trips whole again, and reads no longer resolve the app's schema. Clearing the marker is an ordinary cosmetic change, so the compatibility rule that rejected it is gone too. Secrets belong in the Secrets service, referenced rather than copied. That is its own change. --- Dockerfile.localtest | 45 +++++++++++++++++++++++++++ internal/schema/compatibility.go | 3 -- internal/schema/configuration.go | 41 ------------------------ internal/schema/schema.go | 11 ------- internal/schema/schema_test.go | 42 +++++-------------------- internal/server/configuration_test.go | 25 ++++++--------- internal/server/converter.go | 18 ++--------- internal/server/server.go | 45 ++++----------------------- internal/server/server_test.go | 4 +++ 9 files changed, 74 insertions(+), 160 deletions(-) create mode 100644 Dockerfile.localtest diff --git a/Dockerfile.localtest b/Dockerfile.localtest new file mode 100644 index 0000000..71004bb --- /dev/null +++ b/Dockerfile.localtest @@ -0,0 +1,45 @@ +# syntax=docker/dockerfile:1.8 +ARG GO_VERSION=1.25 +ARG BUF_VERSION=1.66.0 + +FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS buf +ARG BUF_VERSION +RUN apk add --no-cache curl +RUN curl -sSL \ + "https://github.com/bufbuild/buf/releases/download/v${BUF_VERSION}/buf-$(uname -s)-$(uname -m)" \ + -o /usr/local/bin/buf && \ + chmod +x /usr/local/bin/buf + +FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS build + +WORKDIR /src + +COPY --from=buf /usr/local/bin/buf /usr/local/bin/buf + +COPY go.mod go.sum ./ +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/root/.cache/go-build \ + go mod download + +COPY .gen ./.gen + +COPY . . + +ARG TARGETOS TARGETARCH +ENV CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH + +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/root/.cache/go-build \ + go build -trimpath -ldflags "-s -w" -o /out/apps ./cmd/apps-service + +FROM alpine:3.21 AS runtime + +WORKDIR /app + +COPY --from=build /out/apps /app/apps + +RUN addgroup -g 10001 -S app && adduser -u 10001 -S app -G app + +USER 10001 + +ENTRYPOINT ["/app/apps"] diff --git a/internal/schema/compatibility.go b/internal/schema/compatibility.go index 4c96fb6..edc9ecb 100644 --- a/internal/schema/compatibility.go +++ b/internal/schema/compatibility.go @@ -63,9 +63,6 @@ func compareProperty(before, after *Property) error { } return fmt.Errorf("property %q changed x-agyn-ref from %q to %q", name, before.Ref, after.Ref) } - if before.Secret && !after.Secret { - return fmt.Errorf("property %q cleared x-agyn-secret; values collected as credentials would become readable", name) - } if err := compareEnum(before, after); err != nil { return err } diff --git a/internal/schema/configuration.go b/internal/schema/configuration.go index c12d930..0b0abcd 100644 --- a/internal/schema/configuration.go +++ b/internal/schema/configuration.go @@ -157,44 +157,3 @@ func containsValue(list []any, value any) bool { } return false } - -// StripSecrets returns the configuration without the values of properties -// marked x-agyn-secret, and the names of the ones that held a value. -// -// The key is omitted rather than masked: a placeholder in the value's position -// is a value, and a client that reads an installation, edits one field, and -// writes it back would submit the placeholder as the credential. -func (s *Schema) StripSecrets(config map[string]any) (map[string]any, []string) { - stripped := make(map[string]any, len(config)) - var set []string - for key, value := range config { - if p, ok := s.Properties[key]; ok && p.Secret { - if value != nil && value != "" { - set = append(set, key) - } - continue - } - stripped[key] = value - } - sort.Strings(set) - return stripped, set -} - -// MergeSecrets carries stored secret values into a submitted configuration -// that omits them, which is what an unchanged round-trip looks like once -// StripSecrets has removed them from every admin-facing read. -func (s *Schema) MergeSecrets(submitted, stored map[string]any) map[string]any { - merged := make(map[string]any, len(submitted)) - for key, value := range submitted { - merged[key] = value - } - for _, name := range s.SecretKeys() { - if _, submittedIt := merged[name]; submittedIt { - continue - } - if value, ok := stored[name]; ok { - merged[name] = value - } - } - return merged -} diff --git a/internal/schema/schema.go b/internal/schema/schema.go index 8fbb31e..bb5d79f 100644 --- a/internal/schema/schema.go +++ b/internal/schema/schema.go @@ -333,17 +333,6 @@ func valueMatchesType(v any, t Type) bool { return false } -// SecretKeys returns the names of properties marked x-agyn-secret. -func (s *Schema) SecretKeys() []string { - var out []string - for _, name := range s.Names { - if s.Properties[name].Secret { - out = append(out, name) - } - } - return out -} - // Refs returns the properties carrying an x-agyn-ref, in declaration order. func (s *Schema) Refs() []*Property { var out []*Property diff --git a/internal/schema/schema_test.go b/internal/schema/schema_test.go index ad40331..f6f64b6 100644 --- a/internal/schema/schema_test.go +++ b/internal/schema/schema_test.go @@ -69,8 +69,8 @@ func TestParseRejectsOutsideTheHonoredSubset(t *testing.T) { func TestParseAcceptsTheTelegramSchema(t *testing.T) { s := mustParse(t, telegram) - if got := s.SecretKeys(); len(got) != 1 || got[0] != "bot_token" { - t.Fatalf("SecretKeys() = %v, want [bot_token]", got) + if !s.Properties["bot_token"].Secret { + t.Fatal("bot_token should carry the x-agyn-secret marker") } refs := s.Refs() if len(refs) != 1 || refs[0].Ref != RefAgent { @@ -132,31 +132,6 @@ func asValidationError(err error, target **ValidationError) bool { return ok } -func TestStripAndMergeSecretsRoundTrip(t *testing.T) { - s := mustParse(t, telegram) - stored := config(t, `{"bot_token":"123:secret","agent_id":"8f14e45f-ceea-467a-9575-6f2f0f1f0f0f"}`) - - stripped, set := s.StripSecrets(stored) - if _, present := stripped["bot_token"]; present { - t.Fatal("StripSecrets left the secret value in place") - } - if len(set) != 1 || set[0] != "bot_token" { - t.Fatalf("secret_keys_set = %v, want [bot_token]", set) - } - - // An unchanged round-trip: the client writes back what it read. - merged := s.MergeSecrets(stripped, stored) - if merged["bot_token"] != "123:secret" { - t.Fatalf("round-trip lost the stored secret: %v", merged["bot_token"]) - } - - // An explicit replacement wins over the stored value. - replaced := s.MergeSecrets(config(t, `{"bot_token":"new","agent_id":"8f14e45f-ceea-467a-9575-6f2f0f1f0f0f"}`), stored) - if replaced["bot_token"] != "new" { - t.Fatalf("replacement did not take: %v", replaced["bot_token"]) - } -} - func never(string) (int, error) { return 0, nil } func TestCheckCompatibleAllowsWidening(t *testing.T) { @@ -205,15 +180,14 @@ func TestCheckCompatibleRejectsNarrowing(t *testing.T) { } } -func TestCheckCompatibleRejectsClearingSecret(t *testing.T) { +// Clearing x-agyn-secret is a display change, not a narrowing: the value was +// never withheld from the wire, so nothing stops validating and nothing is +// disclosed that was not already returned. +func TestCheckCompatibleAllowsClearingSecret(t *testing.T) { prev := mustParse(t, `{"type":"object","properties":{"t":{"type":"string","x-agyn-secret":true}}}`) next := mustParse(t, `{"type":"object","properties":{"t":{"type":"string"}}}`) - err := next.CheckCompatible(prev, never) - if err == nil { - t.Fatal("clearing x-agyn-secret was accepted") - } - if !strings.Contains(err.Error(), "readable") { - t.Fatalf("error does not explain the disclosure: %v", err) + if err := next.CheckCompatible(prev, never); err != nil { + t.Fatalf("clearing x-agyn-secret rejected: %v", err) } } diff --git a/internal/server/configuration_test.go b/internal/server/configuration_test.go index e0d8376..f0371fe 100644 --- a/internal/server/configuration_test.go +++ b/internal/server/configuration_test.go @@ -197,21 +197,20 @@ func (f resolverFunc) ResolveExists(ctx context.Context, kind string, id, organi return f(ctx, kind, id, organizationID) } -func TestGetInstallationOmitsSecretValues(t *testing.T) { +// 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{} - appID := uuid.New() - organizationID := uuid.New() installationID := uuid.New() - store.getFn = func(_ context.Context, id uuid.UUID) (storepkg.App, error) { - return storepkg.App{Meta: storepkg.EntityMeta{ID: id}, ConfigurationSchema: jsonMap(t, secretSchema)}, nil - } store.getInstallationFn = func(_ context.Context, _ uuid.UUID) (storepkg.Installation, error) { return storepkg.Installation{ Meta: storepkg.EntityMeta{ID: installationID}, - AppID: appID, - OrganizationID: organizationID, + AppID: uuid.New(), + OrganizationID: uuid.New(), Configuration: jsonMap(t, `{"bot_token":"123:secret","channel":"#ops"}`), }, nil } @@ -226,14 +225,8 @@ func TestGetInstallationOmitsSecretValues(t *testing.T) { t.Fatalf("unexpected error: %v", err) } fields := resp.GetInstallation().GetConfiguration().GetFields() - if _, present := fields["bot_token"]; present { - t.Fatal("secret value was returned on the admin read path") - } - if fields["channel"].GetStringValue() != "#ops" { - t.Fatalf("non-secret value was stripped: %v", fields) - } - if got := resp.GetInstallation().GetSecretKeysSet(); len(got) != 1 || got[0] != "bot_token" { - t.Fatalf("secret_keys_set = %v, want [bot_token]", got) + if fields["bot_token"].GetStringValue() != "123:secret" { + t.Fatalf("configuration did not round-trip whole: %v", fields) } } diff --git a/internal/server/converter.go b/internal/server/converter.go index 5a46cea..5de2c3d 100644 --- a/internal/server/converter.go +++ b/internal/server/converter.go @@ -4,7 +4,6 @@ import ( "fmt" appsv1 "github.com/agynio/apps/.gen/go/agynio/api/apps/v1" - "github.com/agynio/apps/internal/schema" "github.com/agynio/apps/internal/store" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" @@ -43,20 +42,8 @@ func toProtoApp(app store.App) *appsv1.App { return proto } -// toProtoInstallation renders an installation for a caller that is not the app. -// It takes the app's schema rather than looking it up so that redaction is a -// property of the conversion every read path goes through: a new read path -// cannot forget to redact, because it cannot build the message without deciding. -// -// appSchema is nil when the app has reported none, in which case nothing is -// marked secret and nothing is stripped. -func toProtoInstallation(installation store.Installation, appSchema *schema.Schema) (*appsv1.Installation, error) { - values := installation.Configuration - var secretKeysSet []string - if appSchema != nil { - values, secretKeysSet = appSchema.StripSecrets(values) - } - configuration, err := mapToProtoStruct(values) +func toProtoInstallation(installation store.Installation) (*appsv1.Installation, error) { + configuration, err := mapToProtoStruct(installation.Configuration) if err != nil { return nil, err } @@ -66,7 +53,6 @@ func toProtoInstallation(installation store.Installation, appSchema *schema.Sche OrganizationId: installation.OrganizationID.String(), Slug: installation.Slug, Configuration: configuration, - SecretKeysSet: secretKeysSet, } if installation.Status != nil { status := *installation.Status diff --git a/internal/server/server.go b/internal/server/server.go index 4e8f0a0..3543fa8 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -15,7 +15,6 @@ import ( groupsv1 "github.com/agynio/apps/.gen/go/agynio/api/groups/v1" identityv1 "github.com/agynio/apps/.gen/go/agynio/api/identity/v1" zitimanagementv1 "github.com/agynio/apps/.gen/go/agynio/api/ziti_management/v1" - "github.com/agynio/apps/internal/schema" "github.com/agynio/apps/internal/store" "github.com/google/uuid" "google.golang.org/grpc" @@ -503,7 +502,7 @@ func (s *Server) InstallApp(ctx context.Context, req *appsv1.InstallAppRequest) return nil, err } - protoInstallation, err := toProtoInstallation(installation, installSchema) + protoInstallation, err := toProtoInstallation(installation) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -526,11 +525,7 @@ func (s *Server) GetInstallation(ctx context.Context, req *appsv1.GetInstallatio if err := s.requireOrgMember(ctx, callerID, installation.OrganizationID); err != nil { return nil, err } - readSchema, err := s.installationSchema(ctx, installation.AppID) - if err != nil { - return nil, err - } - protoInstallation, err := toProtoInstallation(installation, readSchema) + protoInstallation, err := toProtoInstallation(installation) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -557,11 +552,7 @@ func (s *Server) GetInstallationBySlug(ctx context.Context, req *appsv1.GetInsta if err := s.requireOrgMember(ctx, callerID, installation.OrganizationID); err != nil { return nil, err } - readSchema, err := s.installationSchema(ctx, installation.AppID) - if err != nil { - return nil, err - } - protoInstallation, err := toProtoInstallation(installation, readSchema) + protoInstallation, err := toProtoInstallation(installation) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -616,9 +607,6 @@ func (s *Server) ListInstallations(ctx context.Context, req *appsv1.ListInstalla return nil, status.Errorf(codes.Internal, "list installations: %v", err) } protoInstallations := make([]*appsv1.Installation, 0, len(installations)) - // One schema lookup per distinct app rather than per installation: a list - // filtered by app or organization repeats the same few apps. - schemasByApp := make(map[uuid.UUID]*schema.Schema) orgAccess := map[uuid.UUID]bool{} for _, installation := range installations { if filter.OrganizationID == nil && !allowAppIdentity { @@ -635,15 +623,7 @@ func (s *Server) ListInstallations(ctx context.Context, req *appsv1.ListInstalla continue } } - listSchema, ok := schemasByApp[installation.AppID] - if !ok { - listSchema, err = s.installationSchema(ctx, installation.AppID) - if err != nil { - return nil, err - } - schemasByApp[installation.AppID] = listSchema - } - protoInstallation, err := toProtoInstallation(installation, listSchema) + protoInstallation, err := toProtoInstallation(installation) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -686,12 +666,6 @@ func (s *Server) UpdateInstallation(ctx context.Context, req *appsv1.UpdateInsta if configuration == nil { configuration = map[string]any{} } - if updateSchema != nil { - // A secret property the caller omitted keeps its stored value: the - // admin read path never returned it, so a round-trip cannot - // resubmit it. - configuration = updateSchema.MergeSecrets(configuration, installation.Configuration) - } if err := s.validateConfiguration(ctx, updateSchema, configuration, installation.OrganizationID); err != nil { return nil, err } @@ -702,7 +676,7 @@ func (s *Server) UpdateInstallation(ctx context.Context, req *appsv1.UpdateInsta if err != nil { return nil, toStatusError(err) } - protoInstallation, err := toProtoInstallation(installation, updateSchema) + protoInstallation, err := toProtoInstallation(installation) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } @@ -780,14 +754,7 @@ func (s *Server) ReportInstallationStatus(ctx context.Context, req *appsv1.Repor if err != nil { return nil, toStatusError(err) } - // Stripped here too: the app reads its own configuration through - // GetInstallationConfiguration, and keeping the rule on the message means - // no read path has to remember it. - statusSchema, err := s.installationSchema(ctx, installation.AppID) - if err != nil { - return nil, err - } - protoInstallation, err := toProtoInstallation(installation, statusSchema) + protoInstallation, err := toProtoInstallation(installation) if err != nil { return nil, status.Errorf(codes.Internal, "convert installation: %v", err) } diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 88e9ea1..61c4ca9 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -324,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 { From 307b1bf2c967837966055aa6b9c13fe528cfff34 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Sat, 12 Sep 2026 18:53:21 +0200 Subject: [PATCH 05/11] Reserve x-agyn-secret; mask with format: password The keyword is the right name for a property that names a Secret, which does not exist yet. Keeping it as a display hint would mean migrating every app that adopted it once it comes to mean something real, so it is rejected at report time with an error naming the alternative. format: password is standard JSON Schema and says only how to draw the field. It is the one honored format that validates nothing, so gaining it on an existing property is a compatible change where gaining uuid or email is not. --- internal/schema/compatibility.go | 9 +++- internal/schema/configuration.go | 3 +- internal/schema/schema.go | 35 ++++++++------- internal/schema/schema_test.go | 63 +++++++++++++++++---------- internal/server/configuration_test.go | 10 ++--- 5 files changed, 71 insertions(+), 49 deletions(-) diff --git a/internal/schema/compatibility.go b/internal/schema/compatibility.go index edc9ecb..bb5a687 100644 --- a/internal/schema/compatibility.go +++ b/internal/schema/compatibility.go @@ -69,7 +69,7 @@ func compareProperty(before, after *Property) error { if before.Pattern != after.Pattern && after.Pattern != "" { return fmt.Errorf("property %q narrowed its pattern", name) } - if before.Format != after.Format && after.Format != "" { + 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 { @@ -136,3 +136,10 @@ func compareFloatBound(name, key string, before, after *float64, lower bool) err } 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 index 0b0abcd..ebaa705 100644 --- a/internal/schema/configuration.go +++ b/internal/schema/configuration.go @@ -125,7 +125,8 @@ func (p *Property) validate(value any) error { func checkFormat(format, value string) error { switch format { - case "": + 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 { diff --git a/internal/schema/schema.go b/internal/schema/schema.go index bb5d79f..680851e 100644 --- a/internal/schema/schema.go +++ b/internal/schema/schema.go @@ -31,9 +31,19 @@ const ( ) var ( - validTypes = map[Type]struct{}{TypeString: {}, TypeInteger: {}, TypeNumber: {}, TypeBoolean: {}, TypeArray: {}} - validRefs = map[string]struct{}{RefAgent: {}, RefEnvironment: {}, RefModel: {}} - validFormats = map[string]struct{}{"uri": {}, "email": {}, "uuid": {}} + 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": {}, @@ -43,7 +53,7 @@ var ( "type": {}, "title": {}, "description": {}, "default": {}, "deprecated": {}, "enum": {}, "pattern": {}, "format": {}, "minLength": {}, "maxLength": {}, "minimum": {}, "maximum": {}, "minItems": {}, "maxItems": {}, "items": {}, - "x-agyn-secret": {}, "x-agyn-ref": {}, + "x-agyn-ref": {}, } ) @@ -65,7 +75,6 @@ type Property struct { Maximum *float64 MinItems *int MaxItems *int - Secret bool Ref string pattern *regexp.Regexp @@ -145,6 +154,9 @@ func Parse(doc map[string]any) (*Schema, error) { 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) } @@ -177,16 +189,6 @@ func parseProperty(name string, raw map[string]any) (*Property, error) { p.Default = raw["default"] p.Deprecated, _ = raw["deprecated"].(bool) - if v, ok := raw["x-agyn-secret"]; ok { - b, ok := v.(bool) - if !ok { - return nil, fmt.Errorf("property %q: x-agyn-secret must be a boolean", name) - } - if b && p.Type != TypeString { - return nil, fmt.Errorf("property %q: x-agyn-secret applies to string properties only", name) - } - p.Secret = b - } if v, ok := raw["x-agyn-ref"]; ok { ref, ok := v.(string) if !ok { @@ -200,9 +202,6 @@ func parseProperty(name string, raw map[string]any) (*Property, error) { } p.Ref = ref } - if p.Secret && p.Ref != "" { - return nil, fmt.Errorf("property %q cannot be both a secret and a reference", name) - } if v, ok := raw["enum"]; ok { list, ok := v.([]any) diff --git a/internal/schema/schema_test.go b/internal/schema/schema_test.go index f6f64b6..3307432 100644 --- a/internal/schema/schema_test.go +++ b/internal/schema/schema_test.go @@ -36,7 +36,7 @@ func config(t *testing.T, doc string) map[string]any { const telegram = `{ "type": "object", "properties": { - "bot_token": {"type": "string", "title": "Bot token", "x-agyn-secret": true}, + "bot_token": {"type": "string", "title": "Bot token", "format": "password"}, "agent_id": {"type": "string", "format": "uuid", "x-agyn-ref": "agent"} }, "required": ["bot_token", "agent_id"] @@ -44,19 +44,18 @@ const telegram = `{ 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"}}}`, - "secret on int": `{"type":"object","properties":{"a":{"type":"integer","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"]}`, - "secret and ref": `{"type":"object","properties":{"a":{"type":"string","x-agyn-secret":true,"x-agyn-ref":"agent"}}}`, + "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) { @@ -69,8 +68,8 @@ func TestParseRejectsOutsideTheHonoredSubset(t *testing.T) { func TestParseAcceptsTheTelegramSchema(t *testing.T) { s := mustParse(t, telegram) - if !s.Properties["bot_token"].Secret { - t.Fatal("bot_token should carry the x-agyn-secret marker") + 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 { @@ -149,7 +148,7 @@ func TestCheckCompatibleAllowsWidening(t *testing.T) { "a":{"type":"string","minLength":2,"enum":["xa","xb","xc"]}, "b":{"type":"integer","minimum":1}, "c":{"type":"string","title":"new and optional"}, - "d":{"type":"string","x-agyn-secret":true} + "d":{"type":"string","format":"password"} }, "required":["a","b","d"] }`) @@ -180,14 +179,30 @@ func TestCheckCompatibleRejectsNarrowing(t *testing.T) { } } -// Clearing x-agyn-secret is a display change, not a narrowing: the value was -// never withheld from the wire, so nothing stops validating and nothing is -// disclosed that was not already returned. -func TestCheckCompatibleAllowsClearingSecret(t *testing.T) { - prev := mustParse(t, `{"type":"object","properties":{"t":{"type":"string","x-agyn-secret":true}}}`) - next := mustParse(t, `{"type":"object","properties":{"t":{"type":"string"}}}`) +// 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("clearing x-agyn-secret rejected: %v", err) + 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) } } diff --git a/internal/server/configuration_test.go b/internal/server/configuration_test.go index f0371fe..1282789 100644 --- a/internal/server/configuration_test.go +++ b/internal/server/configuration_test.go @@ -34,10 +34,10 @@ func jsonStruct(t *testing.T, doc string) *structpb.Struct { return value } -const secretSchema = `{ +const maskedSchema = `{ "type": "object", "properties": { - "bot_token": {"type": "string", "x-agyn-secret": true}, + "bot_token": {"type": "string", "format": "password"}, "channel": {"type": "string"} }, "required": ["bot_token"] @@ -80,7 +80,7 @@ func TestReportConfigurationSchemaStoresFirstReport(t *testing.T) { _, err := srv.ReportConfigurationSchema(ctx, &appsv1.ReportConfigurationSchemaRequest{ AppId: appID.String(), - ConfigurationSchema: jsonStruct(t, secretSchema), + ConfigurationSchema: jsonStruct(t, maskedSchema), }) if err != nil { t.Fatalf("first report rejected: %v", err) @@ -107,7 +107,7 @@ func TestReportConfigurationSchemaRejectsOutsideSubset(t *testing.T) { } func TestReportConfigurationSchemaRejectsIncompatibleAndKeepsPrevious(t *testing.T) { - store, appID, _, ctx := reportingApp(t, secretSchema) + store, appID, _, ctx := reportingApp(t, maskedSchema) srv := newServer(store) // Drops bot_token and adds a compatible property in the same document. @@ -135,7 +135,7 @@ func TestReportConfigurationSchemaRequiresOwnIdentity(t *testing.T) { _, err := srv.ReportConfigurationSchema(ctx, &appsv1.ReportConfigurationSchemaRequest{ AppId: appID.String(), - ConfigurationSchema: jsonStruct(t, secretSchema), + ConfigurationSchema: jsonStruct(t, maskedSchema), }) if status.Code(err) != codes.PermissionDenied { t.Fatalf("want PermissionDenied, got %v", err) From 6a7d423ebb1c606f9c0b4138cee8118840356f64 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Sat, 12 Sep 2026 19:06:09 +0200 Subject: [PATCH 06/11] Treat an inexpressible stored schema as absent, not as an error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reserving x-agyn-secret made every schema already stored with it unparseable, and appSchema returned an error for that — which stranded the app completely: every report was rejected for the state of the schema it was trying to replace, and every installation write failed against a schema nobody could evaluate. A stored schema that no longer parses was valid when written, so the subset has tightened underneath it. It is treated as absent and logged. The compatibility guarantee lapses for that one transition, which is the price of ever narrowing the subset — and far cheaper than an app that can never report again. --- internal/server/configuration.go | 16 ++++++++++++---- internal/server/configuration_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/internal/server/configuration.go b/internal/server/configuration.go index 85d2680..60c5dbc 100644 --- a/internal/server/configuration.go +++ b/internal/server/configuration.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "log" appsv1 "github.com/agynio/apps/.gen/go/agynio/api/apps/v1" "github.com/agynio/apps/internal/schema" @@ -21,16 +22,23 @@ type ReferenceResolver interface { } // appSchema parses the schema the app reported, or returns nil when it has -// reported none. A stored schema that no longer parses is an internal -// inconsistency: it was validated against the honored subset when it was -// written. +// 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 { - return nil, status.Errorf(codes.Internal, "stored configuration schema for app %s does not parse: %v", app.Meta.ID, err) + 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 } diff --git a/internal/server/configuration_test.go b/internal/server/configuration_test.go index 1282789..c92b73d 100644 --- a/internal/server/configuration_test.go +++ b/internal/server/configuration_test.go @@ -238,3 +238,27 @@ func mustServerSchema(t *testing.T, doc string) *schema.Schema { } 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") + } +} From cb41069b8dae9c319069168cc4686233e95cddf8 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Sun, 13 Sep 2026 13:38:46 +0200 Subject: [PATCH 07/11] Keep the local build scaffolding out of the repo Dockerfile.localtest builds against protos generated on the host, because the api module carrying them is not published yet. It is a stopgap for testing on the local VM, not something the repo should ship. --- .gitignore | 2 ++ Dockerfile.localtest | 45 -------------------------------------------- 2 files changed, 2 insertions(+), 45 deletions(-) delete mode 100644 Dockerfile.localtest 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.localtest b/Dockerfile.localtest deleted file mode 100644 index 71004bb..0000000 --- a/Dockerfile.localtest +++ /dev/null @@ -1,45 +0,0 @@ -# syntax=docker/dockerfile:1.8 -ARG GO_VERSION=1.25 -ARG BUF_VERSION=1.66.0 - -FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS buf -ARG BUF_VERSION -RUN apk add --no-cache curl -RUN curl -sSL \ - "https://github.com/bufbuild/buf/releases/download/v${BUF_VERSION}/buf-$(uname -s)-$(uname -m)" \ - -o /usr/local/bin/buf && \ - chmod +x /usr/local/bin/buf - -FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS build - -WORKDIR /src - -COPY --from=buf /usr/local/bin/buf /usr/local/bin/buf - -COPY go.mod go.sum ./ -RUN --mount=type=cache,target=/go/pkg/mod \ - --mount=type=cache,target=/root/.cache/go-build \ - go mod download - -COPY .gen ./.gen - -COPY . . - -ARG TARGETOS TARGETARCH -ENV CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH - -RUN --mount=type=cache,target=/go/pkg/mod \ - --mount=type=cache,target=/root/.cache/go-build \ - go build -trimpath -ldflags "-s -w" -o /out/apps ./cmd/apps-service - -FROM alpine:3.21 AS runtime - -WORKDIR /app - -COPY --from=build /out/apps /app/apps - -RUN addgroup -g 10001 -S app && adduser -u 10001 -S app -G app - -USER 10001 - -ENTRYPOINT ["/app/apps"] From a0028081349652194790e09e594ca53236202fc1 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Mon, 14 Sep 2026 14:29:37 +0200 Subject: [PATCH 08/11] Generate the agents and llm protos the reference resolver needs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The generate step lists proto paths explicitly, and resolving an x-agyn-ref means calling Agents and LLM — so the build found no package for either. It passed locally only because those protos had been generated by hand while the api module was unpublished. --- Dockerfile | 4 +++- buf.gen.yaml | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 9b1de5a..fb27af3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,7 +27,9 @@ RUN buf generate buf.build/agynio/api \ --path agynio/api/authorization/v1 \ --path agynio/api/identity/v1 \ --path agynio/api/ziti_management/v1 \ - --path agynio/api/groups/v1 + --path agynio/api/groups/v1 \ + --path agynio/api/agents/v1 \ + --path agynio/api/llm/v1 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 From 28b149b666bf3215c7258fa80d77dbfc3083e1c0 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 15 Sep 2026 16:08:35 +0200 Subject: [PATCH 09/11] Generate from one list of proto paths, not three MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The paths were spelled out in buf.gen.yaml, the Dockerfile, and devspace.yaml. Adding agents and llm to the first two left e2e building from the third, which still had the old list — so the service failed to compile in-cluster and the run timed out waiting for it to become healthy. The Dockerfile and devspace now run plain `buf generate`, which takes the module and paths from buf.gen.yaml, the way CI already did. --- Dockerfile | 10 ++-------- devspace.yaml | 7 +------ 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/Dockerfile b/Dockerfile index fb27af3..aeddf5a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -22,14 +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 \ - --path agynio/api/agents/v1 \ - --path agynio/api/llm/v1 +# The module and paths come from buf.gen.yaml, so the list lives in one place. +RUN buf generate COPY . . diff --git a/devspace.yaml b/devspace.yaml index df4c5cd..dadb232 100644 --- a/devspace.yaml +++ b/devspace.yaml @@ -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..." From 29f19f5fa71e584fcbfeb2f69085ece690594af9 Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 15 Sep 2026 16:51:45 +0200 Subject: [PATCH 10/11] Provision e2e from the bundle VM, not from bootstrap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The run provisioned with agynio/bootstrap, which no longer leaves a Gateway token behind, so every run died at "AGYN_API_TOKEN is not set" before a single test ran. Bootstrap is the deprecated install path; the platform installs from the umbrella chart onto the prebuilt VM now, and agents, gateway and console-app already provision that way — console-app's e2e is green on it. Also picks up what those workflows carry and this one lacked: a concurrency group so a new push cancels the previous run, a 60 minute timeout, and packages: read. --- .github/workflows/e2e.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) 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 From b717723d1e67821574e923c1ee0e252860ae8fde Mon Sep 17 00:00:00 2001 From: Vitalii Valkov Date: Tue, 15 Sep 2026 17:04:41 +0200 Subject: [PATCH 11/11] Deploy into agyn-platform, the namespace the VM installs into The deploy died on 'namespaces "platform" not found'. That name came from bootstrap, which built the cluster itself; the platform VM installs the umbrella chart into agyn-platform, which is what agents already targets. --- devspace.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/devspace.yaml b/devspace.yaml index dadb232..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: |-