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

Fix assignability of wrong message type in create #972

Merged

Conversation

timostamm
Copy link
Member

@timostamm timostamm commented Sep 18, 2024

The function create() takes an optional initializer object as the second argument. In the object, all fields of the message are optional.

Because of a confusion in the type, it also accepts a message of a different type, as long as the type is assignable (any non-optional property in the target is also present in the source with the same name and type). This results in broken behavior with field presence, where passing a message with unset fields will populate fields in the target with the default value.

Here is an example that demonstrates the issue:

syntax = "proto2";

message A {
  optional string str = 1;
}

message B {
  optional string str = 1;
}
import { create } from "@bufbuild/protobuf";
import { ASchema, BSchema } from "./gen/example_pb";

const a = create(ASchema);
isFieldSet(a, ASchema.str); // false
a.str; // ""

const b = create(BSchema, a); // Type A is assignable to the init argument for B.
isFieldSet(b, BSchema.str); // true 💥
b.str; // ""

We thought that we prevent this situation with the $typeName property, but there is a bug in the internal MessageInit type that bypasses the type branding.

This PR fixes the bug. This is a breaking change because it introduces a compile-time error for a situation that previously compiled without complaints. Since the situation should be very rare, and most likely a bug in itself, we decided to make this change and release it as a bugfix.

@timostamm timostamm force-pushed the tstamm/Fix-assignability-of-wrong-message-type-in-create branch from 609a324 to 50e8324 Compare September 18, 2024 10:50
@timostamm timostamm marked this pull request as ready for review September 18, 2024 11:08
@timostamm timostamm merged commit 47d89b9 into main Sep 18, 2024
18 checks passed
@timostamm timostamm deleted the tstamm/Fix-assignability-of-wrong-message-type-in-create branch September 18, 2024 14:22
@timostamm timostamm mentioned this pull request Sep 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants