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

Add a validate function. #39

Merged
merged 1 commit into from
Aug 14, 2020
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package typegen

import (
"bytes"
"fmt"
"io"
)

// ValidateCBOR validates that a byte array is a single valid CBOR object.
func ValidateCBOR(b []byte) error {
// The code here is basically identical to the previous function, it
// just doesn't copy.

br := bytes.NewReader(b)

// Allocate some scratch space.
scratch := make([]byte, maxHeaderSize)

for remaining := uint64(1); remaining > 0; remaining-- {
maj, extra, err := CborReadHeaderBuf(br, scratch)
if err != nil {
return err
}

switch maj {
case MajUnsignedInt, MajNegativeInt, MajOther:
// nothing fancy to do
case MajByteString, MajTextString:
if extra > ByteArrayMaxLen {
return maxLengthError
}
if uint64(br.Len()) < extra {
return io.ErrUnexpectedEOF
}

if _, err := br.Seek(int64(extra), io.SeekCurrent); err != nil {
return err
}
case MajTag:
remaining++
case MajArray:
if extra > MaxLength {
return maxLengthError
}
remaining += extra
case MajMap:
if extra > MaxLength {
return maxLengthError
}
remaining += extra * 2
default:
return fmt.Errorf("unhandled deferred cbor type: %d", maj)
}
}
if br.Len() > 0 {
return fmt.Errorf("unexpected %d unread bytes", br.Len())
}
return nil
}
42 changes: 42 additions & 0 deletions validate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package typegen

import (
"bytes"
"testing"
)

func TestValidateShort(t *testing.T) {
var buf bytes.Buffer
if err := WriteMajorTypeHeader(&buf, MajByteString, 100); err != nil {
t.Fatal("failed to write header")
}

if err := ValidateCBOR(buf.Bytes()); err == nil {
t.Fatal("expected an error checking truncated cbor")
}
}

func TestValidateDouble(t *testing.T) {
var buf bytes.Buffer
if err := WriteBool(&buf, false); err != nil {
t.Fatal(err)
}
if err := WriteBool(&buf, false); err != nil {
t.Fatal(err)
}

if err := ValidateCBOR(buf.Bytes()); err == nil {
t.Fatal("expected an error checking cbor with two objects")
}
}

func TestValidate(t *testing.T) {
var buf bytes.Buffer
if err := WriteBool(&buf, false); err != nil {
t.Fatal(err)
}

if err := ValidateCBOR(buf.Bytes()); err != nil {
t.Fatal(err)
}
}