reftable: ensure that obj_id_len is >= 2 on writing

When writing the same hash many times, we might decide to use a length-1 object ID prefix for the ObjectID => ref table, which is out of spec. Signed-off-by: Han-Wen Nienhuys <hanwen@google.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Han-Wen Nienhuys committed Feb 21, 2022 at 18:46 UTC b4007fcc6fe04deeeb3cdf7b018413f65c9de6e8
2 files changed +40 -1
reftable/readwrite_test.c
+37
@@ -667,6 +667,42 @@ static void test_write_empty_table(void)
667 strbuf_release(&buf);
668 }
669
670 +static void test_write_object_id_min_length(void)
671 +{
672 + struct reftable_write_options opts = {
673 + .block_size = 75,
674 + };
675 + struct strbuf buf = STRBUF_INIT;
676 + struct reftable_writer *w =
677 + reftable_new_writer(&strbuf_add_void, &buf, &opts);
678 + uint8_t hash[GIT_SHA1_RAWSZ] = {42};
679 + struct reftable_ref_record ref = {
680 + .update_index = 1,
681 + .value_type = REFTABLE_REF_VAL1,
682 + .value.val1 = hash,
683 + };
684 + int err;
685 + int i;
686 +
687 + reftable_writer_set_limits(w, 1, 1);
688 +
689 + /* Write the same hash in many refs. If there is only 1 hash, the
690 + * disambiguating prefix is length 0 */
691 + for (i = 0; i < 256; i++) {
692 + char name[256];
693 + snprintf(name, sizeof(name), "ref%05d", i);
694 + ref.refname = name;
695 + err = reftable_writer_add_ref(w, &ref);
696 + EXPECT_ERR(err);
697 + }
698 +
699 + err = reftable_writer_close(w);
700 + EXPECT_ERR(err);
701 + EXPECT(writer_stats(w)->object_id_len == 2);
702 + reftable_writer_free(w);
703 + strbuf_release(&buf);
704 +}
705 +
706 static void test_write_empty_key(void)
707 {
708 struct reftable_write_options opts = { 0 };
@@ -772,5 +808,6 @@ int readwrite_test_main(int argc, const char *argv[])
808 RUN_TEST(test_write_empty_key);
809 RUN_TEST(test_write_empty_table);
810 RUN_TEST(test_log_overflow);
811 + RUN_TEST(test_write_object_id_min_length);
812 return 0;
813 }
reftable/writer.c
+3 -1
@@ -515,7 +515,9 @@ static void object_record_free(void *void_arg, void *key)
515 static int writer_dump_object_index(struct reftable_writer *w)
516 {
517 struct write_record_arg closure = { .w = w };
518 - struct common_prefix_arg common = { NULL };
518 + struct common_prefix_arg common = {
519 + .max = 1, /* obj_id_len should be >= 2. */
520 + };
521 if (w->obj_index_tree) {
522 infix_walk(w->obj_index_tree, &update_common, &common);
523 }