google / protobuf.dart

Runtime library for Dart protobufs
https://pub.dev/packages/protobuf
BSD 3-Clause "New" or "Revised" License
533 stars 185 forks source link

`readonlyDefault` for map fields returns mutable map #705

Open osa1 opened 2 years ago

osa1 commented 2 years ago

https://github.com/google/protobuf.dart/blob/6a3e7f024a46b9353fd172abe2b80125244cae45/protobuf/lib/src/protobuf/field_info.dart#L160-L165

which for map fields calls https://github.com/google/protobuf.dart/blob/6a3e7f024a46b9353fd172abe2b80125244cae45/protobuf/lib/src/protobuf/field_info.dart#L282

which uses PbMap, instead of PbMap.unmodifiable.

osa1 commented 2 years ago

Repro:

syntax = "proto3";

message Test {
  map<int32, int32> map_field = 1;
  repeated int32 repeated_field = 2;
  NestedMsg message_field = 3;
}

message NestedMsg {
  int32 int_field = 1;
}
import '../test.pb.dart';
import 'package:protobuf/protobuf.dart';

void main() {
  final msg = (Test().freeze()) as Test;

  final map = (msg.getDefaultForField(1)) as PbMap;
  map[1] = 2; // works
  print('OK');

  final nestedMsg = msg.getDefaultForField(3) as NestedMsg;
  try {
    nestedMsg.intField = 123; // fails as expected
  } catch (e) {
    print('OK');
  }

  final list = (msg.getDefaultForField(2)) as PbList;
  try {
    list.add(1); // fails as expected
  } catch (e) {
    print('OK');
  }
}