/* 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/. */
"use strict";

// Tests handling of Encrypted Client Hello. These ECHConfigs
// can be regenerated by running EncryptedClientHelloServer
// and dumping the output of SSL_EncodeEchConfig. They do not
// expire. An update here is only needed if the host or ECH
// ciphersuite configuration changes, or if the keypair in
// EncryptedClientHelloServer.cpp is modified.

// Public name: ech-public.example.com
const ECH_CONFIG_FIXED =
  "AEn+DQBFTQAgACCKB1Y5SfrGIyk27W82xPpzWTDs3q72c04xSurDWlb9CgAEAAEAA2QWZWNoLXB1YmxpYy5leGFtcGxlLmNvbQAA";

// Public name: ech-public.example.com, Unsupported AEAD to prompt retry_configs from a trusted host.
const ECH_CONFIG_TRUSTED_RETRY =
  "AEn+DQBFTQAgACCKB1Y5SfrGIyk27W82xPpzWTDs3q72c04xSurDWlb9CgAEAAMAA2QWZWNoLXB1YmxpYy5leGFtcGxlLmNvbQAA";

// Public name: selfsigned.example.com. Unsupported AEAD to prompt retry_configs from an untrusted host.
const ECH_CONFIG_UNTRUSTED_RETRY =
  "AEn+DQBFTQAgACCKB1Y5SfrGIyk27W82xPpzWTDs3q72c04xSurDWlb9CgAEAAMAA2QWc2VsZnNpZ25lZC5leGFtcGxlLmNvbQAA";

function shouldBeAcceptedEch(aTransportSecurityInfo) {
  Assert.ok(
    aTransportSecurityInfo.isAcceptedEch,
    "This host should have accepted ECH"
  );
  Assert.ok(
    !aTransportSecurityInfo.usedPrivateDNS,
    "This connection does not use DoH"
  );
}

function shouldBeRejectedEch(aTransportSecurityInfo) {
  Assert.ok(
    !aTransportSecurityInfo.isAcceptedEch,
    "This host should have rejected ECH"
  );
  Assert.ok(
    !aTransportSecurityInfo.usedPrivateDNS,
    "This connection does not use DoH"
  );
}

do_get_profile();

add_tls_server_setup(
  "EncryptedClientHelloServer",
  "test_encrypted_client_hello"
);

// Connect directly without ECH first
add_connection_test(
  "ech-public.example.com",
  PRErrorCodeSuccess,
  null,
  shouldBeRejectedEch
);

// Connect with ECH
add_connection_test(
  "ech-private.example.com",
  PRErrorCodeSuccess,
  null,
  shouldBeAcceptedEch,
  null,
  null,
  ECH_CONFIG_FIXED
);

// Trigger retry_configs by setting an ECHConfig with a different.
// AEAD than the server supports.
add_connection_test(
  "ech-private.example.com",
  SSL_ERROR_ECH_RETRY_WITH_ECH,
  null,
  null,
  null,
  null,
  ECH_CONFIG_TRUSTED_RETRY
);

// Trigger retry_configs, but from a host that is untrusted
// (due to a self-signed certificate for the public name).
// Retry_configs must not be used or reported as available.
add_connection_test(
  "ech-private.example.com",
  MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT,
  null,
  null,
  null,
  null,
  ECH_CONFIG_UNTRUSTED_RETRY
);

// A client-only (retry_without_ech) test is located in
// test_encrypted_client_hello_client_only.js We can't easily restart
// a different server (one without ECHConfigs) here, so put that
// test in a different file that launches a non-ECH server.
