Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions internal/codegen/backends/openapi3/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ func convertOp(op *operation, method, path string, pathParams []parameter, globa
mediaTypes = append(mediaTypes, ct)
}
sort.Strings(mediaTypes)
out.RequestBody.MediaType = mediaTypes[0]
out.RequestBody.Schema = convertSchema(op.RequestBody.Content[mediaTypes[0]].Schema)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"Parameters": null,
"RequestBody": {
"Required": true,
"MediaType": "application/xml",
"Schema": {
"Ref": "",
"Type": "object",
Expand Down
15 changes: 15 additions & 0 deletions pkg/runtime/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,9 @@ func buildCmd(s CommandSpec) *cobra.Command {
} else if s.RequestBody != nil {
switch {
case cmd.Flags().Changed("set") || cmd.Flags().Changed("set-str"):
if !supportsJSONBodyBuilder(s.RequestBody.MediaType) {
return fmt.Errorf("request body media type %s requires --file; --set and --set-str only support JSON request bodies", s.RequestBody.MediaType)
}
raw, berr := buildBodyFromSet(bodySets, bodyStringSets)
if berr != nil {
return berr
Expand All @@ -243,12 +246,18 @@ func buildCmd(s CommandSpec) *cobra.Command {
}
body = raw
case s.RequestBody.Required:
if !supportsJSONBodyBuilder(s.RequestBody.MediaType) {
return fmt.Errorf("request body media type %s requires --file", s.RequestBody.MediaType)
}
return fmt.Errorf("request body required: pass --file, --set, or --set-str")
}
}
if err := validateRequiredVariableParams(s, body); err != nil {
return err
}
if body != nil && s.RequestBody != nil && s.RequestBody.MediaType != "" {
hdrs["Content-Type"] = s.RequestBody.MediaType
}

if v, err := cmd.Root().PersistentFlags().GetBool("debug"); err == nil && v {
clientOpts.Debug = true
Expand Down Expand Up @@ -389,6 +398,12 @@ func buildCmd(s CommandSpec) *cobra.Command {
return cmd
}

func supportsJSONBodyBuilder(mediaType string) bool {
mt, _, _ := strings.Cut(strings.ToLower(strings.TrimSpace(mediaType)), ";")
mt = strings.TrimSpace(mt)
return mt == "" || mt == "application/json" || strings.HasSuffix(mt, "+json")
}

func addSafeInputFlags(cmd *cobra.Command, p ParamSpec) {
if !isSensitiveStringParam(p) {
return
Expand Down
66 changes: 66 additions & 0 deletions pkg/runtime/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,72 @@ func TestBuild_SetStrSendsStringBodyFields(t *testing.T) {
}
}

func TestBuild_FileSendsRequestBodyMediaType(t *testing.T) {
bindTestManifest(t, "myctl", "MYCTL_HOST")
t.Setenv("MYCTL_CONFIG_DIR", t.TempDir())

var gotContentType string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotContentType = r.Header.Get("Content-Type")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{}`))
}))
defer srv.Close()

bodyFile := t.TempDir() + "/body.txt"
if err := os.WriteFile(bodyFile, []byte("hello"), 0600); err != nil {
t.Fatalf("write body file: %v", err)
}

root := newRootWithModuleGroup()
root.PersistentFlags().String("hostname", "", "")
root.PersistentFlags().StringP("output", "o", "raw", "")
Build(root, "demo", []CommandSpec{{
Group: "Exports",
Use: "create-export",
Method: "POST",
PathTpl: "/exports",
RequestBody: &RequestBody{Required: true, MediaType: "text/plain"},
Security: &SecurityHint{Public: true},
}})
root.SetArgs([]string{"--hostname", srv.URL, "demo", "exports", "create-export", "--file", bodyFile})

if err := root.Execute(); err != nil {
t.Fatalf("Execute: %v", err)
}
if gotContentType != "text/plain" {
t.Errorf("Content-Type = %q, want text/plain", gotContentType)
}
}

func TestBuild_NonJSONRequestBodyRequiresFile(t *testing.T) {
for _, args := range [][]string{
{"--set", "id=1"},
nil,
} {
bindTestManifest(t, "myctl", "MYCTL_HOST")
t.Setenv("MYCTL_CONFIG_DIR", t.TempDir())

root := newRootWithModuleGroup()
root.PersistentFlags().String("hostname", "", "")
root.PersistentFlags().StringP("output", "o", "raw", "")
Build(root, "demo", []CommandSpec{{
Group: "Exports",
Use: "create-export",
Method: "POST",
PathTpl: "/exports",
RequestBody: &RequestBody{Required: true, MediaType: "text/plain"},
Security: &SecurityHint{Public: true},
}})
root.SetArgs(append([]string{"--hostname", "http://127.0.0.1:1", "demo", "exports", "create-export"}, args...))

err := root.Execute()
if err == nil || !strings.Contains(err.Error(), "requires --file") {
t.Fatalf("Execute error = %v, want requires --file", err)
}
}
}

func TestBuild_VariableFlagsMergeIntoEnvelope(t *testing.T) {
root, url, recorded := newRecordingGraphQLRoot(t, createAppSpec())
root.SetArgs([]string{"--hostname", url, "demo", "apps", "create-app", "--input-name", "demo"})
Expand Down