diff --git a/cli/internal/daemon/boundary_regression_test.go b/cli/internal/daemon/boundary_regression_test.go index bb4c57657..ef38cade5 100644 --- a/cli/internal/daemon/boundary_regression_test.go +++ b/cli/internal/daemon/boundary_regression_test.go @@ -3,6 +3,7 @@ package daemon import ( + "albedo/cli/internal/daemon/protocol" "context" "encoding/json" "errors" @@ -117,3 +118,35 @@ func TestSessionReadValidatesRequiredAndNullableMembers(t *testing.T) { }) } } + +func TestSessionChangeRejectsMissingNestedMembers(t *testing.T) { + for _, valid := range []bool{true, false} { + session := canonicalSession("s", generationA, 0) + if !valid { + delete(session["kernel"].(map[string]any), "live_job_count") + } + payload, err := json.Marshal(map[string]any{"session": session, "resource": session["configuration_resource"], "move": nil}) + if err != nil { + t.Fatal(err) + } + var change protocol.SessionChange + err = decodeRequired(payload, &change) + if (err == nil) != valid { + t.Fatalf("nested session validation valid=%v: %v", valid, err) + } + } +} + +func TestModelPagingRejectsRepeatedTokens(t *testing.T) { + calls := 0 + conn := controlledConnection(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + if calls == 1 && r.URL.Query().Get("next") != "" || calls == 2 && r.URL.Query().Get("next") != "same" { + t.Errorf("wrong cursor at page %d: %s", calls, r.URL) + } + _, _ = fmt.Fprint(w, `{"items":[],"next":"same"}`) + }) + if _, err := ListModels(t.Context(), conn, "provider", ""); err == nil || calls != 2 { + t.Fatalf("repeated cursor accepted: calls=%d, error=%v", calls, err) + } +} diff --git a/cli/internal/daemon/extensions.go b/cli/internal/daemon/extensions.go index b1cd79202..510604462 100644 --- a/cli/internal/daemon/extensions.go +++ b/cli/internal/daemon/extensions.go @@ -51,9 +51,10 @@ func ListExtensions(ctx context.Context, conn *Connection, session string) ([]Ex } func SelectExtension(ctx context.Context, conn *Connection, session string, request ExtensionSelectionRequest) ([]ExtensionSummary, error) { if request.Scope == "global" { - _, err := patchSettingsGroup[protocol.ExtensionSettings](ctx, conn, "extensions", request.ETag, struct { + var change protocol.ExtensionSettingsChange + err := patchSettingsGroup(ctx, conn, "extensions", request.ETag, struct { Defaults map[string]*bool `json:"defaults"` - }{map[string]*bool{request.Name: request.Enabled}}) + }{map[string]*bool{request.Name: request.Enabled}}, &change) if err != nil { return nil, err } diff --git a/cli/internal/daemon/models.go b/cli/internal/daemon/models.go index 2d8ad8e9c..09b3ef149 100644 --- a/cli/internal/daemon/models.go +++ b/cli/internal/daemon/models.go @@ -100,7 +100,8 @@ func ChangeModel(ctx context.Context, conn *Connection, id string, request Model return selection, err } if request.MakeDefault { - change, saveErr := patchSettingsGroup[protocol.ProviderSettings](ctx, conn, "providers", request.DefaultETag, map[string]any{"default_profile": selection.Provider, "profiles": map[string]any{selection.Provider: map[string]any{"model": selection.Model, "effort": optionalString(selection.Effort)}}}) + var change protocol.ProviderSettingsChange + saveErr := patchSettingsGroup(ctx, conn, "providers", request.DefaultETag, map[string]any{"default_profile": selection.Provider, "profiles": map[string]any{selection.Provider: map[string]any{"model": selection.Model, "effort": optionalText(selection.Effort)}}}, &change) selection.DefaultETag = change.Resource.ETag if saveErr != nil { return selection, fmt.Errorf("switched session; saving the default model: %w", saveErr) @@ -112,7 +113,8 @@ func SetModelContextCap(ctx context.Context, conn *Connection, request ModelCont if request.CapKey == "" { return "", fieldError("model cap key") } - change, err := patchSettingsGroup[protocol.ModelSettings](ctx, conn, "models", request.ETag, map[string]any{"raised_caps": map[string]bool{request.CapKey: request.Enabled}}) + var change protocol.ModelSettingsChange + err := patchSettingsGroup(ctx, conn, "models", request.ETag, map[string]any{"raised_caps": map[string]bool{request.CapKey: request.Enabled}}, &change) return change.Resource.ETag, err } func ReadEffort(ctx context.Context, conn *Connection, session Session) (EffortResult, error) { @@ -134,7 +136,7 @@ func ReadEffort(ctx context.Context, conn *Connection, session Session) (EffortR // SelectEffort clears the preference when effort is empty. func SelectEffort(ctx context.Context, conn *Connection, session Session, effort string) (EffortResult, error) { - result, err := patchSession(ctx, conn, session.ID, session.ETag, map[string]any{"effort": optionalString(effort)}) + result, err := patchSession(ctx, conn, session.ID, session.ETag, map[string]any{"effort": optionalText(effort)}) return EffortResult{Effort: result.Effort, Message: "Effort saved.", ETag: result.ETag}, err } diff --git a/cli/internal/daemon/server.go b/cli/internal/daemon/server.go index 5d1d237ad..23310ccb0 100644 --- a/cli/internal/daemon/server.go +++ b/cli/internal/daemon/server.go @@ -123,7 +123,8 @@ func noticeValues(rows []struct { return result } func DismissServerNotices(ctx context.Context, conn *Connection, etag string, ids []string) error { - _, err := patchSettingsGroup[protocol.UISettings](ctx, conn, "ui", etag, map[string]any{"dismissed_notices": ids}) + var change protocol.UISettingsChange + err := patchSettingsGroup(ctx, conn, "ui", etag, map[string]any{"dismissed_notices": ids}, &change) return err } diff --git a/cli/internal/daemon/sessions.go b/cli/internal/daemon/sessions.go index 6f0e03ada..c79c0beef 100644 --- a/cli/internal/daemon/sessions.go +++ b/cli/internal/daemon/sessions.go @@ -178,9 +178,7 @@ func patchSession(ctx context.Context, conn *Connection, id, etag string, body a return result, err } func RenameSession(ctx context.Context, conn *Connection, id, name, etag string) (Session, error) { - return patchSession(ctx, conn, id, etag, struct { - Name string `json:"name"` - }{name}) + return patchSession(ctx, conn, id, etag, protocol.SessionPatch{Name: &name}) } func ForkSession(ctx context.Context, conn *Connection, id string, body ForkRequest) (Session, error) { return CreateSession(ctx, conn, CreateSessionRequest{Kind: "fork", SourceSessionID: id, CheckpointID: body.Checkpoint}) diff --git a/cli/internal/daemon/settings.go b/cli/internal/daemon/settings.go index 7a3ae0409..8281a8076 100644 --- a/cli/internal/daemon/settings.go +++ b/cli/internal/daemon/settings.go @@ -5,13 +5,12 @@ import ( "errors" "io" "net/http" - "reflect" "albedo/cli/internal/config" "albedo/cli/internal/daemon/protocol" ) -type ReloadResult struct{ Reloaded, Message, Warning string } +type ReloadResult struct{ Message, Warning string } type UIPreferencesPatch struct { Thinking *bool `json:"thinking,omitempty"` Tools *bool `json:"tools,omitempty"` @@ -86,37 +85,43 @@ func ProviderProfiles(ctx context.Context, conn *Connection) (config.Profiles, e return settings.Profiles, err } -type settingsChange[T any] struct { - Group string `json:"group"` - Resource struct { - URL string `json:"url"` - ETag string `json:"etag"` - Value T `json:"value"` - } `json:"resource"` - Application protocol.SettingsApplication `json:"application"` -} - -func patchSettingsGroup[T any](ctx context.Context, conn *Connection, group, etag string, body any) (settingsChange[T], error) { - var result settingsChange[T] +func patchSettingsGroup(ctx context.Context, conn *Connection, group, etag string, body any, target any) error { headers, err := observedHeaders(etag) if err != nil { - return result, err + return err } - err = executeMutation(ctx, conn, operation{Name: "edit " + group + " settings", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { - return protocol.NewPatchSettingsRequestWithBody(base, &protocol.PatchSettingsParams{Group: group, IfMatch: headers.Get("If-Match")}, "application/merge-patch+json", body) + return executeMutation(ctx, conn, operation{Name: "edit " + group + " settings", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { + return protocol.NewPatchSettingsRequestWithBody(base, &protocol.PatchSettingsParams{Group: group, IfMatch: etag}, "application/merge-patch+json", body) }, Headers: headers, Body: body, Policy: authRecovery}, []int{200}, func(data []byte, _ int) error { - if err := decodeRequired(data, &result, "group", "resource", "application"); err != nil { + if err := decodeRequired(data, target); err != nil { return err } - if err := validateWireJSON(data, reflect.TypeFor[settingsChange[T]]()); err != nil { + var savedGroup, savedURL, savedETag string + switch change := target.(type) { + case *protocol.ProviderSettingsChange: + savedGroup, savedURL, savedETag = change.Group, change.Resource.URL, change.Resource.ETag + case *protocol.CapabilitySettingsChange: + savedGroup, savedURL, savedETag = change.Group, change.Resource.URL, change.Resource.ETag + case *protocol.MCPSettingsChange: + savedGroup, savedURL, savedETag = change.Group, change.Resource.URL, change.Resource.ETag + case *protocol.ExtensionSettingsChange: + savedGroup, savedURL, savedETag = change.Group, change.Resource.URL, change.Resource.ETag + case *protocol.ModelSettingsChange: + savedGroup, savedURL, savedETag = change.Group, change.Resource.URL, change.Resource.ETag + case *protocol.UISettingsChange: + savedGroup, savedURL, savedETag = change.Group, change.Resource.URL, change.Resource.ETag + default: + return fieldError("settings group") + } + request, err := protocol.NewGetSettingsRequest("", &protocol.GetSettingsParams{Group: &group}) + if err != nil { return err } - if result.Group != group || result.Resource.ETag == "" || result.Resource.URL != "/settings?group="+group { + if savedGroup != group || savedETag == "" || savedURL != request.URL.RequestURI() { return fieldError("settings resource") } return nil }) - return result, err } func SaveProvider(ctx context.Context, conn *Connection, name string, profile config.Settings, etag string) error { return saveProvider(ctx, conn, name, profile, etag, false) @@ -125,28 +130,22 @@ func SaveAndSelectProvider(ctx context.Context, conn *Connection, name string, p return saveProvider(ctx, conn, name, profile, etag, true) } func saveProvider(ctx context.Context, conn *Connection, name string, profile config.Settings, etag string, selectDefault bool) error { - type profilePatch struct { - Extension string `json:"extension"` - Endpoint *string `json:"endpoint"` - Protocol string `json:"protocol"` - Model string `json:"model"` - Effort *string `json:"effort"` - ImageEdge *int `json:"image_edge"` - AccountID *string `json:"account_id"` - APIKey string `json:"api_key,omitempty"` + // Nullable patch fields must be emitted to clear saved overrides. Generated + // optional pointers omit nil and would preserve those overrides instead. + profilePatch := map[string]any{ + "extension": profile.Extension, "endpoint": optionalText(profile.BaseURL), + "protocol": profile.Protocol, "model": profile.Model, "effort": profile.Effort, + "image_edge": profile.ImageEdge, "account_id": profile.AccountID, } - var endpoint *string - if profile.BaseURL != "" { - endpoint = &profile.BaseURL + if profile.APIKey != "" { + profilePatch["api_key"] = profile.APIKey } - body := struct { - Profiles map[string]profilePatch `json:"profiles"` - DefaultProfile *string `json:"default_profile,omitempty"` - }{Profiles: map[string]profilePatch{name: {profile.Extension, endpoint, profile.Protocol, profile.Model, profile.Effort, profile.ImageEdge, profile.AccountID, profile.APIKey}}} + body := map[string]any{"profiles": map[string]any{name: profilePatch}} if selectDefault { - body.DefaultProfile = &name + body["default_profile"] = name } - _, err := patchSettingsGroup[protocol.ProviderSettings](ctx, conn, "providers", etag, body) + var change protocol.ProviderSettingsChange + err := patchSettingsGroup(ctx, conn, "providers", etag, body, &change) return err } func DeleteProvider(ctx context.Context, conn *Connection, name string, profiles config.Profiles) error { @@ -154,7 +153,8 @@ func DeleteProvider(ctx context.Context, conn *Connection, name string, profiles if profiles.Active == name { body["default_profile"] = nil } - _, err := patchSettingsGroup[protocol.ProviderSettings](ctx, conn, "providers", profiles.ETag, body) + var change protocol.ProviderSettingsChange + err := patchSettingsGroup(ctx, conn, "providers", profiles.ETag, body, &change) return err } @@ -168,11 +168,10 @@ func SetCapability(ctx context.Context, conn *Connection, session string, reques } func setSelection(ctx context.Context, conn *Connection, session, kind, id, revision, scope, etag string, enabled *bool) (ReloadResult, error) { if scope == "global" { - _, err := patchSettingsGroup[protocol.CapabilitySettings](ctx, conn, "capabilities", etag, struct { - SessionID string `json:"catalog_session_id"` - Revision string `json:"catalog_revision"` - Choices map[string]*bool `json:"choices"` - }{session, revision, map[string]*bool{id: enabled}}) + var change protocol.CapabilitySettingsChange + err := patchSettingsGroup(ctx, conn, "capabilities", etag, protocol.CapabilitySettingsPatch{ + CatalogSessionID: session, CatalogRevision: revision, Choices: map[string]*bool{id: enabled}, + }, &change) return ReloadResult{Message: "Saved the global default; reload open sessions to apply it."}, err } body := map[string]any{"selection": map[string]any{kind: map[string]*bool{id: enabled}}} @@ -209,34 +208,31 @@ func SaveMCP(ctx context.Context, conn *Connection, session string, request MCPU secrets.Env[name] = nil } } - definition = struct { - Enabled bool `json:"enabled"` - Transport string `json:"transport"` - Command *string `json:"command"` - Arguments []string `json:"arguments"` - CWD *string `json:"cwd"` - URL *string `json:"url"` - Environment map[string]map[string]string `json:"environment"` - Headers map[string]map[string]string `json:"headers"` - BearerTokenEnvVar *string `json:"bearer_token_env_var"` - EnabledTools []string `json:"enabled_tools"` - DisabledTools []string `json:"disabled_tools"` - StartupTimeout int `json:"startup_timeout_ms,omitempty"` - CallTimeout int `json:"call_timeout_ms,omitempty"` - Secrets MCPSecretsPatch `json:"secrets"` - }{Enabled: server.Enabled == nil || *server.Enabled, Transport: server.Type, Command: optionalString(server.Command), Arguments: nonNil(server.Args), CWD: optionalString(server.CWD), URL: optionalString(server.URL), Environment: nonNilMap(server.Env), Headers: nonNilMap(server.Headers), BearerTokenEnvVar: optionalString(server.BearerTokenEnvVar), EnabledTools: nonNil(server.EnabledTools), DisabledTools: nonNil(server.DisabledTools), StartupTimeout: server.StartupTimeoutMs, CallTimeout: server.CallTimeoutMs, Secrets: secrets} + // These nulls clear fields when changing transports; nil optional + // pointers in MCPDefinitionPatch would omit them. + patch := map[string]any{ + "enabled": server.Enabled == nil || *server.Enabled, "transport": server.Type, + "command": optionalText(server.Command), "arguments": nonNil(server.Args), + "cwd": optionalText(server.CWD), "url": optionalText(server.URL), + "environment": nonNilMap(server.Env), "headers": nonNilMap(server.Headers), + "bearer_token_env_var": optionalText(server.BearerTokenEnvVar), + "enabled_tools": nonNil(server.EnabledTools), "disabled_tools": nonNil(server.DisabledTools), + "secrets": secrets, + } + if server.StartupTimeoutMs != 0 { + patch["startup_timeout_ms"] = server.StartupTimeoutMs + } + if server.CallTimeoutMs != 0 { + patch["call_timeout_ms"] = server.CallTimeoutMs + } + definition = patch } - change, err := patchSettingsGroup[protocol.MCPSettings](ctx, conn, "mcp", request.ETag, struct { - Definitions map[string]any `json:"definitions"` - }{map[string]any{request.Name: definition}}) + var change protocol.MCPSettingsChange + err := patchSettingsGroup(ctx, conn, "mcp", request.ETag, map[string]any{ + "definitions": map[string]any{request.Name: definition}, + }, &change) return applicationResult(change.Application), err } -func optionalString(s string) *string { - if s == "" { - return nil - } - return &s -} func nonNil[T any](s []T) []T { if s == nil { return []T{} @@ -266,20 +262,15 @@ func PatchUI(ctx context.Context, conn *Connection, patch UIPreferencesPatch) (U if patch.Pinned != nil || patch.Archived != nil { return UIPreferences{}, errors.New("pin and archive are session preferences") } - change, err := patchSettingsGroup[protocol.UISettings](ctx, conn, "ui", patch.ETag, patch) + var change protocol.UISettingsChange + err := patchSettingsGroup(ctx, conn, "ui", patch.ETag, patch, &change) return UIPreferences{Thinking: change.Resource.Value.Thinking, Tools: change.Resource.Value.Tools, ETag: change.Resource.ETag}, err } func PatchSessionUI(ctx context.Context, conn *Connection, session string, patch UIPreferencesPatch) (UIPreferences, error) { if patch.Thinking != nil || patch.Tools != nil { return UIPreferences{}, errors.New("thinking and tools are shared preferences") } - body := struct { - Preferences struct { - Pinned *bool `json:"pinned,omitempty"` - Archived *bool `json:"archived,omitempty"` - } `json:"preferences"` - }{} - body.Preferences.Pinned, body.Preferences.Archived = patch.Pinned, patch.Archived + body := protocol.SessionPatch{Preferences: &protocol.PreferencePatch{Pinned: patch.Pinned, Archived: patch.Archived}} updated, err := patchSession(ctx, conn, session, patch.ETag, body) prefs := UIPreferences{SessionETags: map[string]string{session: updated.ETag}} if updated.Pinned { diff --git a/cli/internal/daemon/webhooks.go b/cli/internal/daemon/webhooks.go index 54df2ca83..dce1457de 100644 --- a/cli/internal/daemon/webhooks.go +++ b/cli/internal/daemon/webhooks.go @@ -29,20 +29,8 @@ type WebhookPermission struct { SessionID, ETag string AgentManagement bool } -type WebhookCreateRequest struct { - SessionID string `json:"session_id"` - Name string `json:"name"` - Secret string `json:"secret,omitempty"` - Header string `json:"signature_header,omitempty"` - Prefix *string `json:"signature_prefix,omitempty"` - Enabled *bool `json:"enabled,omitempty"` -} -type WebhookPatch struct { - Name *string `json:"name,omitempty"` - Header *string `json:"signature_header,omitempty"` - Prefix *string `json:"signature_prefix,omitempty"` - Enabled *bool `json:"enabled,omitempty"` -} +type WebhookCreateRequest = protocol.HookCreate +type WebhookPatch = protocol.HookPatch type WebhookAction string const ( @@ -63,7 +51,6 @@ type WebhookRequest struct { } var webhookNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) -var webhookHeaderPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`) func hookValue(w protocol.HookConfigurationResource, deliveryURL string) Webhook { c := w.Value @@ -139,7 +126,7 @@ func CreateWebhook(ctx context.Context, conn *Connection, request WebhookCreateR return nil, errors.New("webhook creation requires a session and a valid name") } return hookChange(ctx, conn, operation{Name: "create webhook", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { - return protocol.NewCreateHookRequestWithBody(base, "application/json", body) + return protocol.NewCreateHookRequest(base, request) }, Body: request, Policy: noRecovery}, 201, true) } func EditWebhook(ctx context.Context, conn *Connection, id, etag string, patch WebhookPatch) (*WebhookResult, error) { @@ -148,7 +135,7 @@ func EditWebhook(ctx context.Context, conn *Connection, id, etag string, patch W return nil, err } return hookChange(ctx, conn, operation{Name: "edit webhook", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { - return protocol.NewPatchHookRequestWithBody(base, id, &protocol.PatchHookParams{View: "configuration", IfMatch: etag}, "application/merge-patch+json", body) + return protocol.NewPatchHookRequestWithApplicationMergePatchPlusJSONBody(base, id, &protocol.PatchHookParams{View: "configuration", IfMatch: etag}, patch) }, Headers: headers, Body: patch, Policy: noRecovery}, 200, false) } func RotateWebhookSecret(ctx context.Context, conn *Connection, id, etag, secret string) (*WebhookResult, error) { diff --git a/cli/internal/daemon/wire_helpers.go b/cli/internal/daemon/wire_helpers.go index 6b98cde00..7fe0e9326 100644 --- a/cli/internal/daemon/wire_helpers.go +++ b/cli/internal/daemon/wire_helpers.go @@ -1,6 +1,7 @@ package daemon import ( + "bytes" "encoding/json" "errors" "net/http" @@ -49,95 +50,99 @@ func observedHeaders(etag string) (http.Header, error) { return http.Header{"If-Match": {etag}, "Content-Type": {"application/merge-patch+json"}}, nil } func decodeRequired(data []byte, target any, names ...string) error { - fields, err := object(data) - if err != nil { - return err - } - for _, name := range names { - if _, ok := fields[name]; !ok { - return fieldError(name) - } + data = bytes.TrimSpace(data) + if len(data) == 0 || data[0] != '{' { + return fieldError("object") } - targetType := reflect.TypeOf(target) - if targetType.Kind() == reflect.Pointer { - targetType = targetType.Elem() - } - if targetType.PkgPath() == reflect.TypeFor[protocol.Session]().PkgPath() { - if err := validateWireFields(fields, targetType); err != nil { + kind := reflect.TypeOf(target).Elem() + generated := kind.PkgPath() == reflect.TypeFor[protocol.Session]().PkgPath() + if generated || len(names) > 0 { + var tree any + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + if err := decoder.Decode(&tree); err != nil { return err } + fields, ok := tree.(map[string]any) + if !ok { + return fieldError("object") + } + for _, name := range names { + if _, ok := fields[name]; !ok { + return fieldError(name) + } + } + if generated { + if err := validateWireValue(tree, kind); err != nil { + return err + } + } } return json.Unmarshal(data, target) } -// Required wire members must be present, and JSON null cannot masquerade as a -// scalar zero value. Generated field tags distinguish nullable from optional. -func validateWireJSON(data []byte, kind reflect.Type) error { +// Validate one parsed tree so nested required members and nulls never become +// Go zero values. Raw unions are decoded by their discriminated adapters. +func validateWireValue(value any, kind reflect.Type) error { if kind == reflect.TypeFor[json.RawMessage]() { return nil } if kind.Kind() == reflect.Pointer { - if string(data) == "null" { + if value == nil { return nil } - return validateWireJSON(data, kind.Elem()) + return validateWireValue(value, kind.Elem()) } - if string(data) == "null" { + if value == nil { return fieldError("null " + kind.String()) } switch kind.Kind() { case reflect.Struct: - fields, err := object(data) - if err != nil { - return err + fields, ok := value.(map[string]any) + if !ok { + return fieldError("object") + } + for field := range kind.Fields() { + name, options, _ := strings.Cut(field.Tag.Get("json"), ",") + if name == "" || name == "-" { + continue + } + child, present := fields[name] + if !present { + if !strings.Contains(options, "omitempty") { + return fieldError(name) + } + continue + } + if child == nil && field.Type != reflect.TypeFor[json.RawMessage]() { + if field.Tag.Get("nullable") != "true" { + return fieldError(name) + } + continue + } + if err := validateWireValue(child, field.Type); err != nil { + return fmtField(name, err) + } } - return validateWireFields(fields, kind) case reflect.Slice: - var items []json.RawMessage - if err := json.Unmarshal(data, &items); err != nil { - return err + items, ok := value.([]any) + if !ok { + return fieldError("array") } for _, item := range items { - if err := validateWireJSON(item, kind.Elem()); err != nil { + if err := validateWireValue(item, kind.Elem()); err != nil { return err } } case reflect.Map: - fields, err := object(data) - if err != nil { - return err - } - for _, raw := range fields { - if err := validateWireJSON(raw, kind.Elem()); err != nil { - return err - } - } - } - return nil -} - -func validateWireFields(fields map[string]json.RawMessage, kind reflect.Type) error { - for i := range kind.NumField() { - field := kind.Field(i) - name, options, _ := strings.Cut(field.Tag.Get("json"), ",") - if name == "" || name == "-" { - continue - } - raw, ok := fields[name] + fields, ok := value.(map[string]any) if !ok { - if !strings.Contains(options, "omitempty") { - return fieldError(name) - } - continue + return fieldError("object") } - if string(raw) == "null" && field.Type != reflect.TypeFor[json.RawMessage]() { - if field.Tag.Get("nullable") != "true" { - return fieldError(name) + for _, child := range fields { + if err := validateWireValue(child, kind.Elem()); err != nil { + return err } - continue - } - if err := validateWireJSON(raw, field.Type); err != nil { - return fmtField(name, err) } } return nil diff --git a/cli/internal/tui/webhooks_page.go b/cli/internal/tui/webhooks_page.go index 7a74328ca..06ddbad58 100644 --- a/cli/internal/tui/webhooks_page.go +++ b/cli/internal/tui/webhooks_page.go @@ -162,9 +162,9 @@ func (m WebhooksPageModel) save(gen int, notice string, steps ...daemon.WebhookR var err error switch step.Action { case daemon.WebhookCreate: - res, err = daemon.CreateWebhook(context.Background(), m.Conn, daemon.WebhookCreateRequest{SessionID: step.SessionID, Name: step.Name, Secret: step.Secret, Header: step.Header, Prefix: &step.Prefix}) + res, err = daemon.CreateWebhook(context.Background(), m.Conn, daemon.WebhookCreateRequest{SessionID: step.SessionID, Name: step.Name, Secret: optionalWebhookText(step.Secret), SignatureHeader: optionalWebhookText(step.Header), SignaturePrefix: &step.Prefix}) case daemon.WebhookSignature: - res, err = daemon.EditWebhook(context.Background(), m.Conn, step.HookID, step.ETag, daemon.WebhookPatch{Header: &step.Header, Prefix: &step.Prefix}) + res, err = daemon.EditWebhook(context.Background(), m.Conn, step.HookID, step.ETag, daemon.WebhookPatch{SignatureHeader: &step.Header, SignaturePrefix: &step.Prefix}) case daemon.WebhookRotate: res, err = daemon.RotateWebhookSecret(context.Background(), m.Conn, step.HookID, step.ETag, step.Secret) case daemon.WebhookEnable, daemon.WebhookDisable: @@ -383,3 +383,10 @@ func (m WebhooksPageModel) Update(msg tea.Msg) (WebhooksPageModel, tea.Cmd) { } return m, nil } + +func optionalWebhookText(text string) *string { + if text == "" { + return nil + } + return &text +} diff --git a/cli/test/e2e/adapter_test.go b/cli/test/e2e/adapter_test.go index 8218f4a22..04011757c 100644 --- a/cli/test/e2e/adapter_test.go +++ b/cli/test/e2e/adapter_test.go @@ -349,7 +349,7 @@ func TestAttachedWebhookScreenCreatesConfiguresDisablesAndDeletesHook(t *testing } }) for _, patch := range []daemon.WebhookPatch{ - {Header: new("x-typed-signature"), Prefix: new("typed=")}, + {SignatureHeader: new("x-typed-signature"), SignaturePrefix: new("typed=")}, {Enabled: new(false)}, {Enabled: new(true)}, } { updated, err := daemon.EditWebhook(t.Context(), attached, hook.ID, hook.ETag, patch)