sdk-go icon indicating copy to clipboard operation
sdk-go copied to clipboard

Race condition in func WithCustomAttributes(ctx context.Context, attrs map[string]string)

Open volkerhess2 opened this issue 10 months ago • 0 comments

The WithCustomAttributes function currently takes a map as input value. Since map is a pointer value, the pointer is passed to msg.Attributes of the pubsub message and then is used throughout the sdk. The map is modified in multiple places. If the pointer to the map is used outside of the event or if the map is reused for multiple events there will be race conditions.

https://github.com/cloudevents/sdk-go/blob/main/protocol/pubsub/v2/attributes.go

type withCustomAttributes struct{}

func AttributesFrom(ctx context.Context) map[string]string {
	return binding.GetOrDefaultFromCtx(ctx, withCustomAttributes{}, make(map[string]string)).(map[string]string)
}

// WithCustomAttributes sets Message Attributes without any CloudEvent logic.
// Note that this function is not intended for CloudEvent Extensions or any `ce-`-prefixed Attributes.
// For these please see `Event` and `Event.SetExtension`.
func WithCustomAttributes(ctx context.Context, attrs map[string]string) context.Context {
	return context.WithValue(ctx, withCustomAttributes{}, attrs)
}

https://github.com/cloudevents/sdk-go/blob/main/protocol/pubsub/v2/protocol.go

// Send implements Sender.Send
func (t *Protocol) Send(ctx context.Context, in binding.Message, transformers ...binding.Transformer) error {
	var err error
	defer func() { _ = in.Finish(err) }()

	topic := cecontext.TopicFrom(ctx)
	if topic == "" {
		topic = t.topicID
	}

	conn := t.getOrCreateConnection(ctx, topic, "", "")

	msg := &pubsub.Message{
		Attributes: AttributesFrom(ctx),
	}
...

volkerhess2 avatar Apr 05 '24 14:04 volkerhess2