Initial QSfera import
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package errorcode
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
cs3rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
|
||||
"github.com/opencloud-eu/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
// FromCS3Status converts a CS3 status code and an error into a corresponding local Error representation.
|
||||
//
|
||||
// It takes a *cs3rpc.Status, an error, and a variadic parameter of type cs3rpc.Code.
|
||||
// If the error is not nil, it creates an Error object with the error message and a GeneralException code.
|
||||
// If the error is nil, it evaluates the provided CS3 status code and returns an equivalent graph Error.
|
||||
// If the CS3 status code does not have a direct equivalent within the app,
|
||||
// or is ignored, a general purpose Error is returned.
|
||||
//
|
||||
// This function is particularly useful when dealing with CS3 responses,
|
||||
// and a unified error handling within the application is necessary.
|
||||
func FromCS3Status(status *cs3rpc.Status, inerr error, ignore ...cs3rpc.Code) error {
|
||||
err := Error{errorCode: GeneralException, msg: "unspecified error has occurred", origin: ErrorOriginCS3}
|
||||
|
||||
if inerr != nil {
|
||||
err.msg = inerr.Error()
|
||||
return err
|
||||
}
|
||||
|
||||
if status != nil {
|
||||
err.msg = status.GetMessage()
|
||||
}
|
||||
|
||||
code := status.GetCode()
|
||||
switch {
|
||||
case slices.Contains(ignore, status.GetCode()):
|
||||
fallthrough
|
||||
case code == cs3rpc.Code_CODE_OK:
|
||||
return nil
|
||||
case code == cs3rpc.Code_CODE_NOT_FOUND:
|
||||
err.errorCode = ItemNotFound
|
||||
case code == cs3rpc.Code_CODE_PERMISSION_DENIED:
|
||||
err.errorCode = AccessDenied
|
||||
case code == cs3rpc.Code_CODE_UNAUTHENTICATED:
|
||||
err.errorCode = Unauthenticated
|
||||
case code == cs3rpc.Code_CODE_INVALID_ARGUMENT:
|
||||
err.errorCode = InvalidRequest
|
||||
case code == cs3rpc.Code_CODE_ALREADY_EXISTS:
|
||||
err.errorCode = NameAlreadyExists
|
||||
case code == cs3rpc.Code_CODE_FAILED_PRECONDITION:
|
||||
err.errorCode = InvalidRequest
|
||||
case code == cs3rpc.Code_CODE_OUT_OF_RANGE:
|
||||
err.errorCode = InvalidRange
|
||||
case code == cs3rpc.Code_CODE_UNIMPLEMENTED:
|
||||
err.errorCode = NotSupported
|
||||
case code == cs3rpc.Code_CODE_UNAVAILABLE:
|
||||
err.errorCode = ServiceNotAvailable
|
||||
case code == cs3rpc.Code_CODE_INSUFFICIENT_STORAGE:
|
||||
err.errorCode = QuotaLimitReached
|
||||
case code == cs3rpc.Code_CODE_LOCKED:
|
||||
err.errorCode = ItemIsLocked
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// FromStat transforms a *provider.StatResponse object and an error into an Error.
|
||||
//
|
||||
// It takes a stat of type *provider.StatResponse, an error, and a variadic parameter of type cs3rpc.Code.
|
||||
// It invokes the FromCS3Status function with the StatResponse Status and the ignore codes.
|
||||
func FromStat(stat *provider.StatResponse, err error, ignore ...cs3rpc.Code) error {
|
||||
// TODO: look into ResourceInfo to get the postprocessing state and map that to 425 status?
|
||||
return FromCS3Status(stat.GetStatus(), err, ignore...)
|
||||
}
|
||||
|
||||
// FromUtilsStatusCodeError returns original error if `err` does not match to the statusCodeError type
|
||||
func FromUtilsStatusCodeError(err error, ignore ...cs3rpc.Code) error {
|
||||
stat := utils.StatusCodeErrorToCS3Status(err)
|
||||
if stat == nil {
|
||||
return FromCS3Status(nil, err, ignore...)
|
||||
}
|
||||
return FromCS3Status(stat, nil, ignore...)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package errorcode_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
cs3rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
|
||||
"github.com/qsfera/server/services/graph/pkg/errorcode"
|
||||
)
|
||||
|
||||
func TestFromCS3Status(t *testing.T) {
|
||||
var tests = []struct {
|
||||
status *cs3rpc.Status
|
||||
err error
|
||||
ignore []cs3rpc.Code
|
||||
expected error
|
||||
}{
|
||||
{nil, nil, nil, errorcode.New(errorcode.GeneralException, "unspecified error has occurred")},
|
||||
{nil, errors.New("test error"), nil, errorcode.New(errorcode.GeneralException, "test error")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_OK}, nil, nil, nil},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_NOT_FOUND}, nil, []cs3rpc.Code{cs3rpc.Code_CODE_NOT_FOUND}, nil},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_PERMISSION_DENIED}, nil, []cs3rpc.Code{cs3rpc.Code_CODE_NOT_FOUND, cs3rpc.Code_CODE_PERMISSION_DENIED}, nil},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_NOT_FOUND, Message: "msg"}, nil, nil, errorcode.New(errorcode.ItemNotFound, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_PERMISSION_DENIED, Message: "msg"}, nil, nil, errorcode.New(errorcode.AccessDenied, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_UNAUTHENTICATED, Message: "msg"}, nil, nil, errorcode.New(errorcode.Unauthenticated, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_INVALID_ARGUMENT, Message: "msg"}, nil, nil, errorcode.New(errorcode.InvalidRequest, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_ALREADY_EXISTS, Message: "msg"}, nil, nil, errorcode.New(errorcode.NameAlreadyExists, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_FAILED_PRECONDITION, Message: "msg"}, nil, nil, errorcode.New(errorcode.InvalidRequest, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_UNIMPLEMENTED, Message: "msg"}, nil, nil, errorcode.New(errorcode.NotSupported, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_INVALID, Message: "msg"}, nil, nil, errorcode.New(errorcode.GeneralException, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_CANCELLED, Message: "msg"}, nil, nil, errorcode.New(errorcode.GeneralException, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_UNKNOWN, Message: "msg"}, nil, nil, errorcode.New(errorcode.GeneralException, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_RESOURCE_EXHAUSTED, Message: "msg"}, nil, nil, errorcode.New(errorcode.GeneralException, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_ABORTED, Message: "msg"}, nil, nil, errorcode.New(errorcode.GeneralException, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_OUT_OF_RANGE, Message: "msg"}, nil, nil, errorcode.New(errorcode.InvalidRange, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_INTERNAL, Message: "msg"}, nil, nil, errorcode.New(errorcode.GeneralException, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_UNAVAILABLE, Message: "msg"}, nil, nil, errorcode.New(errorcode.ServiceNotAvailable, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_REDIRECTION, Message: "msg"}, nil, nil, errorcode.New(errorcode.GeneralException, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_INSUFFICIENT_STORAGE, Message: "msg"}, nil, nil, errorcode.New(errorcode.QuotaLimitReached, "msg")},
|
||||
{&cs3rpc.Status{Code: cs3rpc.Code_CODE_LOCKED, Message: "msg"}, nil, nil, errorcode.New(errorcode.ItemIsLocked, "msg")},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
var e errorcode.Error
|
||||
if errors.As(test.expected, &e) {
|
||||
test.expected = e.WithOrigin(errorcode.ErrorOriginCS3)
|
||||
}
|
||||
|
||||
if got := errorcode.FromCS3Status(test.status, test.err, test.ignore...); !reflect.DeepEqual(got, test.expected) {
|
||||
t.Error("Test Failed: {} expected, received: {}", test.expected, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromStat(t *testing.T) {
|
||||
var tests = []struct {
|
||||
stat *provider.StatResponse
|
||||
err error
|
||||
result error
|
||||
}{
|
||||
{nil, errors.New("some error"), errorcode.New(errorcode.GeneralException, "some error").WithOrigin(errorcode.ErrorOriginCS3)},
|
||||
{&provider.StatResponse{Status: &cs3rpc.Status{Code: cs3rpc.Code_CODE_OK}}, nil, nil},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
if output := errorcode.FromStat(test.stat, test.err); !reflect.DeepEqual(output, test.result) {
|
||||
t.Error("Test Failed: {} expected, received: {}", test.result, output)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// Package errorcode allows to deal with graph error codes
|
||||
package errorcode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/render"
|
||||
libregraph "github.com/opencloud-eu/libre-graph-api-go"
|
||||
)
|
||||
|
||||
// Error defines a custom error struct, containing and MS Graph error code and a textual error message
|
||||
type Error struct {
|
||||
errorCode ErrorCode
|
||||
msg string
|
||||
origin ErrorOrigin
|
||||
}
|
||||
|
||||
// ErrorOrigin gives information about where the error originated
|
||||
type ErrorOrigin int
|
||||
|
||||
const (
|
||||
// ErrorOriginUnknown is the default error source
|
||||
// and indicates that the error does not have any information about its origin
|
||||
ErrorOriginUnknown ErrorOrigin = iota
|
||||
|
||||
// ErrorOriginCS3 indicates that the error originated from a CS3 service
|
||||
ErrorOriginCS3
|
||||
)
|
||||
|
||||
// ErrorCode defines code as used in MS Graph - see https://docs.microsoft.com/en-us/graph/errors?context=graph%2Fapi%2F1.0&view=graph-rest-1.0
|
||||
type ErrorCode int
|
||||
|
||||
// List taken from https://github.com/microsoft/microsoft-graph-docs-1/blob/main/concepts/errors.md#code-property
|
||||
const (
|
||||
// AccessDenied defines the error if the caller doesn't have permission to perform the action.
|
||||
AccessDenied ErrorCode = iota
|
||||
// ActivityLimitReached defines the error if the app or user has been throttled.
|
||||
ActivityLimitReached
|
||||
// GeneralException defines the error if an unspecified error has occurred.
|
||||
GeneralException
|
||||
// InvalidAuthenticationToken defines the error if the access token is missing
|
||||
InvalidAuthenticationToken
|
||||
// InvalidRange defines the error if the specified byte range is invalid or unavailable.
|
||||
InvalidRange
|
||||
// InvalidRequest defines the error if the request is malformed or incorrect.
|
||||
InvalidRequest
|
||||
// ItemNotFound defines the error if the resource could not be found.
|
||||
ItemNotFound
|
||||
// MalwareDetected defines the error if malware was detected in the requested resource.
|
||||
MalwareDetected
|
||||
// NameAlreadyExists defines the error if the specified item name already exists.
|
||||
NameAlreadyExists
|
||||
// NotAllowed defines the error if the action is not allowed by the system.
|
||||
NotAllowed
|
||||
// NotSupported defines the error if the request is not supported by the system.
|
||||
NotSupported
|
||||
// ResourceModified defines the error if the resource being updated has changed since the caller last read it, usually an eTag mismatch.
|
||||
ResourceModified
|
||||
// ResyncRequired defines the error if the delta token is no longer valid, and the app must reset the sync state.
|
||||
ResyncRequired
|
||||
// ServiceNotAvailable defines the error if the service is not available. Try the request again after a delay. There may be a Retry-After header.
|
||||
ServiceNotAvailable
|
||||
// SyncStateNotFound defines the error when the sync state generation is not found. The delta token is expired and data must be synchronized again.
|
||||
SyncStateNotFound
|
||||
// QuotaLimitReached the user has reached their quota limit.
|
||||
QuotaLimitReached
|
||||
// Unauthenticated the caller is not authenticated.
|
||||
Unauthenticated
|
||||
// PreconditionFailed the request cannot be made and this error response is sent back
|
||||
PreconditionFailed
|
||||
// ItemIsLocked The item is locked by another process. Try again later.
|
||||
ItemIsLocked
|
||||
)
|
||||
|
||||
var errorCodes = [...]string{
|
||||
"accessDenied",
|
||||
"activityLimitReached",
|
||||
"generalException",
|
||||
"InvalidAuthenticationToken",
|
||||
"invalidRange",
|
||||
"invalidRequest",
|
||||
"itemNotFound",
|
||||
"malwareDetected",
|
||||
"nameAlreadyExists",
|
||||
"notAllowed",
|
||||
"notSupported",
|
||||
"resourceModified",
|
||||
"resyncRequired",
|
||||
"serviceNotAvailable",
|
||||
"syncStateNotFound",
|
||||
"quotaLimitReached",
|
||||
"unauthenticated",
|
||||
"preconditionFailed",
|
||||
"itemIsLocked",
|
||||
}
|
||||
|
||||
// New constructs a new errorcode.Error
|
||||
func New(e ErrorCode, msg string) Error {
|
||||
return Error{
|
||||
errorCode: e,
|
||||
msg: msg,
|
||||
}
|
||||
}
|
||||
|
||||
// Render writes a Graph ErrorCode object to the response writer
|
||||
func (e ErrorCode) Render(w http.ResponseWriter, r *http.Request, status int, msg string) {
|
||||
render.Status(r, status)
|
||||
render.JSON(w, r, e.CreateOdataError(r.Context(), msg))
|
||||
}
|
||||
|
||||
// CreateOdataError creates and populates a Graph ErrorCode object
|
||||
func (e ErrorCode) CreateOdataError(ctx context.Context, msg string) *libregraph.OdataError {
|
||||
innererror := map[string]any{
|
||||
"date": time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
innererror["request-id"] = middleware.GetReqID(ctx)
|
||||
return &libregraph.OdataError{
|
||||
Error: libregraph.OdataErrorMain{
|
||||
Code: e.String(),
|
||||
Message: msg,
|
||||
Innererror: innererror,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Render writes a Graph Error object to the response writer
|
||||
func (e Error) Render(w http.ResponseWriter, r *http.Request) {
|
||||
var status int
|
||||
switch e.errorCode {
|
||||
case AccessDenied:
|
||||
status = http.StatusForbidden
|
||||
case NotSupported:
|
||||
status = http.StatusNotImplemented
|
||||
case InvalidRange:
|
||||
status = http.StatusRequestedRangeNotSatisfiable
|
||||
case InvalidRequest:
|
||||
status = http.StatusBadRequest
|
||||
case ItemNotFound:
|
||||
status = http.StatusNotFound
|
||||
case NameAlreadyExists:
|
||||
status = http.StatusConflict
|
||||
case NotAllowed:
|
||||
status = http.StatusMethodNotAllowed
|
||||
case ItemIsLocked:
|
||||
status = http.StatusLocked
|
||||
case PreconditionFailed:
|
||||
status = http.StatusPreconditionFailed
|
||||
default:
|
||||
status = http.StatusInternalServerError
|
||||
}
|
||||
e.errorCode.Render(w, r, status, e.msg)
|
||||
}
|
||||
|
||||
// String returns the string corresponding to the ErrorCode
|
||||
func (e ErrorCode) String() string {
|
||||
return errorCodes[e]
|
||||
}
|
||||
|
||||
// Error returns the concatenation of the error string and optional message
|
||||
func (e Error) Error() string {
|
||||
errString := errorCodes[e.errorCode]
|
||||
if e.msg != "" {
|
||||
errString += ": " + e.msg
|
||||
}
|
||||
return errString
|
||||
}
|
||||
|
||||
func (e Error) GetCode() ErrorCode {
|
||||
return e.errorCode
|
||||
}
|
||||
|
||||
// GetOrigin returns the source of the error
|
||||
func (e Error) GetOrigin() ErrorOrigin {
|
||||
return e.origin
|
||||
}
|
||||
|
||||
// WithOrigin returns a new Error with the provided origin
|
||||
func (e Error) WithOrigin(o ErrorOrigin) Error {
|
||||
e.origin = o
|
||||
return e
|
||||
}
|
||||
|
||||
// RenderError render the Graph Error based on a code or default one
|
||||
func RenderError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
e, ok := ToError(err)
|
||||
if !ok {
|
||||
GeneralException.Render(w, r, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
e.Render(w, r)
|
||||
}
|
||||
|
||||
// ToError checks if the error is of type Error and returns it,
|
||||
// the second parameter indicates if the error conversion was successful
|
||||
func ToError(err error) (Error, bool) {
|
||||
var e Error
|
||||
if errors.As(err, &e) {
|
||||
return e, true
|
||||
}
|
||||
|
||||
return Error{}, false
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package errorcode_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/qsfera/server/services/graph/pkg/errorcode"
|
||||
)
|
||||
|
||||
type customErr struct{}
|
||||
|
||||
func (customErr) Error() string {
|
||||
return "some error"
|
||||
}
|
||||
|
||||
func TestRenderError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("errorcode.Error value error", func(t *testing.T) {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
err := errorcode.New(errorcode.ItemNotFound, "test error")
|
||||
errorcode.RenderError(w, r, err)
|
||||
require.Equal(t, http.StatusNotFound, w.Code)
|
||||
})
|
||||
|
||||
t.Run("errorcode.Error zero value error", func(t *testing.T) {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
var err errorcode.Error
|
||||
errorcode.RenderError(w, r, err)
|
||||
require.Equal(t, http.StatusForbidden, w.Code)
|
||||
})
|
||||
|
||||
t.Run("custom error", func(t *testing.T) {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
w := httptest.NewRecorder()
|
||||
var err customErr
|
||||
errorcode.RenderError(w, r, err)
|
||||
require.Equal(t, http.StatusInternalServerError, w.Code)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user