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
}
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)
})
}
5 changes: 5 additions & 0 deletions client/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ func NewAuthInterceptor(apiKey, token string) *AuthInterceptor {
}
}

// SetToken sets the token.
func (i *AuthInterceptor) SetToken(token string) {
i.token = token
}

// WrapUnary creates a unary server interceptor for authorization.
func (i *AuthInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
return func(
Expand Down
11 changes: 9 additions & 2 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ type Client struct {
client v1connect.YorkieServiceClient
options Options
clientOptions []connect.ClientOption
interceptor *AuthInterceptor
logger *zap.Logger

id *time.ActorID
Expand Down Expand Up @@ -149,8 +150,8 @@ func New(opts ...Option) (*Client, error) {
}

var clientOptions []connect.ClientOption

clientOptions = append(clientOptions, connect.WithInterceptors(NewAuthInterceptor(options.APIKey, options.Token)))
interceptor := NewAuthInterceptor(options.APIKey, options.Token)
clientOptions = append(clientOptions, connect.WithInterceptors(interceptor))
if options.MaxCallRecvMsgSize != 0 {
clientOptions = append(clientOptions, connect.WithReadMaxBytes(options.MaxCallRecvMsgSize))
}
Expand All @@ -169,6 +170,7 @@ func New(opts ...Option) (*Client, error) {
clientOptions: clientOptions,
options: options,
logger: logger,
interceptor: interceptor,

key: k,
status: deactivated,
Expand Down Expand Up @@ -205,6 +207,11 @@ func (c *Client) Dial(rpcAddr string) error {
return nil
}

// SetToken sets the given token of this client.
func (c *Client) SetToken(token string) {
c.interceptor.SetToken(token)
}

// Close closes all resources of this client.
func (c *Client) Close() error {
if err := c.Deactivate(context.Background()); err != nil {
Expand Down
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
53 changes: 53 additions & 0 deletions internal/metaerrors/metaerrors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* 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())
})

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