cabo / cbor-ruby

CBOR (RFC 7049) extension for Ruby
45 stars 12 forks source link

Unpacker doesn't throw exceptions #18

Closed PhKP closed 1 year ago

PhKP commented 1 year ago

First of all, thank you very much for creating the gem!

I am currently integrating the library into an application and stumbled upon something where I'm getting different behavior then expected.

Consider the following:

require 'cbor'
unpacker = CBOR::Unpacker.new
invalid_cbor = "\xA1\x64\x64\x74\x65\x73\x74\x63\x68\x65\x6A" # A16464746573746368656A
unpacker.feed_each(invalid_cbor) do |obj|
    puts obj
end

I am expecting the unpacker to raise an exception (maybe Exception: CBOR::MalformedFormatError) but it seems that no matter what I feed it I cannot make that happen.

Is it just me or isn't the parse error handling missing?

cabo commented 1 year ago

invalid_cbor is an incomplete encoded CBOR data item.

CBOR.decode(invalid_cbor)
(irb):6:in `decode': end of buffer reached (EOFError)

CBOR.decode(invalid_cbor + "0" * 16)
=> {"dtes"=>"chej0000000000000000"}

After receiving the incomplete item, unpacker's feed_each doesn't have a complete item to return.

If you complete the item:

 unpacker.feed_each("0"*16) do |obj|
    puts obj
 end
{"dtes"=>"chej0000000000000000"}

you get the decoded item.

PhKP commented 1 year ago

Okay, so invalid_cbor isn't actually invalid.. It's just incomplete. My mistake.

My problem is then that when my application (which is a server) receives an data from a client which is encoded as json and not cbor (which can happen if user misconfigures something), then my server just thinks it's incomplete cbor and waits for more data... Hmm.. I will have to implement handing for this issue in another way then.

require 'cbor'
require 'json'
data_from_misconfigured_client = ["This_is_from_a_misconfigured_client"].to_json
unpacker = CBOR::Unpacker.new
unpacker.feed_each(data_from_misconfigured_client) do |obj| # I need to implement some error handling that detects if data is json and not cbor
    puts obj
end
puts CBOR.decode(data_from_misconfigured_client)

But that's my problem and not something that I can expect the library to detect.

Thank you for your time!