//! Cross-implementation interop fixtures for the encrypted-CEK envelope.
//!
//! `MS_JDBC_ENVELOPE` below was produced by Microsoft's shipped JDBC driver
//! (mssql-jdbc 12.10.1, `SQLServerColumnEncryptionJavaKeyStoreProvider`,
//! public API) wrapping the test CEK with the RSA key in
//! `fixtures/test_cmk_rsa2048.pem`. The same canonical layout is used by all
//! Microsoft Always Encrypted clients (.NET, SSMS, ODBC, PowerShell):
//!
//! ```text
//! version(0x01) || keyPathLen(u16 LE) || cipherLen(u16 LE)
//!               || keyPath(UTF-16LE)  || ciphertext || RSA-PKCS1-SHA256 signature
//! ```
//!
//! Decrypting it proves the parser layout AND the mandatory signature
//! verification match what real-world provisioning tools emit. A self
//! round-trip cannot catch a layout that is internally consistent but
//! non-conformant (the v0.9.0 lesson, twice over).
//!
//! Regenerate with `fixtures/CekHarness.java` (full recipe in its header);
//! the fixture is stable because parse + RSA-OAEP decrypt of a captured
//! envelope is deterministic.

#![cfg(feature = "always-encrypted")]
#![allow(clippy::expect_used)]

use mssql_auth::encryption::KeyStoreProvider;
use mssql_auth::key_store::InMemoryKeyStore;

/// PKCS#8 PEM RSA-2048 private key. Test fixture only — never use for real data.
const TEST_CMK_PEM: &str = include_str!("fixtures/test_cmk_rsa2048.pem");

/// Key path / keystore alias used when the fixture was generated.
const KEY_PATH: &str = "rmd-test-cmk";

/// The wrapped CEK: bytes 0x00..=0x1f.
fn expected_cek() -> Vec<u8> {
    (0u8..32).collect()
}

/// Encrypted-CEK envelope produced by mssql-jdbc 12.10.1 (Microsoft binary).
/// Layout: 1 + 2 + 2 + 24 (path) + 256 (ciphertext) + 256 (signature).
const MS_JDBC_ENVELOPE: [u8; 541] = [
    0x01, 0x18, 0x00, 0x00, 0x01, 0x72, 0x00, 0x6d, 0x00, 0x64, 0x00, 0x2d, 0x00, 0x74, 0x00, 0x65,
    0x00, 0x73, 0x00, 0x74, 0x00, 0x2d, 0x00, 0x63, 0x00, 0x6d, 0x00, 0x6b, 0x00, 0x52, 0xc7, 0x90,
    0x5a, 0x33, 0x4b, 0xe0, 0xc4, 0x7e, 0x67, 0x90, 0x00, 0x65, 0xeb, 0x57, 0xb8, 0x14, 0x51, 0x6a,
    0xd0, 0xa4, 0x3f, 0xe8, 0xbe, 0x77, 0x81, 0x95, 0xab, 0x65, 0xd2, 0x49, 0x2c, 0xc7, 0xd6, 0x8a,
    0x30, 0x24, 0xcd, 0x70, 0x03, 0x8d, 0x3d, 0x7d, 0x39, 0x57, 0x53, 0x6f, 0x87, 0x46, 0x34, 0x3c,
    0x22, 0x07, 0x33, 0x15, 0x10, 0x70, 0xf6, 0x40, 0xff, 0x68, 0xa9, 0x97, 0x79, 0x66, 0x11, 0x35,
    0xcb, 0x4b, 0x77, 0xab, 0x9a, 0x84, 0x3b, 0xca, 0x19, 0xa2, 0x48, 0xbb, 0x99, 0x04, 0xe5, 0xf6,
    0xab, 0xa8, 0xcc, 0x2a, 0xe5, 0xd9, 0xad, 0xb0, 0xc6, 0xc8, 0x7a, 0x06, 0x2d, 0x37, 0x26, 0x6e,
    0x7a, 0x07, 0xb4, 0x3b, 0xbd, 0xcc, 0x9c, 0x46, 0x8a, 0x90, 0xac, 0x10, 0xd0, 0x01, 0xa0, 0xec,
    0x00, 0x59, 0x6e, 0x20, 0x95, 0xa3, 0x64, 0xc9, 0xce, 0xdd, 0x1f, 0x42, 0x64, 0x73, 0xd7, 0x6b,
    0x8d, 0x97, 0x6c, 0xb6, 0xb9, 0x58, 0xdf, 0x6d, 0x46, 0xc0, 0x4c, 0x0a, 0xa7, 0x7f, 0x39, 0x14,
    0xdc, 0x7f, 0x17, 0xd0, 0x0a, 0xf7, 0x33, 0xc1, 0x80, 0x42, 0xc4, 0xa8, 0xc9, 0x73, 0x5f, 0xd5,
    0x0c, 0x3a, 0x49, 0x51, 0x0d, 0xd2, 0x82, 0xf8, 0xc1, 0x40, 0xeb, 0xa5, 0xc9, 0x75, 0xd7, 0x5f,
    0xf2, 0x40, 0x2a, 0x2f, 0x4b, 0xe6, 0xa3, 0x3a, 0xfb, 0xd5, 0x9f, 0x08, 0x87, 0x05, 0xb3, 0x96,
    0x8a, 0x5a, 0x72, 0x78, 0xf3, 0xa6, 0xe4, 0xae, 0x33, 0x45, 0xe3, 0x5c, 0x32, 0x94, 0xa5, 0xad,
    0xd9, 0x13, 0xad, 0x42, 0x99, 0x04, 0xea, 0x82, 0x57, 0x03, 0xf1, 0xd0, 0x03, 0x4a, 0x4d, 0x3b,
    0x07, 0x01, 0x26, 0x9c, 0xbe, 0x6a, 0xff, 0xc7, 0xd4, 0x73, 0x8b, 0x6b, 0xb5, 0xff, 0x1f, 0xc2,
    0xe5, 0xe6, 0x69, 0x37, 0x5a, 0x22, 0x17, 0x82, 0xe6, 0x4f, 0xab, 0x0c, 0x79, 0xae, 0xf6, 0x62,
    0xba, 0xbd, 0x17, 0x1b, 0x01, 0x49, 0xa3, 0x47, 0xcf, 0xe3, 0xca, 0xf5, 0xcc, 0xba, 0xf7, 0xf3,
    0xe0, 0xfe, 0x2d, 0x0b, 0x5e, 0x3b, 0xbc, 0xb6, 0xd2, 0x99, 0x2f, 0xd1, 0xaa, 0x74, 0x8a, 0xba,
    0xf9, 0x45, 0x88, 0x1b, 0xfa, 0x18, 0x59, 0xe6, 0x95, 0x44, 0x5e, 0x76, 0x12, 0x88, 0xff, 0x1b,
    0x31, 0xe9, 0x0c, 0x36, 0x24, 0xa0, 0x67, 0xc8, 0xd2, 0x8a, 0x9e, 0x31, 0x8b, 0x19, 0x4c, 0xc7,
    0x62, 0xac, 0x6e, 0xe9, 0xbd, 0x38, 0x7a, 0xdd, 0xe5, 0x87, 0xd2, 0x03, 0xec, 0x0b, 0xf9, 0xcc,
    0xe8, 0xf0, 0xfb, 0x79, 0x4e, 0x63, 0x36, 0x48, 0x38, 0xeb, 0xfc, 0x25, 0xc7, 0xbe, 0x35, 0x9d,
    0x70, 0x01, 0x66, 0x24, 0x61, 0x77, 0x86, 0x12, 0xff, 0xcb, 0xd8, 0x83, 0x33, 0x4d, 0x26, 0xd9,
    0xe7, 0x5a, 0xb8, 0x47, 0x26, 0xd4, 0x1d, 0x69, 0x44, 0xb9, 0x98, 0xb3, 0x5a, 0x86, 0xb9, 0x6c,
    0x68, 0xdf, 0xec, 0xb4, 0x58, 0x97, 0x64, 0x27, 0x34, 0x71, 0xbe, 0xff, 0x6f, 0xc2, 0x03, 0x93,
    0x76, 0xd6, 0x22, 0x46, 0x14, 0x1b, 0x30, 0xbc, 0xfb, 0x8e, 0x0a, 0x89, 0x9e, 0x2e, 0xfe, 0x6a,
    0xac, 0xf6, 0xbb, 0xe2, 0xf9, 0xec, 0xe2, 0x12, 0xe3, 0xdc, 0x1d, 0x84, 0x0d, 0x5a, 0xb4, 0xef,
    0xf2, 0x67, 0xb0, 0xec, 0x11, 0x31, 0x58, 0x13, 0x25, 0x02, 0x77, 0x41, 0xbf, 0x91, 0xa7, 0x13,
    0xfa, 0x3a, 0x83, 0x8f, 0xdd, 0x4d, 0x63, 0x65, 0xa0, 0xbf, 0x42, 0x35, 0xbd, 0x82, 0x44, 0xa2,
    0x53, 0x76, 0x84, 0x05, 0x49, 0x28, 0x23, 0x7a, 0x58, 0xee, 0x71, 0xb4, 0xc3, 0x8d, 0x50, 0x7f,
    0x48, 0xb1, 0xa8, 0x30, 0x0d, 0xc0, 0xb7, 0xea, 0xc1, 0x9b, 0x90, 0xf7, 0x24, 0x52, 0xc0, 0xea,
    0xc8, 0x68, 0x9d, 0xb1, 0x86, 0xdd, 0xf1, 0x4c, 0xaf, 0x3f, 0xc5, 0x5c, 0x53,
];

/// Build an envelope ourselves (OAEP-SHA1 wrap, canonical layout,
/// PKCS1-SHA256 signature) and round-trip it through our own provider.
///
/// Run with `--nocapture` to emit the envelope hex; feeding it to
/// `fixtures/CekHarness.java` (recipe in its header) proves Microsoft's
/// binary decrypts it and accepts our signature (done for the PR; OAEP is
/// randomized so the bytes differ per run, which is why this isn't a fixed
/// fixture).
#[tokio::test]
async fn builds_envelope_other_clients_accept() {
    use rsa::{Oaep, Pkcs1v15Sign, RsaPrivateKey, pkcs8::DecodePrivateKey};
    use sha1::Sha1;
    use sha2::{Digest, Sha256};

    let key = RsaPrivateKey::from_pkcs8_pem(TEST_CMK_PEM).expect("fixture key parses");
    let cek = expected_cek();

    let mut rng = rand::thread_rng();
    let ciphertext = key
        .to_public_key()
        .encrypt(&mut rng, Oaep::new::<Sha1>(), &cek)
        .expect("RSA-OAEP wrap");

    let mut envelope = mssql_auth::cek_envelope::build_signed_portion(KEY_PATH, &ciphertext);
    let digest: [u8; 32] = Sha256::digest(&envelope).into();
    let signature = key
        .sign(Pkcs1v15Sign::new::<Sha256>(), &digest)
        .expect("CMK signs");
    envelope.extend_from_slice(&signature);

    let hex: String = envelope.iter().map(|b| format!("{b:02X}")).collect();
    println!("OUR_ENVELOPE:{hex}");

    let mut store = InMemoryKeyStore::new();
    store
        .add_key(KEY_PATH, TEST_CMK_PEM)
        .expect("fixture key parses");
    let decrypted = store
        .decrypt_cek(KEY_PATH, "RSA_OAEP", &envelope)
        .await
        .expect("our own envelope round-trips");
    assert_eq!(decrypted, cek);
}

#[tokio::test]
async fn decrypts_microsoft_provisioned_cek() {
    let mut store = InMemoryKeyStore::new();
    store
        .add_key(KEY_PATH, TEST_CMK_PEM)
        .expect("fixture key parses");

    let cek = store
        .decrypt_cek(KEY_PATH, "RSA_OAEP", &MS_JDBC_ENVELOPE)
        .await
        .expect("Microsoft-provisioned CEK envelope must parse, verify, and decrypt");
    assert_eq!(cek, expected_cek());
}
