/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License v. 2.0. If a copy of the MPL was not distributed with this file
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <algorithm>
#include <string>
#include <vector>

#if !defined(_WIN32) && defined(__LP64__)
#include <cstring>
#include <sys/mman.h>
#endif

#include "gtest/gtest.h"

#include "der_encode.h"
#include "nss.h"
#include "plarena.h"
#include "scoped_ptrs_smime.h"
#include "secasn1.h"
#include "secoid.h"
#include "smime.h"

namespace nss_test {

// See bug 1507174; this is a CMS serialization (RFC 5652) that claims to be
// 12336 bytes long, which ensures CMS validates the streaming decoder's
// incorrect length.
static const unsigned char kHugeLenAsn1[] = {
    0x30, 0x82, 0x30, 0x30, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
    0x0D, 0x01, 0x07, 0x02, 0xA0, 0x82, 0x02, 0x30, 0x30, 0x30, 0x02,
    0x01, 0x30, 0x31, 0x0F, 0x30, 0x0D, 0x06, 0x09, 0x30, 0x30, 0x30,
    0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x00, 0x30, 0x0B, 0x06,
    0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x05};

// secp256r1 signature with no certs and no attrs
static unsigned char kValidSignature[] = {
    0x30, 0x81, 0xFE, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01,
    0x07, 0x02, 0xA0, 0x81, 0xF0, 0x30, 0x81, 0xED, 0x02, 0x01, 0x01, 0x31,
    0x0F, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04,
    0x02, 0x01, 0x05, 0x00, 0x30, 0x0B, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86,
    0xF7, 0x0D, 0x01, 0x07, 0x01, 0x31, 0x81, 0xC9, 0x30, 0x81, 0xC6, 0x02,
    0x01, 0x01, 0x30, 0x5D, 0x30, 0x45, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
    0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06,
    0x03, 0x55, 0x04, 0x08, 0x0C, 0x0A, 0x53, 0x6F, 0x6D, 0x65, 0x2D, 0x53,
    0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1F, 0x06, 0x03, 0x55, 0x04,
    0x0A, 0x0C, 0x18, 0x49, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x65, 0x74, 0x20,
    0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20,
    0x4C, 0x74, 0x64, 0x02, 0x14, 0x6B, 0x22, 0xCA, 0x91, 0xE0, 0x71, 0x97,
    0xEB, 0x45, 0x0D, 0x68, 0xC0, 0xD4, 0xB6, 0xE9, 0x45, 0x38, 0x4C, 0xDD,
    0xA3, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04,
    0x02, 0x01, 0x05, 0x00, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE,
    0x3D, 0x04, 0x03, 0x02, 0x04, 0x47, 0x30, 0x45, 0x02, 0x20, 0x48, 0xEB,
    0xE6, 0xBA, 0xFC, 0xFD, 0x83, 0xB3, 0xA2, 0xB5, 0x59, 0x35, 0x0C, 0xA1,
    0x31, 0x0E, 0x2F, 0xE3, 0x8D, 0x81, 0xD8, 0xF5, 0x33, 0xE4, 0x83, 0x87,
    0xB1, 0xFD, 0x43, 0x9D, 0x95, 0x7D, 0x02, 0x21, 0x00, 0xD0, 0x05, 0x0E,
    0x05, 0xA6, 0x80, 0x3C, 0x1A, 0xFE, 0x51, 0xFC, 0x4D, 0x1A, 0x25, 0x05,
    0x78, 0xB5, 0x42, 0xF5, 0xDE, 0x4E, 0x8A, 0xF8, 0xE3, 0xD8, 0x52, 0xDC,
    0x2B, 0x73, 0x80, 0x4A, 0x1A};

// See bug 1507135; this is a CMS signature that contains only the OID
static unsigned char kTruncatedSignature[] = {0x30, 0x0B, 0x06, 0x09, 0x2A,
                                              0x86, 0x48, 0x86, 0xF7, 0x0D,
                                              0x01, 0x07, 0x02};

// secp256r1 signature that's truncated by one byte.
static unsigned char kSlightlyTruncatedSignature[] = {
    0x30, 0x81, 0xFE, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01,
    0x07, 0x02, 0xA0, 0x81, 0xF0, 0x30, 0x81, 0xED, 0x02, 0x01, 0x01, 0x31,
    0x0F, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04,
    0x02, 0x01, 0x05, 0x00, 0x30, 0x0B, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86,
    0xF7, 0x0D, 0x01, 0x07, 0x01, 0x31, 0x81, 0xC9, 0x30, 0x81, 0xC6, 0x02,
    0x01, 0x01, 0x30, 0x5D, 0x30, 0x45, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
    0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06,
    0x03, 0x55, 0x04, 0x08, 0x0C, 0x0A, 0x53, 0x6F, 0x6D, 0x65, 0x2D, 0x53,
    0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1F, 0x06, 0x03, 0x55, 0x04,
    0x0A, 0x0C, 0x18, 0x49, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x65, 0x74, 0x20,
    0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20,
    0x4C, 0x74, 0x64, 0x02, 0x14, 0x6B, 0x22, 0xCA, 0x91, 0xE0, 0x71, 0x97,
    0xEB, 0x45, 0x0D, 0x68, 0xC0, 0xD4, 0xB6, 0xE9, 0x45, 0x38, 0x4C, 0xDD,
    0xA3, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04,
    0x02, 0x01, 0x05, 0x00, 0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE,
    0x3D, 0x04, 0x03, 0x02, 0x04, 0x47, 0x30, 0x45, 0x02, 0x20, 0x48, 0xEB,
    0xE6, 0xBA, 0xFC, 0xFD, 0x83, 0xB3, 0xA2, 0xB5, 0x59, 0x35, 0x0C, 0xA1,
    0x31, 0x0E, 0x2F, 0xE3, 0x8D, 0x81, 0xD8, 0xF5, 0x33, 0xE4, 0x83, 0x87,
    0xB1, 0xFD, 0x43, 0x9D, 0x95, 0x7D, 0x02, 0x21, 0x00, 0xD0, 0x05, 0x0E,
    0x05, 0xA6, 0x80, 0x3C, 0x1A, 0xFE, 0x51, 0xFC, 0x4D, 0x1A, 0x25, 0x05,
    0x78, 0xB5, 0x42, 0xF5, 0xDE, 0x4E, 0x8A, 0xF8, 0xE3, 0xD8, 0x52, 0xDC,
    0x2B, 0x73, 0x80, 0x4A};

// AuthEnvelopedData (RFC 5083) encrypted to Fran with AES-128-GCM, PKCS#1 v1.5
static unsigned char kAuthEnvelopedData[] = {
    0x30, 0x82, 0x02, 0x07, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
    0x01, 0x09, 0x10, 0x01, 0x17, 0xa0, 0x82, 0x01, 0xf6, 0x30, 0x82, 0x01,
    0xf2, 0x02, 0x01, 0x00, 0x31, 0x82, 0x01, 0xa6, 0x30, 0x82, 0x01, 0xa2,
    0x02, 0x01, 0x00, 0x30, 0x81, 0x89, 0x30, 0x71, 0x31, 0x0b, 0x30, 0x09,
    0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x13, 0x30,
    0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, 0x43, 0x61, 0x6c, 0x69,
    0x66, 0x6f, 0x72, 0x6e, 0x69, 0x61, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
    0x55, 0x04, 0x07, 0x13, 0x0d, 0x4d, 0x6f, 0x75, 0x6e, 0x74, 0x61, 0x69,
    0x6e, 0x20, 0x56, 0x69, 0x65, 0x77, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03,
    0x55, 0x04, 0x0a, 0x13, 0x09, 0x42, 0x4f, 0x47, 0x55, 0x53, 0x20, 0x4e,
    0x53, 0x53, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13,
    0x18, 0x4e, 0x53, 0x53, 0x20, 0x50, 0x72, 0x65, 0x67, 0x65, 0x6e, 0x65,
    0x72, 0x61, 0x74, 0x65, 0x64, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43,
    0x41, 0x02, 0x14, 0x4c, 0x98, 0x1f, 0x68, 0xed, 0xe1, 0x8f, 0xf1, 0xe1,
    0x06, 0xcc, 0x05, 0xda, 0xdb, 0xf2, 0x31, 0xa9, 0x67, 0xa9, 0xad, 0x30,
    0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01,
    0x05, 0x00, 0x04, 0x82, 0x01, 0x00, 0x5a, 0x14, 0x13, 0x92, 0x34, 0xd5,
    0x04, 0x75, 0xe5, 0x32, 0xeb, 0x69, 0xaf, 0x22, 0x50, 0xab, 0xd5, 0xf4,
    0xcc, 0xd8, 0x55, 0x8c, 0x63, 0x87, 0xcf, 0xf9, 0xb6, 0x8c, 0x44, 0x6e,
    0x3b, 0x0a, 0x1b, 0x20, 0x6b, 0x72, 0x9e, 0xaf, 0xad, 0x17, 0xde, 0x78,
    0x52, 0x23, 0x35, 0xea, 0xbb, 0x40, 0x79, 0x23, 0x95, 0xeb, 0xd0, 0xc3,
    0x63, 0xa9, 0x44, 0x0c, 0x12, 0x85, 0x81, 0x98, 0x55, 0xfc, 0x20, 0x11,
    0xd6, 0x92, 0x87, 0x73, 0x44, 0x49, 0xc1, 0xf5, 0x14, 0x1f, 0x2e, 0xee,
    0x7f, 0xa1, 0xa1, 0x06, 0xa2, 0x87, 0xb7, 0x29, 0x63, 0x9f, 0x07, 0x47,
    0xfb, 0x92, 0x5a, 0x66, 0x13, 0x7e, 0x1c, 0xae, 0x58, 0x51, 0x71, 0xde,
    0xcf, 0x09, 0x17, 0x7c, 0xce, 0x4e, 0x23, 0xc9, 0x85, 0x96, 0x75, 0xcf,
    0x08, 0xea, 0xfc, 0xf0, 0x54, 0x02, 0xc8, 0x2e, 0x69, 0xae, 0x84, 0x11,
    0xd9, 0x24, 0xb2, 0xbf, 0x1d, 0x1b, 0x57, 0xce, 0x41, 0x5e, 0x13, 0x25,
    0x39, 0xfd, 0xd2, 0xa3, 0x70, 0x75, 0xa9, 0x40, 0xd7, 0x92, 0x16, 0x80,
    0x3b, 0xcf, 0x70, 0x6c, 0x1e, 0x8a, 0x95, 0x00, 0x35, 0xfd, 0xbd, 0xb4,
    0xd7, 0x19, 0x64, 0xb8, 0x31, 0x75, 0x71, 0xa5, 0xbf, 0x73, 0xcf, 0x61,
    0xce, 0x21, 0xed, 0x6c, 0x0b, 0x2c, 0x9f, 0xb7, 0x52, 0xb6, 0x0c, 0x91,
    0x36, 0xb2, 0xda, 0x68, 0x0f, 0xee, 0x28, 0xc8, 0x5c, 0xca, 0xd6, 0x27,
    0x91, 0x2f, 0xd5, 0xf5, 0x1a, 0x4f, 0x4f, 0xda, 0x78, 0xd4, 0x05, 0xb7,
    0x10, 0x42, 0x59, 0x6f, 0xb1, 0x47, 0x05, 0x61, 0xe0, 0xea, 0x89, 0x90,
    0xdc, 0x42, 0x4e, 0xd3, 0xa2, 0x8a, 0xad, 0x42, 0x8b, 0xd9, 0x24, 0x93,
    0x14, 0xba, 0x46, 0x3b, 0xd2, 0x6c, 0x2f, 0xcc, 0x62, 0x9d, 0xc6, 0x2d,
    0x0f, 0xfe, 0x43, 0x1f, 0x55, 0x1c, 0x80, 0xdc, 0xfc, 0x98, 0x30, 0x31,
    0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0x30,
    0x1e, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x06,
    0x30, 0x11, 0x04, 0x0c, 0xc6, 0x9f, 0xfd, 0x30, 0x97, 0xa4, 0x4d, 0x52,
    0x17, 0xb1, 0x56, 0xf3, 0x02, 0x01, 0x10, 0x80, 0x04, 0x67, 0x28, 0x3e,
    0x1c, 0x04, 0x10, 0xb4, 0xb2, 0x9c, 0x8c, 0x90, 0x28, 0x00, 0x94, 0x94,
    0x34, 0xa7, 0x03, 0x19, 0xb7, 0x34, 0x23};

class SMimeTest : public ::testing::Test {};

TEST_F(SMimeTest, InvalidDER) {
  PK11SymKey* bulk_key = nullptr;
  NSSCMSDecoderContext* dcx =
      NSS_CMSDecoder_Start(nullptr, nullptr, nullptr, /* content callback  */
                           nullptr, nullptr,          /* password callback */
                           nullptr,                   /* key callback      */
                           bulk_key);
  ASSERT_NE(nullptr, dcx);
  EXPECT_EQ(SECSuccess, NSS_CMSDecoder_Update(
                            dcx, reinterpret_cast<const char*>(kHugeLenAsn1),
                            sizeof(kHugeLenAsn1)));
  EXPECT_EQ(nullptr, bulk_key);
  ASSERT_FALSE(NSS_CMSDecoder_Finish(dcx));
}

TEST_F(SMimeTest, IsSignedValid) {
  SECItem sig_der_item = {siBuffer, kValidSignature, sizeof(kValidSignature)};

  ScopedNSSCMSMessage cms_msg(NSS_CMSMessage_CreateFromDER(
      &sig_der_item, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr));

  ASSERT_TRUE(cms_msg);

  ASSERT_TRUE(NSS_CMSMessage_IsSigned(cms_msg.get()));
}

TEST_F(SMimeTest, TruncatedCmsSignature) {
  SECItem sig_der_item = {siBuffer, kTruncatedSignature,
                          sizeof(kTruncatedSignature)};

  ScopedNSSCMSMessage cms_msg(NSS_CMSMessage_CreateFromDER(
      &sig_der_item, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr));

  ASSERT_TRUE(cms_msg);

  ASSERT_FALSE(NSS_CMSMessage_IsSigned(cms_msg.get()));
}

TEST_F(SMimeTest, SlightlyTruncatedCmsSignature) {
  SECItem sig_der_item = {siBuffer, kSlightlyTruncatedSignature,
                          sizeof(kSlightlyTruncatedSignature)};

  ScopedNSSCMSMessage cms_msg(NSS_CMSMessage_CreateFromDER(
      &sig_der_item, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr));

  ASSERT_FALSE(cms_msg);

  ASSERT_FALSE(NSS_CMSMessage_IsSigned(cms_msg.get()));
}

TEST_F(SMimeTest, IsSignedNull) {
  ASSERT_FALSE(NSS_CMSMessage_IsSigned(nullptr));
}

// Verify that the CMS streaming decoder rejects content large enough to
// trigger integer truncation in the buffer-growth path of work_data.
// This bug only manifests on LP64 where unsigned long is 64-bit and the
// 64-bit product is truncated when assigned to int.
#if !defined(_WIN32) && defined(__LP64__)
TEST_F(SMimeTest, CmsDecoderRejectsOversizeContent) {
  const size_t kLenA = 0x3F800000;
  const size_t kLenB = 0x42000000;

  // CMS SignedData with a constructed indefinite-length OCTET STRING
  // containing two large primitive substrings.
  static const uint8_t kHeader[] = {
      0x30,
      0x80,
      0x06,
      0x09,
      0x2A,
      0x86,
      0x48,
      0x86,
      0xF7,
      0x0D,
      0x01,
      0x07,
      0x02,
      0xA0,
      0x80,
      0x30,
      0x80,
      0x02,
      0x01,
      0x01,
      0x31,
      0x00,
      0x30,
      0x80,
      0x06,
      0x09,
      0x2A,
      0x86,
      0x48,
      0x86,
      0xF7,
      0x0D,
      0x01,
      0x07,
      0x01,
      0xA0,
      0x80,
      0x24,
      0x80,
      0x04,
      0x84,
      (uint8_t)(kLenA >> 24),
      (uint8_t)(kLenA >> 16),
      (uint8_t)(kLenA >> 8),
      (uint8_t)(kLenA),
  };
  static const uint8_t kMid[] = {
      0x04,
      0x84,
      (uint8_t)(kLenB >> 24),
      (uint8_t)(kLenB >> 16),
      (uint8_t)(kLenB >> 8),
      (uint8_t)(kLenB),
  };
  static const uint8_t kFooter[] = {
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  };

  const size_t total =
      sizeof(kHeader) + kLenA + sizeof(kMid) + kLenB + sizeof(kFooter);

  void* m = mmap(nullptr, total, PROT_READ | PROT_WRITE,
                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  ASSERT_NE(MAP_FAILED, m) << "mmap of " << total << " bytes failed";

  uint8_t* p = static_cast<uint8_t*>(m);
  memcpy(p, kHeader, sizeof(kHeader));
  memcpy(p + sizeof(kHeader) + kLenA, kMid, sizeof(kMid));
  memcpy(p + sizeof(kHeader) + kLenA + sizeof(kMid) + kLenB, kFooter,
         sizeof(kFooter));

  NSSCMSDecoderContext* dcx = NSS_CMSDecoder_Start(
      nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
  ASSERT_NE(nullptr, dcx);

  SECStatus rv =
      NSS_CMSDecoder_Update(dcx, reinterpret_cast<const char*>(p), total);

  NSSCMSMessage* msg = NSS_CMSDecoder_Finish(dcx);
  munmap(m, total);

  EXPECT_NE(SECSuccess, rv);
  if (msg) {
    NSS_CMSMessage_Destroy(msg);
  }
}
#endif  // !defined(_WIN32) && defined(__LP64__)

TEST_F(SMimeTest, AuthEnvelopedDataParses) {
  SECItem der_item = {siBuffer, kAuthEnvelopedData, sizeof(kAuthEnvelopedData)};

  ScopedNSSCMSMessage cms_msg(NSS_CMSMessage_CreateFromDER(
      &der_item, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr));

  ASSERT_TRUE(cms_msg);
}

TEST_F(SMimeTest, AuthEnvelopedDataIsEncrypted) {
  SECItem der_item = {siBuffer, kAuthEnvelopedData, sizeof(kAuthEnvelopedData)};

  ScopedNSSCMSMessage cms_msg(NSS_CMSMessage_CreateFromDER(
      &der_item, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr));

  ASSERT_TRUE(cms_msg);
  ASSERT_TRUE(NSS_CMSMessage_IsEncrypted(cms_msg.get()));
  ASSERT_FALSE(NSS_CMSMessage_IsSigned(cms_msg.get()));
}

// Mirror the internal NSSSMIMECapability layout from smimeutil.c
struct SMIMECapability {
  SECItem capabilityID;
  SECItem parameters;
};

static const SEC_ASN1Template SMIMECapabilityTemplate[] = {
    {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SMIMECapability)},
    {SEC_ASN1_OBJECT_ID, offsetof(SMIMECapability, capabilityID)},
    {SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, offsetof(SMIMECapability, parameters)},
    {0}};

static const SEC_ASN1Template SMIMECapabilitiesTemplate[] = {
    {SEC_ASN1_SEQUENCE_OF, 0, SMIMECapabilityTemplate}};

TEST_F(SMimeTest, SMIMECapabilitiesIncludeGCM) {
  PLArenaPool* arena = PORT_NewArena(1024);
  ASSERT_NE(nullptr, arena);

  SECItem encoded = {siBuffer, nullptr, 0};
  ASSERT_EQ(SECSuccess, NSS_SMIMEUtil_CreateSMIMECapabilities(arena, &encoded));

  // Decode the DER back into structured capabilities
  SMIMECapability** caps = nullptr;
  ASSERT_EQ(
      SECSuccess,
      SEC_QuickDERDecodeItem(
          arena,
          static_cast<void*>(
              &caps),  // NOLINT(bugprone-multi-level-implicit-pointer-conversion)
          SMIMECapabilitiesTemplate, &encoded));
  ASSERT_NE(nullptr, caps);

  // Collect OID tags in advertised order
  std::vector<SECOidTag> tags;
  for (int i = 0; caps[i] != nullptr; i++) {
    tags.push_back(SECOID_FindOIDTag(&caps[i]->capabilityID));
  }

  auto hasTag = [&tags](SECOidTag t) {
    return std::find(tags.begin(), tags.end(), t) != tags.end();
  };
  auto tagIndex = [&tags](SECOidTag t) -> int {
    auto it = std::find(tags.begin(), tags.end(), t);
    return it != tags.end() ? static_cast<int>(it - tags.begin()) : -1;
  };

  // All three GCM variants must be present
  EXPECT_TRUE(hasTag(SEC_OID_AES_128_GCM)) << "AES-128-GCM missing";
  EXPECT_TRUE(hasTag(SEC_OID_AES_192_GCM)) << "AES-192-GCM missing";
  EXPECT_TRUE(hasTag(SEC_OID_AES_256_GCM)) << "AES-256-GCM missing";

  // GCM must appear before its CBC counterpart (RFC 8551 preference)
  int idx256gcm = tagIndex(SEC_OID_AES_256_GCM);
  int idx256cbc = tagIndex(SEC_OID_AES_256_CBC);
  int idx128gcm = tagIndex(SEC_OID_AES_128_GCM);
  int idx128cbc = tagIndex(SEC_OID_AES_128_CBC);

  if (idx256gcm >= 0 && idx256cbc >= 0) {
    EXPECT_LT(idx256gcm, idx256cbc) << "AES-256-GCM should precede AES-256-CBC";
  }
  if (idx128gcm >= 0 && idx128cbc >= 0) {
    EXPECT_LT(idx128gcm, idx128cbc) << "AES-128-GCM should precede AES-128-CBC";
  }

  PORT_FreeArena(arena, PR_FALSE);
}

// Helper functions for DeepNestingRejected and ShallowNestingNotRejected
static Bytes NssOid(SECOidTag tag) {
  const SECOidData* od = SECOID_FindOIDByTag(tag);
  return OidVal(od->oid.data, od->oid.len);
}

static Bytes MakeNestedDigestedData(int levels) {
  Bytes alg = Seq(NssOid(SEC_OID_SHA1));

  // Innermost DigestedData: version 0 (NSS_CMS_DIGESTED_DATA_VERSION_DATA),
  // eContentType=id-data so nss_cms_before_data() returns early without
  // creating a child decoder.
  Bytes encap = Seq(Cat({NssOid(SEC_OID_PKCS7_DATA), Ctx0(OctetStr({0x00}))}));
  Bytes dd = Seq(
      Cat({Bytes{0x02, 0x01, 0x00}, alg, encap, OctetStr(Bytes(20, 0x00))}));

  // Each wrapper level uses version 2 (NSS_CMS_DIGESTED_DATA_VERSION_ENCAP)
  // because its eContentType is id-digestedData, not id-data.
  for (int i = 1; i < levels; i++) {
    encap = Seq(Cat({NssOid(SEC_OID_PKCS7_DIGESTED_DATA), Ctx0(OctetStr(dd))}));
    dd = Seq(
        Cat({Bytes{0x02, 0x01, 0x02}, alg, encap, OctetStr(Bytes(20, 0x00))}));
  }

  // Root ContentInfo wrapper (not itself a DigestedData level).
  return Seq(Cat({NssOid(SEC_OID_PKCS7_DIGESTED_DATA), Ctx0(dd)}));
}

// Bug 2023208: a CMS message whose nesting depth exceeds
// NSS_CMS_MAX_NESTING_DEPTH must be rejected cleanly by the setup-time check in
// nss_cms_before_data().
TEST_F(SMimeTest, DeepNestingRejected) {
  Bytes der = MakeNestedDigestedData(40);
  SECItem item = {siBuffer, der.data(), static_cast<unsigned int>(der.size())};
  ScopedNSSCMSMessage msg(NSS_CMSMessage_CreateFromDER(
      &item, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr));
  EXPECT_EQ(nullptr, msg.get());
}

TEST_F(SMimeTest, ShallowNestingNotRejected) {
  Bytes der = MakeNestedDigestedData(3);
  SECItem item = {siBuffer, der.data(), static_cast<unsigned int>(der.size())};
  ScopedNSSCMSMessage msg(NSS_CMSMessage_CreateFromDER(
      &item, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr));
  EXPECT_NE(nullptr, msg.get());
}

}  // namespace nss_test
