<commit_before>/*
 * OpenRemote, the Home of the Digital Home.
 * Copyright 2008-2014, OpenRemote Inc.
 *
 * See the contributors.txt file in the distribution for a
 * full listing of individual contributors.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.openremote.security;

import org.openremote.base.exception.IncorrectImplementationException;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Unit tests for {@link KeySigner}.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class KeySignerTest
{
  // Class Members --------------------------------------------------------------------------------

  /**
   * Public helper method for all tests to generate 2048 bit RSA key pair using default
   * security providers.
   */
  public static KeyPair generateRSAKeyPair() throws Exception
  {
    return generateRSAKeyPair(2048);
  }

  /**
   * Public helper method for all tests to generate RSA key pair using default security
   * providers.
   */
  public static KeyPair generateRSAKeyPair(int bitlen) throws Exception
  {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    keyGen.initialize(bitlen);

    return keyGen.generateKeyPair();
  }



  // Tests ----------------------------------------------------------------------------------------

  /**
   * Basic test for setting the certificate issuer common name in configuration.
   */
  @Test public void testConfigurationIssuerName() throws Exception
  {
    KeySigner.Configuration config = KeySigner.Configuration.createDefault(
        KeySignerTest.generateRSAKeyPair(), "foo"
    );

    Assert.assertTrue(config.getIssuer().toX500Name().contains("CN=foo"));
  }

  /**
   * Basic test for null guard for issuer common name in configuration constructor.
   */
  @Test public void testNullConfigurationIssuerName() throws Exception
  {
    try
    {
      KeySigner.Configuration.createDefault(KeySignerTest.generateRSAKeyPair(), null);

      Assert.fail("should not get here...");
    }

    catch (IncorrectImplementationException e)
    {
      // expected...
    }
  }

  /**
   * Basic test to guard against empty issuer common names in configuration constructor.
   */
  @Test public void testEmptyConfigurationIssuerName()
  {
    try
    {
      new KeySigner.Configuration("");

      Assert.fail("should not get here...");
    }

    catch (IllegalArgumentException e)
    {
      // expected...
    }
  }

  /**
   * Tests string trimming on provided issuer name.
   */
  @Test public void testConfigurationIssuerNameTrimming()
  {
    long time = System.currentTimeMillis();

    KeySigner.Configuration config = new KeySigner.Configuration("  foo  ");

    Assert.assertTrue(config.getIssuer().getX500Name().contains("CN=foo"));


    // Check default signature algorithm...

    Assert.assertTrue(
        config.getSignatureAlgorithm()
            .equals(
                KeySigner.Configuration.DEFAULT_SIGNATURE_ALGORITHM)
    );


    // Check default validity period...

    Assert.assertTrue(
        config.getValidityPeriod().getNotBeforeDate()
            .before(
        config.getValidityPeriod().getNotAfterDate())
    );

    Assert.assertTrue(
        config.getValidityPeriod().getNotBeforeDate()
            .after(
        new Date(time - 5000))
    );

    Assert.assertTrue(
        config.getValidityPeriod().getNotAfterDate()
            .before(
        new Date(time + TimeUnit.MILLISECONDS.convert(
            KeySigner.Validity.DEFAULT_VALID_DAYS, TimeUnit.DAYS) + 5000)
        )
    );
  }


  /**
   * Tests string trimming on provided issuer name and validity of 3 days.
   */
  @Test public void testConfiguration2IssuerNameTrimming()
  {
    long time = System.currentTimeMillis();

    KeySigner.Configuration config = new KeySigner.Configuration(
        new KeySigner.Validity(3),
        "  foo  "
    );

    Assert.assertTrue(config.getIssuer().getX500Name().contains("CN=foo"));<commit_msg>Update test API: configuration create methods, toX500Name() method, exception types<commit_after>/*
 * OpenRemote, the Home of the Digital Home.
 * Copyright 2008-2014, OpenRemote Inc.
 *
 * See the contributors.txt file in the distribution for a
 * full listing of individual contributors.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.openremote.security;

import org.openremote.base.exception.IncorrectImplementationException;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Unit tests for {@link KeySigner}.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class KeySignerTest
{
  // Class Members --------------------------------------------------------------------------------

  /**
   * Public helper method for all tests to generate 2048 bit RSA key pair using default
   * security providers.
   */
  public static KeyPair generateRSAKeyPair() throws Exception
  {
    return generateRSAKeyPair(2048);
  }

  /**
   * Public helper method for all tests to generate RSA key pair using default security
   * providers.
   */
  public static KeyPair generateRSAKeyPair(int bitlen) throws Exception
  {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    keyGen.initialize(bitlen);

    return keyGen.generateKeyPair();
  }



  // Tests ----------------------------------------------------------------------------------------

  /**
   * Basic test for setting the certificate issuer common name in configuration.
   */
  @Test public void testConfigurationIssuerName() throws Exception
  {
    KeySigner.Configuration config = KeySigner.Configuration.createDefault(
        KeySignerTest.generateRSAKeyPair(), "foo"
    );

    Assert.assertTrue(config.getIssuer().toX500Name().contains("CN=foo"));
  }

  /**
   * Basic test for null guard for issuer common name in configuration constructor.
   */
  @Test public void testNullConfigurationIssuerName() throws Exception
  {
    try
    {
      KeySigner.Configuration.createDefault(KeySignerTest.generateRSAKeyPair(), null);

      Assert.fail("should not get here...");
    }

    catch (IncorrectImplementationException e)
    {
      // expected...
    }
  }

  /**
   * Basic test to guard against empty issuer common names in configuration constructor.
   */
  @Test public void testEmptyConfigurationIssuerName() throws Exception
  {
    try
    {
      KeySigner.Configuration.createDefault(KeySignerTest.generateRSAKeyPair(), "");

      Assert.fail("should not get here...");
    }

    catch (IncorrectImplementationException e)
    {
      // expected...
    }
  }

  /**
   * Tests string trimming on provided issuer name.
   */
  @Test public void testConfigurationIssuerNameTrimming() throws Exception
  {
    long time = System.currentTimeMillis();

    KeySigner.Configuration config = KeySigner.Configuration.createDefault(
        KeySignerTest.generateRSAKeyPair(), "  foo  "
    );

    Assert.assertTrue(config.getIssuer().toX500Name().contains("CN=foo"));


    // Check default signature algorithm...

    Assert.assertTrue(
        config.getSignatureAlgorithm()
            .equals(
                KeySigner.Configuration.DEFAULT_SIGNATURE_ALGORITHM)
    );


    // Check default validity period...

    Assert.assertTrue(
        config.getValidityPeriod().getNotBeforeDate()
            .before(
        config.getValidityPeriod().getNotAfterDate())
    );

    Assert.assertTrue(
        config.getValidityPeriod().getNotBeforeDate()
            .after(
        new Date(time - 5000))
    );

    Assert.assertTrue(
        config.getValidityPeriod().getNotAfterDate()
            .before(
        new Date(time + TimeUnit.MILLISECONDS.convert(
            KeySigner.Validity.DEFAULT_VALID_DAYS, TimeUnit.DAYS) + 5000)
        )
    );
  }


  /**
   * Tests string trimming on provided issuer name and validity of 3 days.
   */
  @Test public void testConfiguration2IssuerNameTrimming() throws Exception
  {
    long time = System.currentTimeMillis();

    KeySigner.Configuration config = KeySigner.Configuration.createSelfSigned(
        KeySignerTest.generateRSAKeyPair(),
        KeySigner.SignatureAlgorithm.SHA512_WITH_RSA,
        new KeySigner.Validity(3),
        "  foo  "
    );

    Assert.assertTrue(config.getIssuer().toX500Name().contains("CN=foo"));
{'fraction_non_alphanumeric': 0.12688544639217286, 'fraction_numerical': 0.008153281695882593, 'mean_word_length': 2.71845395983327, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '528231', 'n_tokens_mistral': 2691, 'n_tokens_neox': 2559, 'n_words': 750}