fix topic validation (#74)

* fix topic validation

* fix tests
This commit is contained in:
Dominic Wong
2021-03-19 13:29:53 +00:00
committed by GitHub
parent 8dfe49f813
commit a711e10961
5 changed files with 88 additions and 16 deletions

View File

@@ -2,12 +2,12 @@ package handler
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/micro/micro/v3/service/errors"
"github.com/micro/micro/v3/service/events"
"github.com/nats-io/nats-streaming-server/util"
"gorm.io/gorm"
)
@@ -35,16 +35,14 @@ type Streams struct {
Time func() time.Time
}
// fmtTopic returns a topic string with namespace prefix and hyphens replaced with dots
// fmtTopic returns a topic string with namespace prefix
func fmtTopic(ns, topic string) string {
// events topic names can only be alphanumeric and "."
return fmt.Sprintf("%s.%s", strings.ReplaceAll(ns, "-", "."), topic)
return fmt.Sprintf("%s.%s", ns, topic)
}
// validateTopicInput validates that topic is alphanumeric
func validateTopicInput(topic string) error {
reg := regexp.MustCompile("^[a-zA-Z0-9]+$")
if len(reg.FindString(topic)) == 0 {
if !util.IsChannelNameValid(topic, false) {
return ErrInvalidTopic
}
return nil

View File

@@ -207,7 +207,7 @@ func TestSubscribe(t *testing.T) {
s := new(streamMock)
ctx = auth.ContextWithAccount(context.TODO(), &auth.Account{Issuer: "bar"})
err = h.Subscribe(ctx, &pb.SubscribeRequest{
Topic: "tok-for-diff",
Topic: "tok-for/diff",
Token: tRsp.Token,
}, s)
assert.Equal(t, handler.ErrInvalidTopic, err)

View File

@@ -32,7 +32,7 @@ func TestToken(t *testing.T) {
t.Run("WithBadTopic", func(t *testing.T) {
var rsp pb.TokenResponse
ctx := auth.ContextWithAccount(context.TODO(), &auth.Account{Issuer: "foo"})
err := h.Token(ctx, &pb.TokenRequest{Topic: "helloworld-1"}, &rsp)
err := h.Token(ctx, &pb.TokenRequest{Topic: "helloworld/1"}, &rsp)
assert.Equal(t, handler.ErrInvalidTopic, err)
})
}