Skip to content
Open
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
33 changes: 29 additions & 4 deletions internal/api/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package api
import (
"errors"
"fmt"
"reflect"
"strings"

"github.com/go-playground/validator/v10"

Expand All @@ -26,13 +28,36 @@ func NewError(err error) Error {
return e
}

func Validator(err error) Error {
func Validator(err error, invalidObj any) Error {
e := Error{}
e.Errors = make(map[string]any)
e.Errors = make(map[string]interface{})
var errs validator.ValidationErrors
errors.As(err, &errs)

if !errors.As(err, &errs) {
return e
}

invalidObjType := reflect.TypeOf(invalidObj)

if invalidObjType.Kind() == reflect.Ptr {
invalidObjType = invalidObjType.Elem()
}

for _, v := range errs {
e.Errors[v.Field()] = fmt.Sprintf("%v", v.Tag())
fieldName := v.StructField()
jsonTag := fieldName
if f, ok := invalidObjType.FieldByName(fieldName); ok {
tag := f.Tag.Get("json")
if tag != "" && tag != "-" {
jsonTag = strings.Split(tag, ",")[0]
}
}
msg := fmt.Sprintf("validation failed on '%s'", v.Tag())
if errList, ok := e.Errors[jsonTag].([]string); ok {
e.Errors[jsonTag] = append(errList, msg)
} else {
e.Errors[jsonTag] = []string{msg}
}
}
return e
}
Expand Down
2 changes: 1 addition & 1 deletion internal/api/handler/evidence.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func (h *EvidenceHandler) Create(ctx echo.Context) error {

err := ctx.Validate(input)
if err != nil {
return ctx.JSON(http.StatusBadRequest, api.Validator(err))
return ctx.JSON(http.StatusBadRequest, api.Validator(err, input))
}

components := []relational.SystemComponent{}
Expand Down
7 changes: 4 additions & 3 deletions internal/api/handler/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package handler

import (
"errors"
"net/http"

"github.com/compliance-framework/api/internal/api"
"github.com/compliance-framework/api/internal/service/relational"
oscalTypes_1_1_3 "github.com/defenseunicorns/go-oscal/src/types/oscal-1-1-3"
Expand All @@ -10,7 +12,6 @@ import (
"go.uber.org/zap"
"gorm.io/datatypes"
"gorm.io/gorm"
"net/http"
)

// FilterHandler handles CRUD operations for filters.
Expand Down Expand Up @@ -136,7 +137,7 @@ func (h *FilterHandler) Create(ctx echo.Context) error {
return ctx.JSON(http.StatusBadRequest, api.NewError(err))
}
if err := ctx.Validate(req); err != nil {
return ctx.JSON(http.StatusBadRequest, api.Validator(err))
return ctx.JSON(http.StatusBadRequest, api.Validator(err, req))
}

filter := relational.Filter{
Expand Down Expand Up @@ -190,7 +191,7 @@ func (h *FilterHandler) Update(ctx echo.Context) error {
return ctx.JSON(http.StatusBadRequest, api.NewError(err))
}
if err := ctx.Validate(req); err != nil {
return ctx.JSON(http.StatusBadRequest, api.Validator(err))
return ctx.JSON(http.StatusBadRequest, api.Validator(err, req))
}

var filter relational.Filter
Expand Down
8 changes: 4 additions & 4 deletions internal/api/handler/heartbeat.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package handler

import (
"net/http"
"time"

"github.com/compliance-framework/api/internal/api"
"github.com/compliance-framework/api/internal/service"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
"gorm.io/gorm"
"net/http"
"time"
)

type HeartbeatHandler struct {
Expand Down Expand Up @@ -54,7 +55,7 @@ func (h *HeartbeatHandler) Create(ctx echo.Context) error {

err := ctx.Validate(heartbeat)
if err != nil {
return ctx.JSON(http.StatusBadRequest, api.Validator(err))
return ctx.JSON(http.StatusBadRequest, api.Validator(err, heartbeat))
}

if err := h.db.Create(&service.Heartbeat{
Expand All @@ -78,7 +79,6 @@ func (h *HeartbeatHandler) Create(ctx echo.Context) error {
// @Failure 500 {object} api.Error
// @Router /agent/heartbeat/over-time [get]
func (h *HeartbeatHandler) OverTime(ctx echo.Context) error {

type HeartbeatInterval struct {
Interval time.Time `json:"interval"`
Total int64 `json:"total"`
Expand Down
5 changes: 5 additions & 0 deletions internal/api/handler/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ func (h *UserHandler) CreateUser(ctx echo.Context) error {
return ctx.JSON(400, api.NewError(err))
}

err := ctx.Validate(req)
if err != nil {
return ctx.JSON(400, api.Validator(err, req))
}

user := &relational.User{
Email: req.Email,
FirstName: req.FirstName,
Expand Down
41 changes: 41 additions & 0 deletions internal/api/handler/users_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,47 @@ func (suite *UserApiIntegrationSuite) TestCreateUser() {
suite.Equal(409, rec.Code, "Expected Conflict response for CreateUser with existing email")
suite.Contains(rec.Body.String(), "email already exists", "Expected error message for existing email in CreateUser response")
})

suite.Run("CreateUserWithInvalidEmail", func() {
existingUser := createUserRequest{
Email: "invalid",
Password: "password123",
FirstName: "Existing",
LastName: "User",
}

existingUserJSON, err := json.Marshal(existingUser)
suite.Require().NoError(err, "Failed to marshal existing user request")

rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/api/users", bytes.NewReader(existingUserJSON))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+*token)

suite.server.E().ServeHTTP(rec, req)
suite.Equal(400, rec.Code, "Expected error response for CreateUser with invalid email")
suite.Contains(rec.Body.String(), "{\"errors\":{\"email\":[\"validation failed on 'email'\"]}}\n", "Expected error message for invalid email in CreateUser response")
})
suite.Run("CreateUserWithMissingEmail", func() {
existingUser := createUserRequest{
Email: "",
Password: "password123",
FirstName: "Existing",
LastName: "User",
}

existingUserJSON, err := json.Marshal(existingUser)
suite.Require().NoError(err, "Failed to marshal existing user request")

rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/api/users", bytes.NewReader(existingUserJSON))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+*token)

suite.server.E().ServeHTTP(rec, req)
suite.Equal(400, rec.Code, "Expected error response for CreateUser with invalid email")
suite.Contains(rec.Body.String(), "{\"errors\":{\"email\":[\"validation failed on 'required'\"]}}\n", "Expected error message for invalid email in CreateUser response")
})
}

func (suite *UserApiIntegrationSuite) ModifyUser() {
Expand Down