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

[ADDED] SecureDeleteMsg method to JetStreamManager #1025

Merged
merged 1 commit into from Aug 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 30 additions & 7 deletions jsm.go
Expand Up @@ -58,9 +58,13 @@ type JetStreamManager interface {
// The stream must have been created/updated with the AllowDirect boolean.
GetLastMsg(name, subject string, opts ...JSOpt) (*RawStreamMsg, error)

// DeleteMsg erases a message from a stream.
// DeleteMsg deletes a message from a stream. The message is marked as erased, but its value is not overwritten.
DeleteMsg(name string, seq uint64, opts ...JSOpt) error

// SecureDeleteMsg deletes a message from a stream. The deleted message is overwritten with random data
// As a result, this operation is slower than DeleteMsg()
SecureDeleteMsg(name string, seq uint64, opts ...JSOpt) error
Copy link
Member

Choose a reason for hiding this comment

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

Wonder if we should not add an option instead of a new API, as we did for the direct get. For instance, we could have a JSOpt that is called nats.EraseMsg() or nats.SecureDelete() that would set a boolean in *jsOpts (see DirectGet() option).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I thought about that, but I feel that in this case (having really only 2 options), 2 separate methods are a bit more straightforward to the user. JSOpt is already confusingly large bag of options and finding the one particular option which is applicable for a specific method is a hard job, even with good documentation.

Providing 2 methods on the other hand, should eliminate any confusion. If a user wants to delete message, they will stumble on 2 methods with relevant names: DeleteMsg(), which looks like a good starting point and SecureDeleteMsg(). Both have clear documentation and are not configurable (which is a good thing IMO).

WDYT?

Copy link
Member

Choose a reason for hiding this comment

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

I started with adding a new API for the "direct get" but was told that it was better to add options instead. I do agree - however - that the JSOpt can be a bit confusing.
To sump up, I don't have objections per-se to add a new API (actually, in the C client I have js_DeleteMsg() and js_EraseMsg() APIs), just felt that the will was to go with options instead of new APIs. If other reviewers in the list are OK with new API, I am ok too.

Copy link
Member

Choose a reason for hiding this comment

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

Usually I would lean into having an option in this case but after reading the ADR discussion, I reached the same conclusion in that in this case a new SecureDeleteMsg is what would fit better. TL;DR; of the ADR discussion, secure delete might have been a good default but considering the performance impact and the context of security, I think it sounds good to have its own function in this case.


// AddConsumer adds a consumer to a stream.
AddConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error)

Expand Down Expand Up @@ -1012,7 +1016,8 @@ func convertDirectGetMsgResponseToMsg(name string, r *Msg) (*RawStreamMsg, error
}

type msgDeleteRequest struct {
Seq uint64 `json:"seq"`
Seq uint64 `json:"seq"`
NoErase bool `json:"no_erase,omitempty"`
}

// msgDeleteResponse is the response for a Stream delete request.
Expand All @@ -1022,6 +1027,7 @@ type msgDeleteResponse struct {
}

// DeleteMsg deletes a message from a stream.
// The message is marked as erased, but not overwritten
func (js *js) DeleteMsg(name string, seq uint64, opts ...JSOpt) error {
o, cancel, err := getJSContextOpts(js.opts, opts...)
if err != nil {
Expand All @@ -1031,17 +1037,34 @@ func (js *js) DeleteMsg(name string, seq uint64, opts ...JSOpt) error {
defer cancel()
}

if name == _EMPTY_ {
return ErrStreamNameRequired
return js.deleteMsg(o.ctx, name, &msgDeleteRequest{Seq: seq, NoErase: true})
}

// SecureDeleteMsg deletes a message from a stream. The deleted message is overwritten with random data
// As a result, this operation is slower than DeleteMsg()
func (js *js) SecureDeleteMsg(name string, seq uint64, opts ...JSOpt) error {
Copy link
Member

Choose a reason for hiding this comment

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

If we go the option route, the implementation will simply have to set NoErase to opts.noErase (or whatever boolean you chose).

o, cancel, err := getJSContextOpts(js.opts, opts...)
if err != nil {
return err
}
if cancel != nil {
defer cancel()
}

req, err := json.Marshal(&msgDeleteRequest{Seq: seq})
return js.deleteMsg(o.ctx, name, &msgDeleteRequest{Seq: seq})
}

func (js *js) deleteMsg(ctx context.Context, stream string, req *msgDeleteRequest) error {
if err := checkStreamName(stream); err != nil {
return err
}
reqJSON, err := json.Marshal(req)
if err != nil {
return err
}

dsSubj := js.apiSubj(fmt.Sprintf(apiMsgDeleteT, name))
r, err := js.apiRequestWithContext(o.ctx, dsSubj, req)
dsSubj := js.apiSubj(fmt.Sprintf(apiMsgDeleteT, stream))
r, err := js.apiRequestWithContext(ctx, dsSubj, reqJSON)
if err != nil {
return err
}
Expand Down
131 changes: 131 additions & 0 deletions test/js_test.go
Expand Up @@ -2207,10 +2207,141 @@ func TestJetStreamManagement_DeleteMsg(t *testing.T) {
}
originalSeq := meta.Sequence.Stream

// create a subscription on delete message API subject to verify the content of delete operation
apiSub, err := nc.SubscribeSync("$JS.API.STREAM.MSG.DELETE.foo")
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
err = js.DeleteMsg("foo", originalSeq)
if err != nil {
t.Fatal(err)
}
msg, err = apiSub.NextMsg(1 * time.Second)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if str := string(msg.Data); !strings.Contains(str, "no_erase\":true") {
t.Fatalf("Request should not have no_erase field set: %s", str)
}

si, err = js.StreamInfo("foo")
if err != nil {
t.Fatal(err)
}
total = 14
if si.State.Msgs != total {
t.Errorf("Expected %d msgs, got: %d", total, si.State.Msgs)
}

// There should be only 4 messages since one deleted.
expected = 4
msgs = make([]*nats.Msg, 0)
ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

sub, err = js.Subscribe("foo.C", func(msg *nats.Msg) {
msgs = append(msgs, msg)

if len(msgs) == expected {
cancel()
}
})
if err != nil {
t.Fatal(err)
}
<-ctx.Done()
sub.Unsubscribe()

msg = msgs[0]
meta, err = msg.Metadata()
if err != nil {
t.Fatal(err)
}
newSeq := meta.Sequence.Stream

// First message removed
if newSeq <= originalSeq {
t.Errorf("Expected %d to be higher sequence than %d", newSeq, originalSeq)
}
}

func TestJetStreamManagement_SecureDeleteMsg(t *testing.T) {
s := RunBasicJetStreamServer()
Copy link
Member

Choose a reason for hiding this comment

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

Since really we don't know - from the client perspective - the difference between a delete and secure delete, what I would do is simply make sure that the client's "delete message request" contains the noErase boolean when it is a simple delete and not (or set to false) when using the secure version. This is done by creating a NATS subscription on the delete API subject and inspecting the content (see TestJetStreamConsumerConfigReplicasAndMemStorage for example)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good idea, I'll add that.

Copy link
Member

Choose a reason for hiding this comment

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

I would have personally JUST done the check of the API request containing the no_erase (or not), the rest is testing server behavior really, but that's ok since code is already done.

defer shutdownJSServerAndRemoveStorage(t, s)

nc, js := jsClient(t, s)
defer nc.Close()

var err error

_, err = js.AddStream(&nats.StreamConfig{
Name: "foo",
Subjects: []string{"foo.A", "foo.B", "foo.C"},
})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}

for i := 0; i < 5; i++ {
js.Publish("foo.A", []byte("A"))
js.Publish("foo.B", []byte("B"))
js.Publish("foo.C", []byte("C"))
}

si, err := js.StreamInfo("foo")
if err != nil {
t.Fatal(err)
}
var total uint64 = 15
if si.State.Msgs != total {
t.Errorf("Expected %d msgs, got: %d", total, si.State.Msgs)
}

expected := 5
msgs := make([]*nats.Msg, 0)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

sub, err := js.Subscribe("foo.C", func(msg *nats.Msg) {
msgs = append(msgs, msg)
if len(msgs) == expected {
cancel()
}
})
if err != nil {
t.Fatal(err)
}
<-ctx.Done()
sub.Unsubscribe()

got := len(msgs)
if got != expected {
t.Fatalf("Expected %d, got %d", expected, got)
}

msg := msgs[0]
meta, err := msg.Metadata()
if err != nil {
t.Fatal(err)
}
originalSeq := meta.Sequence.Stream

// create a subscription on delete message API subject to verify the content of delete operation
apiSub, err := nc.SubscribeSync("$JS.API.STREAM.MSG.DELETE.foo")
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
err = js.SecureDeleteMsg("foo", originalSeq)
if err != nil {
t.Fatal(err)
}
msg, err = apiSub.NextMsg(1 * time.Second)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if str := string(msg.Data); strings.Contains(str, "no_erase\":true") {
t.Fatalf("Request should not have no_erase field set: %s", str)
}

si, err = js.StreamInfo("foo")
if err != nil {
Expand Down