2022-03-18 13:21:40 +00:00
|
|
|
// Package read implements request object readers.
|
|
|
|
package read
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2022-03-30 12:50:14 +00:00
|
|
|
"errors"
|
2022-03-18 13:21:40 +00:00
|
|
|
"io"
|
2022-03-30 12:50:14 +00:00
|
|
|
"net/http"
|
2022-04-26 12:01:16 +00:00
|
|
|
"strings"
|
2022-03-18 13:21:40 +00:00
|
|
|
|
|
|
|
"google.golang.org/protobuf/encoding/protojson"
|
|
|
|
"google.golang.org/protobuf/proto"
|
2022-03-18 13:25:34 +00:00
|
|
|
|
2022-04-19 10:07:57 +00:00
|
|
|
"github.com/smallstep/certificates/api/render"
|
2022-03-18 13:25:34 +00:00
|
|
|
"github.com/smallstep/certificates/errs"
|
2022-03-18 13:21:40 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// JSON reads JSON from the request body and stores it in the value
|
2022-04-26 12:56:42 +00:00
|
|
|
// pointed to by v.
|
2022-03-18 13:21:40 +00:00
|
|
|
func JSON(r io.Reader, v interface{}) error {
|
|
|
|
if err := json.NewDecoder(r).Decode(v); err != nil {
|
|
|
|
return errs.BadRequestErr(err, "error decoding json")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ProtoJSON reads JSON from the request body and stores it in the value
|
2022-04-21 10:14:03 +00:00
|
|
|
// pointed to by m.
|
2022-03-18 13:21:40 +00:00
|
|
|
func ProtoJSON(r io.Reader, m proto.Message) error {
|
|
|
|
data, err := io.ReadAll(r)
|
|
|
|
if err != nil {
|
|
|
|
return errs.BadRequestErr(err, "error reading request body")
|
|
|
|
}
|
2022-04-19 10:07:57 +00:00
|
|
|
|
|
|
|
switch err := protojson.Unmarshal(data, m); {
|
|
|
|
case errors.Is(err, proto.Error):
|
2022-04-26 12:56:42 +00:00
|
|
|
return badProtoJSONError(err.Error())
|
2022-04-19 10:07:57 +00:00
|
|
|
default:
|
|
|
|
return err
|
2022-04-18 21:38:13 +00:00
|
|
|
}
|
|
|
|
}
|
2022-03-30 12:50:14 +00:00
|
|
|
|
2022-04-19 10:07:57 +00:00
|
|
|
// badProtoJSONError is an error type that is returned by ProtoJSON
|
|
|
|
// when a proto message cannot be unmarshaled. Usually this is caused
|
|
|
|
// by an error in the request body.
|
|
|
|
type badProtoJSONError string
|
|
|
|
|
|
|
|
// Error implements error for badProtoJSONError
|
|
|
|
func (e badProtoJSONError) Error() string {
|
|
|
|
return string(e)
|
2022-04-18 21:38:13 +00:00
|
|
|
}
|
|
|
|
|
2022-04-19 10:07:57 +00:00
|
|
|
// Render implements render.RenderableError for badProtoJSONError
|
|
|
|
func (e badProtoJSONError) Render(w http.ResponseWriter) {
|
|
|
|
v := struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
Detail string `json:"detail"`
|
|
|
|
Message string `json:"message"`
|
|
|
|
}{
|
2022-04-26 12:56:42 +00:00
|
|
|
Type: "badRequest",
|
|
|
|
Detail: "bad request",
|
|
|
|
// trim the proto prefix for the message
|
|
|
|
Message: strings.TrimSpace(strings.TrimPrefix(e.Error(), "proto:")),
|
2022-03-30 12:50:14 +00:00
|
|
|
}
|
2022-04-19 10:07:57 +00:00
|
|
|
render.JSONStatus(w, v, http.StatusBadRequest)
|
2022-03-30 12:50:14 +00:00
|
|
|
}
|