#!/bin/bash
# SPDX-License-Identifier: GPL-3.0+
# Copyright (C) 2022 Hannes Reinecke, SUSE Labs
#
# Test dhchap key types for authenticated connections

. tests/nvme/rc

DESCRIPTION="Test dhchap key types for authenticated connections"
QUICK=1

requires() {
	_nvme_requires
	_have_loop
	_have_kernel_option NVME_AUTH
	_have_kernel_option NVME_TARGET_AUTH
	_require_kernel_nvme_fabrics_feature dhchap_ctrl_secret
	_require_nvme_trtype_is_fabrics
	_require_nvme_cli_auth
}

set_conditions() {
	_set_nvme_trtype "$@"
}

test() {
	echo "Running ${TEST_NAME}"

	_setup_nvmet

	local hmac
	local key_len
	local hostkey
	local ctrldev

	_nvmet_target_setup --blkdev file

	for hmac in 0 1 2 3; do
		echo "Testing hmac ${hmac}"
		hostkey="$(nvme gen-dhchap-key --hmac=${hmac} -n "${def_subsysnqn}" 2> /dev/null)"
		if [ -z "$hostkey" ] ; then
			echo "couldn't generate host key for hmac ${hmac}"
			return 1
		fi
		_set_nvmet_hostkey "${def_hostnqn}" "${hostkey}"

		_nvme_connect_subsys --dhchap-secret "${hostkey}"

		_nvme_disconnect_subsys
	done

	for key_len in 32 48 64; do
		echo "Testing key length ${key_len}"
		hostkey="$(nvme gen-dhchap-key --key-length=${key_len} -n "${def_subsysnqn}" 2> /dev/null)"
		if [ -z "$hostkey" ] ; then
			echo "couldn't generate host key for length ${key_len}"
			return 1
		fi
		_set_nvmet_hostkey "${def_hostnqn}" "${hostkey}"

		_nvme_connect_subsys --dhchap-secret "${hostkey}"

		_nvme_disconnect_subsys
	done

	_nvmet_target_cleanup

	echo "Test complete"
}
