/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
/* jshint node:true */
'use strict';

var keyStore = require('../lib/index');
var certificate = require('scytl-certificate');
var codec = require('scytl-codec');

describe('The key store module that should be able to ...', function() {
  var PASSWORD = 'PM6XtkOTbefJmhHGFgbz';
  var PKCS12_DER_B64 =
      '[encoded data, 8884 characters]';
  var ROOT_PUBLIC_KEY_PEM =
      '-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAngCJ2RYh3XOvghmAi2MT26/fx4Hx8gYkYS2zaf9c2H8Qns1hnIHO8pIlHze/stUmNzim6nlytbJLQHmVDu64Pf9dn1ClAW2caKqUo4ofjnOzDd6RocQByjTsvZ1nOcG5BMYtOWGua+QIVFrxvxZgL6T3ShQ+9J3/1LiQDUmWj0kMoct6vRJuNkJxVFegtIEqYZYTTFI1+Y25k040NFu0e9IDwDXQA63EqKL3DjrgxdjOY+KXu4zU6DUcL4VcKaTMs1+pDfU6bSOtrecuasKkEmNE9fuy9WejFqNGqlrNVCeYmOOnNXvI0vCdH1bw4/CpqddxvGZOStczF8vGJVcMVQIDAQAB-----END PUBLIC KEY-----';
  var ROOT_PRIVATE_KEY_PEM =
      '-----BEGIN RSA PRIVATE KEY-----MIIEogIBAAKCAQEAngCJ2RYh3XOvghmAi2MT26/fx4Hx8gYkYS2zaf9c2H8Qns1hnIHO8pIlHze/stUmNzim6nlytbJLQHmVDu64Pf9dn1ClAW2caKqUo4ofjnOzDd6RocQByjTsvZ1nOcG5BMYtOWGua+QIVFrxvxZgL6T3ShQ+9J3/1LiQDUmWj0kMoct6vRJuNkJxVFegtIEqYZYTTFI1+Y25k040NFu0e9IDwDXQA63EqKL3DjrgxdjOY+KXu4zU6DUcL4VcKaTMs1+pDfU6bSOtrecuasKkEmNE9fuy9WejFqNGqlrNVCeYmOOnNXvI0vCdH1bw4/C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AGyXTcOvhr+5ayXkQ36VAr2YcAUs2SeN0HwmYBP2ErCgd/KXri7RwWXqEQtvpvAOGJq/tXyc7P5BnBhlqQtUm9WX7kqTy/dIS+pJP0UMm02N9U+b02G0auPmBKM35LXO4YGhZep1Vig+MLycR8OSe0cd4gzk52u3Th9I3e0bV9Fw=-----END RSA PRIVATE KEY-----';
  var LEAF_PUBLIC_KEY_PEM =
      '-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAglypZU45bnf2opnRI+Y51VqouBpvDT33xIB/OtbwKzwVpi+JrjBFtfk33tE9t/dSRs79CK94HRhCWcOiLa2qWPrjeZ9SBiEyScrhIvRZVBF41zBgwQNuRvJCsKmAqlZaFNJDZxEP4repmlBn1CfVFmfrXmOKqwP5F7l9ZtucveRzsfmF1yVPFkW8TMuB3YqMiyymyqHlS8ujCsu5I8tpgPbwuxdMOY94fNhSXrYkY8IuX1g1zdq/Z1jluOaR/UqK4UpnbuJaH/F0VgDNiWh6cTD0DFGEk0b70i5wU4Q3L/S6XZQRvSuADoCbhwBKuFL5pW5n865oLVb5S3wuVdWaGwIDAQAB-----END PUBLIC KEY-----';
  var LEAF_PRIVATE_KEY_PEM =
      '-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEAglypZU45bnf2opnRI+Y51VqouBpvDT33xIB/OtbwKzwVpi+JrjBFtfk33tE9t/dSRs79CK94HRhCWcOiLa2qWPrjeZ9SBiEyScrhIvRZVBF41zBgwQNuRvJCsKmAqlZaFNJDZxEP4repmlBn1CfVFmfrXmOKqwP5F7l9ZtucveRzsfmF1yVPFkW8TMuB3YqMiyymyqHlS8ujCsu5I8tpgPbwuxdMOY94fNhSXrYkY8IuX1g1zdq/Z1jluOaR/UqK4UpnbuJaH/F0VgDNiWh6cTD0DFGEk0b70i5wU4Q3L/S6XZQRvSuADoCbhwBKuFL5pW5n865oLVb5S3wuVdWaGwIDAQABAoIBAC/tn34Wf3kE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KiFCxCUZ948+9NuG+DnpXDWzw//r8mPBRRGGsqFws5Aipp7yjQ3kRDCCzGelPCVhHyfmKqA+8ewXPulKS3/wIyHIvaXmsuAtTfurHtpRyzjKmCBK1Y6WQ3trIXvo7s-----END RSA PRIVATE KEY-----';
  var ROOT_COMMON_NAME = 'Root CN';
  var ROOT_CERTIFICATE_PEM =
      '-----BEGIN CERTIFICATE-----MIIEKjCCAxKgAwIBAgIQQtWFdPN4NAvUIWyyJyUlbTANBgkqhkiG9w0BAQsFADBUMRAwDgYDVQQDDAdSb290IENOMRYwFAYDVQQLDA1Sb290IE9yZyBVbml0MREwDwYDVQQKDAhSb290IE9yZzEVMBMGA1UEBhMMUm9vdCBDb3VudHJ5MB4XDTE0MDYxODEwMjMyOFoXDTE1MDYxODEwMjMyOFowVDEQMA4GA1UEAwwHUm9vdCBDTjEWMBQGA1UECwwNUm9vdCBPcmcgVW5pdDERMA8GA1UECgwIUm9vdCBPcmcxFTATBgNVBAYTDFJvb3QgQ291bnRyeTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ4AidkWId1zr4IZgItjE9uv38eB8fIGJGEts2n/XNh/EJ7NYZyBzvKSJR83v7LVJjc4pup5crWyS0B5lQ7uuD3/XZ9QpQFtnGiqlKOKH45zsw3ekaHEAco07L2dZznBuQTGLTlhrmvkCFRa8b8WYC+k90oUPvSd/9S4kA1Jlo9JDKHLer0SbjZCcVRXoLSBKmGWE0xSNfmNuZNONDRbtHvSA8A10AOtxKii9w464MXYzmPil7uM1Og1HC+FXCmkzLNfqQ31Om0jra3nLmrCpBJjRPX7svVnoxajRqpazVQnmJjjpzV7yNLwnR9W8OPwqanXcbxmTkrXMxfLxiVXDFUCAwEAAaOB9zCB9DAPBgNVHRMBAf8EBTADAQH/MDUGCCsGAQUFBwEBAQH/BCYwJDAiBggrBgEFBQcwAYYWaHR0cDovL29jc3AudGhhd3RlLmNvbTA0BgNVHR8BAf8EKjAoMCagJKAihiBodHRwOi8vY3JsLnZlcmlzaWduLmNvbS9wY2EzLmNybDArBgNVHREBAf8EITAfpB0wGzEZMBcGA1UEAwwQUHJpdmF0ZUxhYmVsMy0xNTAOBgNVHQ8BAf8EBAMCAQYwNwYDVR0lAQH/BC0wKwYIKwYBBQUHAwEGCCsGAQUFBwMCBgpghkgBhvhFAQgBBglghkgBhvhCBAEwDQYJKoZIhvcNAQELBQADggEBADmtmjApZAXIkGLaZCdkRnhel53BtEdQnG990Oo/tBBboqy2ipum9ByTj3hNWJB3zuPN77rkrek9rbookNcCgVWhHtTk1lUpUK6ZohDsZh8k0MqIhkz+X+HiWGRsEOptjsCaknyWcWb4aXAevMAQMPm/ktkpQ8AOxAq+gtieewWQZP3kGPhBBCfn8TGjdrn9+ymf8EIbAUFXQ8m+oWeNlrdWhqzRXwQbj4EDds1kZdTo0nCYUdH+XEBF9nMyhAxSQWzCKQQTRFWv1dr3dKapzfgrdH8wEgvptiBYCY62O5+3DxiNK/VWquHz6S5GqIwkmSPDPMUU/qK3SNG3xIL1U1k=-----END CERTIFICATE-----';
  var LEAF_COMMON_NAME = 'Subject CN';
  var LEAF_CERTIFICATE_PEM =
      '-----BEGIN CERTIFICATE-----MIIEMzCCAxugAwIBAgIQRbaPaToIM+VS/d6etgYZ4jANBgkqhkiG9w0BAQsFADBUMRAwDgYDVQQDDAdSb290IENOMRYwFAYDVQQLDA1Sb290IE9yZyBVbml0MREwDwYDVQQKDAhSb290IE9yZzEVMBMGA1UEBhMMUm9vdCBDb3VudHJ5MB4XDTE0MDYxODEwMjMyOFoXDTE1MDYxODEwMjMyOFowYDETMBEGA1UEAwwKU3ViamVjdCBDTjEZMBcGA1UECwwQU3ViamVjdCBPcmcgVW5pdDEUMBIGA1UECgwLU3ViamVjdCBPcmcxGDAWBgNVBAYTD1N1YmplY3QgQ291bnRyeTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIJcqWVOOW539qKZ0SPmOdVaqLgabw0998SAfzrW8Cs8FaYvia4wRb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S = 'user_rsa_private_key';

  var keyStoreService_;
  var certificateService_;
  var pkcs12KeyStore_;

  beforeAll(function() {
    keyStoreService_ = keyStore.newService();
    certificateService_ = certificate.newService();
    pkcs12KeyStore_ = keyStoreService_.newPkcs12KeyStore(
        codec.base64Decode(PKCS12_DER_B64), PASSWORD);
  });

  describe('create a key store service that should be able to ..', function() {
    describe('load a PKCS12 key store that should be able to', function() {
      it('retrieve a private key, given its storage alias name and password',
         function() {
           var rootPrivateKeyPem = removeNewLineChars(
               pkcs12KeyStore_.getPrivateKey(ROOT_PRIVATE_KEY_ALIAS, PASSWORD));
           expect(rootPrivateKeyPem).toBe(ROOT_PRIVATE_KEY_PEM);

           var leafPrivateKeyPem = removeNewLineChars(
               pkcs12KeyStore_.getPrivateKey(LEAF_PRIVATE_KEY_ALIAS, PASSWORD));
           expect(leafPrivateKeyPem).toBe(LEAF_PRIVATE_KEY_PEM);
         });

      it('retrieve a certificate, given the storage alias name of its associated private key entry',
         function() {
           var rootCertificatePem = removeNewLineChars(
               pkcs12KeyStore_.getCertificate(ROOT_PRIVATE_KEY_ALIAS));
           expect(rootCertificatePem).toBe(ROOT_CERTIFICATE_PEM);
           var rootCertificate =
               certificateService_.newX509Certificate(rootCertificatePem);
           var rootPublicKeyPem = removeNewLineChars(rootCertificate.publicKey);
           expect(rootPublicKeyPem).toBe(ROOT_PUBLIC_KEY_PEM);

           var leafCertificatePem = removeNewLineChars(
               pkcs12KeyStore_.getCertificate(LEAF_PRIVATE_KEY_ALIAS));
           expect(leafCertificatePem).toBe(LEAF_CERTIFICATE_PEM);
           var leafCertificate =
               certificateService_.newX509Certificate(leafCertificatePem);
           var leafPublicKeyPem = removeNewLineChars(leafCertificate.publicKey);
           expect(leafPublicKeyPem).toBe(LEAF_PUBLIC_KEY_PEM);

           expect(rootCertificate.verify(rootCertificatePem)).toBeTruthy();
           expect(rootCertificate.verify(leafCertificatePem)).toBeTruthy();
         });

      it('retrieve a certificate, given its subject common name', function() {
        var rootCertificatePem = removeNewLineChars(
            pkcs12KeyStore_.getCertificateBySubject(ROOT_COMMON_NAME));
        expect(rootCertificatePem).toBe(ROOT_CERTIFICATE_PEM);
        var rootCertificate =
            certificateService_.newX509Certificate(rootCertificatePem);
        var rootPublicKeyPem = removeNewLineChars(rootCertificate.publicKey);
        expect(rootPublicKeyPem).toBe(ROOT_PUBLIC_KEY_PEM);

        var leafCertificatePem = removeNewLineChars(
            pkcs12KeyStore_.getCertificateBySubject(LEAF_COMMON_NAME));
        expect(leafCertificatePem).toBe(LEAF_CERTIFICATE_PEM);
        var leafCertificate =
            certificateService_.newX509Certificate(leafCertificatePem);
        var leafPublicKeyPem = removeNewLineChars(leafCertificate.publicKey);
        expect(leafPublicKeyPem).toBe(LEAF_PUBLIC_KEY_PEM);

        expect(rootCertificate.verify(rootCertificatePem)).toBeTruthy();
        expect(rootCertificate.verify(leafCertificatePem)).toBeTruthy();
      });

      it('retrieve a certificate chain, given the storage alias name of its associated private key entry',
         function() {
           var rootCertificateChain =
               pkcs12KeyStore_.getCertificateChain(ROOT_PRIVATE_KEY_ALIAS);
           expect(rootCertificateChain.length).toBe(1);
           var rootCertificatePem = removeNewLineChars(rootCertificateChain[0]);
           expect(rootCertificatePem).toBe(ROOT_CERTIFICATE_PEM);

           var leafCertificateChain =
               pkcs12KeyStore_.getCertificateChain(LEAF_PRIVATE_KEY_ALIAS);
           expect(leafCertificateChain.length).toBe(2);
           var leafCertificatePem = removeNewLineChars(leafCertificateChain[0]);
           expect(leafCertificatePem).toBe(LEAF_CERTIFICATE_PEM);
           rootCertificatePem = removeNewLineChars(leafCertificateChain[1]);
           expect(rootCertificatePem).toBe(ROOT_CERTIFICATE_PEM);
         });
    });

    it('load a PKCS12 key store, in Base64 encoded format', function() {
      var pkcs12KeyStore =
          keyStoreService_.newPkcs12KeyStore(PKCS12_DER_B64, PASSWORD);
      expect(pkcs12KeyStore).toBeDefined();

      // Check private keys.
      var rootPrivateKeyPem = removeNewLineChars(
          pkcs12KeyStore.getPrivateKey(ROOT_PRIVATE_KEY_ALIAS, PASSWORD));
      expect(rootPrivateKeyPem).toBe(ROOT_PRIVATE_KEY_PEM);
      var leafPrivateKeyPem = removeNewLineChars(
          pkcs12KeyStore.getPrivateKey(LEAF_PRIVATE_KEY_ALIAS, PASSWORD));
      expect(leafPrivateKeyPem).toBe(LEAF_PRIVATE_KEY_PEM);

      // Check certificates.
      var rootCertificatePem = removeNewLineChars(
          pkcs12KeyStore.getCertificate(ROOT_PRIVATE_KEY_ALIAS));
      expect(rootCertificatePem).toBe(ROOT_CERTIFICATE_PEM);
      var leafCertificatePem = removeNewLineChars(
          pkcs12KeyStore.getCertificate(LEAF_PRIVATE_KEY_ALIAS));
      expect(leafCertificatePem).toBe(LEAF_CERTIFICATE_PEM);

      // Check certificate chains.
      var rootCertificateChain =
          pkcs12KeyStore_.getCertificateChain(ROOT_PRIVATE_KEY_ALIAS);
      rootCertificatePem = removeNewLineChars(rootCertificateChain[0]);
      expect(rootCertificatePem).toBe(ROOT_CERTIFICATE_PEM);
      var leafCertificateChain =
          pkcs12KeyStore_.getCertificateChain(LEAF_PRIVATE_KEY_ALIAS);
      leafCertificatePem = removeNewLineChars(leafCertificateChain[0]);
      expect(leafCertificatePem).toBe(LEAF_CERTIFICATE_PEM);
      rootCertificatePem = removeNewLineChars(leafCertificateChain[1]);
      expect(rootCertificatePem).toBe(ROOT_CERTIFICATE_PEM);
    });
  });

  function removeNewLineChars(str) {
    return str.replace(/(\r\n|\n|\r)/gm, '');
  }
});
