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
28 changes: 28 additions & 0 deletions internal/richerror/richerror.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* 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 richerror provides a rich error type that can be used to wrap errors
package richerror

// RichError is an error type that can be used to wrap errors with additional metadata
type RichError struct {
Err error
Metadata map[string]string
}
hackerwins marked this conversation as resolved.
Show resolved Hide resolved

func (e RichError) Error() string {
return e.Err.Error()
}
hackerwins marked this conversation as resolved.
Show resolved Hide resolved
35 changes: 26 additions & 9 deletions server/rpc/auth/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,26 @@ import (
"time"

"github.com/yorkie-team/yorkie/api/types"
"github.com/yorkie-team/yorkie/internal/richerror"
"github.com/yorkie-team/yorkie/server/backend"
"github.com/yorkie-team/yorkie/server/logging"
)

var (
// ErrNotAllowed is returned when the given user is not allowed for the access.
ErrNotAllowed = errors.New("method is not allowed for this user")
// ErrPermissionDenied is returned when the given user is not allowed for the access.
ErrPermissionDenied = errors.New("method is not allowed for this user")

// ErrUnexpectedStatusCode is returned when the response code is not 200 from the webhook.
ErrUnexpectedStatusCode = errors.New("unexpected status code from webhook")

// ErrUnexpectedResponse is returned when the response from the webhook is not as expected.
ErrUnexpectedResponse = errors.New("unexpected response from webhook")

// ErrWebhookTimeout is returned when the webhook does not respond in time.
ErrWebhookTimeout = errors.New("webhook timeout")

// ErrUnauthenticated is returned when the request lacks valid authentication credentials.
ErrUnauthenticated = errors.New("request lacks valid authentication credentials")
)

// verifyAccess verifies the given user is allowed to access the given method.
Expand All @@ -63,8 +70,8 @@ func verifyAccess(
cacheKey := string(reqBody)
if entry, ok := be.AuthWebhookCache.Get(cacheKey); ok {
resp := entry
if !resp.Allowed {
return fmt.Errorf("%s: %w", resp.Reason, ErrNotAllowed)
if resp.Code != types.CodeOK {
return fmt.Errorf("%s: %w", resp.Message, ErrPermissionDenied)
}
return nil
}
Expand Down Expand Up @@ -95,13 +102,23 @@ func verifyAccess(
return resp.StatusCode, err
}

if !authResp.Allowed {
return resp.StatusCode, fmt.Errorf("%s: %w", authResp.Reason, ErrNotAllowed)
if authResp.Code == types.CodeOK {
return resp.StatusCode, nil
}
if authResp.Code == types.CodePermissionDenied {
return resp.StatusCode, fmt.Errorf("%s: %w", authResp.Message, ErrPermissionDenied)
}
if authResp.Code == types.CodeUnauthenticated {
richError := &richerror.RichError{
Err: ErrUnauthenticated,
Metadata: map[string]string{"message": authResp.Message},
}
return resp.StatusCode, richError
}

return resp.StatusCode, nil
return resp.StatusCode, fmt.Errorf("%d: %w", authResp.Code, ErrUnexpectedResponse)
}); err != nil {
if errors.Is(err, ErrNotAllowed) {
if errors.Is(err, ErrPermissionDenied) {
be.AuthWebhookCache.Add(cacheKey, authResp, be.Config.ParseAuthWebhookCacheUnauthTTL())
}

chacha912 marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -120,7 +137,7 @@ func withExponentialBackoff(ctx context.Context, cfg *backend.Config, webhookFn
statusCode, err := webhookFn()
if !shouldRetry(statusCode, err) {
if err == ErrUnexpectedStatusCode {
return fmt.Errorf("unexpected status code from webhook: %d", statusCode)
return fmt.Errorf("%d: %w", statusCode, ErrUnexpectedStatusCode)
}

return err
Expand Down
53 changes: 51 additions & 2 deletions server/rpc/connecthelper/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (

"github.com/yorkie-team/yorkie/api/converter"
"github.com/yorkie-team/yorkie/api/types"
"github.com/yorkie-team/yorkie/internal/richerror"
"github.com/yorkie-team/yorkie/internal/validation"
"github.com/yorkie-team/yorkie/pkg/document/key"
"github.com/yorkie-team/yorkie/pkg/document/time"
Expand Down Expand Up @@ -78,11 +79,15 @@ var errorToConnectCode = map[error]connect.Code{
converter.ErrUnsupportedCounterType: connect.CodeUnimplemented,

// Unauthenticated means the request does not have valid authentication
auth.ErrNotAllowed: connect.CodeUnauthenticated,
auth.ErrUnexpectedStatusCode: connect.CodeUnauthenticated,
auth.ErrUnexpectedResponse: connect.CodeUnauthenticated,
auth.ErrWebhookTimeout: connect.CodeUnauthenticated,
auth.ErrUnauthenticated: connect.CodeUnauthenticated,
database.ErrMismatchedPassword: connect.CodeUnauthenticated,

// PermissionDenied means the request does not have permission for the operation.
auth.ErrPermissionDenied: connect.CodePermissionDenied,

// Canceled means the operation was canceled (typically by the caller).
context.Canceled: connect.CodeCanceled,
}
Expand Down Expand Up @@ -124,7 +129,9 @@ var errorToCode = map[error]string{
converter.ErrUnsupportedValueType: "ErrUnsupportedValueType",
converter.ErrUnsupportedCounterType: "ErrUnsupportedCounterType",

auth.ErrNotAllowed: "ErrNotAllowed",
auth.ErrPermissionDenied: "ErrPermissionDenied",
auth.ErrUnauthenticated: "ErrUnauthenticated",
auth.ErrUnexpectedResponse: "ErrUnexpectedResponse",
auth.ErrUnexpectedStatusCode: "ErrUnexpectedStatusCode",
auth.ErrWebhookTimeout: "ErrWebhookTimeout",
database.ErrMismatchedPassword: "ErrMismatchedPassword",
Expand Down Expand Up @@ -179,6 +186,44 @@ func errorToConnectError(err error) (*connect.Error, bool) {
return connectErr, true
}

// richErrorToConnectError returns connect.Error from the given rich error.
func richErrorToConnectError(err error) (*connect.Error, bool) {
var richError *richerror.RichError
if !errors.As(err, &richError) {
return nil, false
}

// NOTE(hackerwins): This prevents panic when the cause is an unhashable
// error.
var connectCode connect.Code
var ok bool
defer func() {
if r := recover(); r != nil {
ok = false
}
}()

connectCode, ok = errorToConnectCode[richError.Err]
if !ok {
return nil, false
}

connectErr := connect.NewError(connectCode, err)
if code, ok := errorToCode[richError.Err]; ok {
errorInfo := &errdetails.ErrorInfo{
Metadata: map[string]string{"code": code},
}
for key, value := range richError.Metadata {
errorInfo.Metadata[key] = value
}
if detail, detailErr := connect.NewErrorDetail(errorInfo); detailErr == nil {
connectErr.AddDetail(detail)
}
}

return connectErr, true
}

hackerwins marked this conversation as resolved.
Show resolved Hide resolved
// structErrorToConnectError returns connect.Error from the given struct error.
func structErrorToConnectError(err error) (*connect.Error, bool) {
var invalidFieldsError *validation.StructError
Expand Down Expand Up @@ -225,6 +270,10 @@ func ToStatusError(err error) error {
return nil
}

if err, ok := richErrorToConnectError(err); ok {
return err
}

if err, ok := errorToConnectError(err); ok {
return err
}
Expand Down
Loading
Loading