Skip to content

Reject encoding nil inside CBOR indefinite-length string#750

Merged
fxamacker merged 1 commit intomasterfrom
fxamacker/reject-encoding-nil-in-indefinite-length-string
Mar 22, 2026
Merged

Reject encoding nil inside CBOR indefinite-length string#750
fxamacker merged 1 commit intomasterfrom
fxamacker/reject-encoding-nil-in-indefinite-length-string

Conversation

@fxamacker
Copy link
Copy Markdown
Owner

@fxamacker fxamacker commented Mar 22, 2026

Generally, using indefinite-length has security considerations, etc. unrelated to this library.

This PR adds a defensive check to prevent programs from incorrectly using this library to create CBOR indefinite-length strings having a CBOR nil value as a chunk.

Details

CBOR indefinite-length strings must only contain zero or more definite length strings (aka chunks), and a "break" stop code indicates the end of indefinite-length string.

Previously, the encoder did not reject attempts to encode a nil value (instead of a chunk) to CBOR indefinite-length strings.

This PR makes the codec return an error when attempting to encode a CBOR nil as a chunk in a CBOR indefinite-length string.

Also added tests to check that the encoder rejects this from now on.

CBOR indefinite-length strings must only contain
zero or more definite length strings (aka chunks), and
a "break" stop code terminates the indefinite-length string.

Previously, the encoder did not reject attempts to encode
a nil value (instead of a chunk) to CBOR indefinite-length
strings.

This commit makes the encoder return an error when attempting
to encode a nil to a CBOR indefinite-length string.

Also added tests to check for this scenario.
@fxamacker fxamacker self-assigned this Mar 22, 2026
@fxamacker
Copy link
Copy Markdown
Owner Author

@x448 PTAL 🙏

I found this bug while refactoring.

Comment thread stream_test.go
t.Errorf("Encode() returned error %q, want %q", err.Error(), "cbor: cannot encode item type slice for indefinite-length text string")
}
if err := encoder.Encode(123); err == nil {
t.Errorf("Encode() didn't return an error")
Copy link
Copy Markdown
Contributor

@x448 x448 Mar 22, 2026

Choose a reason for hiding this comment

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

This error message is confusing to me. It's easier to understand if it says something like "expected error foo but got nil error".

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Good point! I found more of these, so I will open separate PR to clean them up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants