Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Authorization Webhook Response Format and Handling #1037

Merged
merged 10 commits into from
Nov 1, 2024
19 changes: 19 additions & 0 deletions api/converter/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,22 @@ func ErrorCodeOf(err error) string {
}
return ""
}

// ErrorMetadataOf returns the error metadata of the given error.
func ErrorMetadataOf(err error) map[string]string {
var connectErr *connect.Error
if !errors.As(err, &connectErr) {
return nil
}
for _, detail := range connectErr.Details() {
msg, valueErr := detail.Value()
if valueErr != nil {
continue
}

if errorInfo, ok := msg.(*errdetails.ErrorInfo); ok {
return errorInfo.GetMetadata()
}
}
return nil
}
21 changes: 19 additions & 2 deletions api/types/auth_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,27 @@ func NewAuthWebhookRequest(reader io.Reader) (*AuthWebhookRequest, error) {
return req, nil
}

// Code represents the result of an authentication webhook request.
type Code int

const (
// CodeOK indicates that the request is fully authenticated and has
// the necessary permissions.
CodeOK Code = 200

// CodeUnauthenticated indicates that the request does not have valid
// authentication credentials for the operation.
CodeUnauthenticated Code = 401

// CodePermissionDenied indicates that the authenticated request lacks
// the necessary permissions.
CodePermissionDenied Code = 403
)

// AuthWebhookResponse represents the response of authentication webhook.
type AuthWebhookResponse struct {
Allowed bool `json:"allowed"`
Reason string `json:"reason"`
Code Code `json:"code"`
Message string `json:"message"`
}

// NewAuthWebhookResponse creates a new instance of AuthWebhookResponse.
Expand Down
16 changes: 8 additions & 8 deletions api/types/updatable_project_fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
)

func TestUpdatableProjectFields(t *testing.T) {
var structError *validation.StructError
var formErr *validation.FormError
t.Run("validation test", func(t *testing.T) {
newName := "changed-name"
newAuthWebhookURL := "http://localhost:3000"
Expand Down Expand Up @@ -68,7 +68,7 @@ func TestUpdatableProjectFields(t *testing.T) {
AuthWebhookMethods: &newAuthWebhookMethods,
ClientDeactivateThreshold: &newClientDeactivateThreshold,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)
})

t.Run("project name format test", func(t *testing.T) {
Expand All @@ -82,36 +82,36 @@ func TestUpdatableProjectFields(t *testing.T) {
fields = &types.UpdatableProjectFields{
Name: &invalidName,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

reservedName := "new"
fields = &types.UpdatableProjectFields{
Name: &reservedName,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

reservedName = "default"
fields = &types.UpdatableProjectFields{
Name: &reservedName,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidName = "1"
fields = &types.UpdatableProjectFields{
Name: &invalidName,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidName = "over_30_chracaters_is_invalid_name"
fields = &types.UpdatableProjectFields{
Name: &invalidName,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidName = "invalid/name"
fields = &types.UpdatableProjectFields{
Name: &invalidName,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)
})
}
16 changes: 8 additions & 8 deletions api/types/user_fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
)

func TestSignupFields(t *testing.T) {
var structError *validation.StructError
var formErr *validation.FormError

t.Run("password validation test", func(t *testing.T) {
validUsername := "test"
Expand All @@ -42,48 +42,48 @@ func TestSignupFields(t *testing.T) {
Username: &validUsername,
Password: &invalidPassword,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidPassword = "abcd"
fields = &types.UserFields{
Username: &validUsername,
Password: &invalidPassword,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidPassword = "!@#$"
fields = &types.UserFields{
Username: &validUsername,
Password: &invalidPassword,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidPassword = "abcd1234"
fields = &types.UserFields{
Username: &validUsername,
Password: &invalidPassword,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidPassword = "abcd!@#$"
fields = &types.UserFields{
Username: &validUsername,
Password: &invalidPassword,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidPassword = "1234!@#$"
fields = &types.UserFields{
Username: &validUsername,
Password: &invalidPassword,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)

invalidPassword = "abcd1234!@abcd1234!@abcd1234!@1"
fields = &types.UserFields{
Username: &validUsername,
Password: &invalidPassword,
}
assert.ErrorAs(t, fields.Validate(), &structError)
assert.ErrorAs(t, fields.Validate(), &formErr)
})
}
59 changes: 59 additions & 0 deletions internal/metaerrors/metaerrors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2024 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Package metaerrors provides a way to attach metadata to errors.
package metaerrors

import "strings"

// MetaError is an error that can have metadata attached to it. This can be used
// to send additional information to the SDK or to the user.
type MetaError struct {
// Err is the underlying error.
Err error

// Metadata is a map of additional information that can be attached to the
// error.
Metadata map[string]string
}
hackerwins marked this conversation as resolved.
Show resolved Hide resolved

// New returns a new MetaError with the given error and metadata.
func New(err error, metadata map[string]string) *MetaError {
return &MetaError{
Err: err,
Metadata: metadata,
}
}
hackerwins marked this conversation as resolved.
Show resolved Hide resolved

// Error returns the error message.
func (e MetaError) Error() string {
if len(e.Metadata) == 0 {
return e.Err.Error()
}

sb := strings.Builder{}

for key, val := range e.Metadata {
if sb.Len() > 0 {
sb.WriteString(",")
}
sb.WriteString(key)
sb.WriteString("=")
sb.WriteString(val)
}

return e.Err.Error() + " [" + sb.String() + "]"
}
hackerwins marked this conversation as resolved.
Show resolved Hide resolved
57 changes: 57 additions & 0 deletions internal/metaerrors/metaerrors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 2024 The Yorkie Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package metaerrors_test

import (
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/assert"

"github.com/yorkie-team/yorkie/internal/metaerrors"
)

func TestMetaError(t *testing.T) {
t.Run("test meta error", func(t *testing.T) {
err := errors.New("error message")
metaErr := metaerrors.New(err, map[string]string{"key": "value"})
assert.Equal(t, "error message [key=value]", metaErr.Error())

err = errors.New("error message")
metaErr = metaerrors.New(err, map[string]string{"key1": "value1", "key2": "value2"})
assert.Equal(t, "error message [key1=value1,key2=value2]", metaErr.Error())
})

t.Run("test meta error without metadata", func(t *testing.T) {
err := errors.New("error message")
metaErr := metaerrors.New(err, nil)
assert.Equal(t, "error message", metaErr.Error())
})

t.Run("test meta error with wrapped error", func(t *testing.T) {
err := fmt.Errorf("wrapped error: %w", errors.New("error message"))
metaErr := metaerrors.New(err, map[string]string{"key": "value"})
assert.Equal(t, "wrapped error: error message [key=value]", metaErr.Error())

metaErr = metaerrors.New(errors.New("error message"), map[string]string{"key": "value"})
assert.Equal(t, "error message [key=value]", metaErr.Error())

wrappedErr := fmt.Errorf("wrapped error: %w", metaErr)
assert.Equal(t, "wrapped error: error message [key=value]", wrappedErr.Error())
})
}
14 changes: 7 additions & 7 deletions internal/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

// Package validation provides the validation functions.
// Package validation provides the validation functions for form and field.
package validation

import (
Expand Down Expand Up @@ -119,13 +119,13 @@ func (e Violation) Error() string {
return e.Err.Error()
}

// StructError is the error returned by the validation of struct.
type StructError struct {
// FormError represents the error of the form validation.
type FormError struct {
Violations []Violation
}

// Error returns the error message.
func (s StructError) Error() string {
func (s FormError) Error() string {
sb := strings.Builder{}

for _, v := range s.Violations {
Expand Down Expand Up @@ -223,16 +223,16 @@ func Validate(v string, tagOrRules []interface{}) error {
// ValidateStruct validates the struct
func ValidateStruct(s interface{}) error {
if err := defaultValidator.Struct(s); err != nil {
structError := &StructError{}
formErr := &FormError{}
for _, e := range err.(validator.ValidationErrors) {
structError.Violations = append(structError.Violations, Violation{
formErr.Violations = append(formErr.Violations, Violation{
Tag: e.Tag(),
Field: e.StructField(),
Err: e,
Description: e.Translate(trans),
})
}
return structError
return formErr
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions internal/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ func TestValidation(t *testing.T) {
user := User{Name: "invalid-key-$-wrong-string-value", Country: "korea"}

err := ValidateStruct(user)
structError := err.(*StructError)
assert.Len(t, structError.Violations, 2, "user should be invalid")
formErr := err.(*FormError)
assert.Len(t, formErr.Violations, 2, "user should be invalid")
})

t.Run("custom rule test", func(t *testing.T) {
Expand Down
Loading
Loading