Subject: Keys: fix signature generation
Origin: v9-2-gafb6055 <https://github.com/latchset/tang/commit/v9-2-gafb6055>
Upstream-Author: Sergio Correia <scorreia@redhat.com>
Date: Fri Apr 30 11:30:24 2021 -0300

    No need to create and pass an array with our template option.
    This was causing issues when we had multiple (>2) pairs of keys.

    Tests added to cover this scenario.

--- a/src/keys.c
+++ b/src/keys.c
@@ -233,21 +233,11 @@
     json_auto_t* sig_template = json_pack("{s:{s:s}}",
                                           "protected", "cty", "jwk-set+json");
 
-    /* Use the template with the signing keys. */
-    json_auto_t* sig_template_arr = json_array();
-    size_t arr_size = json_array_size(sig_keys);
-    for (size_t i = 0; i < arr_size; i++) {
-        if (json_array_append(sig_template_arr, sig_template) == -1) {
-            fprintf(stderr, "Unable to append sig template to array\n");
-            return NULL;
-        }
-    }
-
     __attribute__ ((__cleanup__(cleanup_str))) char* data_to_sign = json_dumps(payload, 0);
     json_auto_t* jws = json_pack("{s:o}", "payload",
                                  jose_b64_enc(data_to_sign, strlen(data_to_sign)));
 
-    if (!jose_jws_sig(NULL, jws, sig_template_arr, sig_keys)) {
+    if (!jose_jws_sig(NULL, jws, sig_template, sig_keys)) {
         fprintf(stderr, "Error trying to jose_jws_sign\n");
         return NULL;
     }
--- a/tests/adv
+++ b/tests/adv
@@ -31,6 +31,19 @@
     [ -d "$TMP" ] && rm -rf $TMP
 }
 
+validate() {
+    if ! _jwks="$(jose fmt --json="${1}" -Og payload -SyOg keys \
+                 -AUo- 2>/dev/null)"; then
+        echo "Advertisement is malformed" >&2
+        exit 1
+    fi
+    _ver="$(printf '%s' "${_jwks}" | jose jwk use -i- -r -u verify -o-)"
+    if ! printf '%s' "${_ver}" | jose jws ver -i "${1}" -k- -a; then
+        echo "Advertisement is missing signatures" >&2
+        exit 1
+    fi
+}
+
 trap 'on_exit' EXIT
 trap 'exit' ERR
 
@@ -95,3 +108,18 @@
 done
 cd -
 fetch /adv
+
+# Lets's now test with multiple pairs of keys.
+for i in 1 2 3 4 5 6 7 8 9; do
+    tangd-keygen "${TMP}"/db other-sig-${i} other-exc-${i}
+done
+
+# Verify the advertisement is correct.
+validate "$(fetch /adv)"
+
+# And make sure we can fetch an adv by its thumbprint.
+for jwk in "${TMP}"/db/other-sig-*.jwk; do
+    for alg in $(jose alg -k hash); do
+        fetch /adv/"$(jose jwk thp -a "${alg}" -i "${jwk}")" | ver "${jwk}"
+    done
+done