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

NOISSUE - New error type for HTTP Proxy server to return Handlers error #50

Merged
merged 4 commits into from
Oct 17, 2024

Conversation

arvindh123
Copy link
Contributor

@arvindh123 arvindh123 commented Jan 4, 2024

Pull request title should be MF-XXX - description or NOISSUE - description where XXX is ID of issue that this PR relate to.
Please review the CONTRIBUTING.md file for detailed contributing guidelines.

What does this do?

At present, Proxy handler return its own http status code.
There is no provision for handlers set return http status code.

This PR helps handlers to return http status code in error
Add new error type interface named HTTPProxyError is created, which return status code on calling method StatusCode()
This can be used in encodeError to return If any error code returned by handlers

This feature was found during testing of this PR absmach/magistrala-old#257,
Where Things gRPC sends error warpped, but in result the HTTP Status is not as expected. Then found this kind of solution in handler will help us to send proper status code clients

Which issue(s) does this PR fix/relate to?

Put here Resolves #XXX to auto-close the issue that your PR fixes (if such)

List any changes that modify/break current functionality

No

Have you included tests for your changes?

No, Not planned in this PR

Did you document any new/modified functionality?

No, Not planned in this PR

Notes

This error type helps to return http status code by handler, Example at here https://github.com/absmach/magistrala/blob/main/http/handler.go#L105-L168
We can implement like below with this new HTTPPorxyError

// Publish - after client successfully published.
func (h *handler) Publish(ctx context.Context, topic *string, payload *[]byte) error {
	if topic == nil {
-		return ErrMissingTopicPub
+		return mHttp.NewHTTPProxyError(http.StatusBadRequest, ErrMissingTopicPub)
	}
	topic = &strings.Split(*topic, "?")[0]
	s, ok := session.FromContext(ctx)
	if !ok {
-		return errors.Wrap(ErrFailedPublish, ErrClientNotInitialized)
+		return mHttp.NewHTTPProxyError(http.StatusBadRequest, errors.Wrap(ErrFailedPublish, ErrClientNotInitialized))
	}
	h.logger.Info(fmt.Sprintf(LogInfoPublished, s.ID, *topic))
	// Topics are in the format:
	// channels/<channel_id>/messages/<subtopic>/.../ct/<content_type>

	channelParts := channelRegExp.FindStringSubmatch(*topic)
	if len(channelParts) < 2 {
-		return errors.Wrap(ErrFailedPublish, ErrMalformedTopic)
+		return mHttp.NewHTTPProxyError(http.StatusBadRequest, errors.Wrap(ErrFailedPublish, ErrMalformedTopic))
	}

	chanID := channelParts[1]
	subtopic := channelParts[2]

	subtopic, err := parseSubtopic(subtopic)
	if err != nil {
-		return errors.Wrap(ErrFailedParseSubtopic, err)
+		return mHttp.NewHTTPProxyError(http.StatusBadRequest, errors.Wrap(ErrFailedParseSubtopic, err))
	}

	msg := messaging.Message{
		Protocol: protocol,
		Channel:  chanID,
		Subtopic: subtopic,
		Payload:  *payload,
		Created:  time.Now().UnixNano(),
	}
	var tok string
	switch {
	case string(s.Password) == "":
-		return errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerKey)
+		return mHttp.NewHTTPProxyError(http.StatusBadRequest, errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerKey))
	case strings.HasPrefix(string(s.Password), "Thing"):
		tok = extractThingKey(string(s.Password))
	default:
		tok = string(s.Password)
	}
	ar := &magistrala.AuthorizeReq{
		Subject:     tok,
		Object:      msg.Channel,
		SubjectType: auth.ThingType,
		Permission:  auth.PublishPermission,
		ObjectType:  auth.GroupType,
	}
	res, err := h.auth.Authorize(ctx, ar)
	if err != nil {
-		return err
+		return mHttp.NewHTTPProxyError(http.StatusForbidden, err)
	}
	if !res.GetAuthorized() {
-		return errors.ErrAuthorization
+		return mHttp.NewHTTPProxyError(http.StatusForbidden, errors.ErrAuthorization)
	}
	msg.Publisher = res.GetId()

	if err := h.publisher.Publish(ctx, msg.Channel, &msg); err != nil {
-		return errors.Wrap(ErrFailedPublishToMsgBroker, err)
+		return mHttp.NewHTTPProxyError(http.StatusForbidden, errors.Wrap(ErrFailedPublishToMsgBroker, err))
	}

	return nil
}

@arvindh123 arvindh123 marked this pull request as ready for review January 4, 2024 11:25
@arvindh123 arvindh123 changed the title add http error type NOISSUE - New error type for HTTP Proxy server to return Handlers error Jan 4, 2024
@arvindh123 arvindh123 self-assigned this May 30, 2024
@dborovcanin dborovcanin requested review from felixgateru and removed request for SammyOina August 7, 2024 13:09

package http

import mgerrors "github.com/absmach/magistrala/pkg/errors"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should not rely on Magistrala dependency.

Copy link
Contributor Author

@arvindh123 arvindh123 Oct 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think mgerrors are no need now , we can use Go native error type

Signed-off-by: Arvindh <[email protected]>
Signed-off-by: Arvindh <[email protected]>
@dborovcanin dborovcanin merged commit e53a940 into absmach:main Oct 17, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

3 participants