#!/usr/bin/env expect
############################################################################
# Purpose: Test of Slurm functionality
#          Verify that auth/munge credential is properly validated.
############################################################################
# Copyright (C) 2012 SchedMD LLC.
# Written by Morris Jette <jette@schedmd.com>
#
# This file is part of Slurm, a resource management program.
# For details, see <https://slurm.schedmd.com/>.
# Please also read the included file: DISCLAIMER.
#
# Slurm is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Slurm 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 General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with Slurm; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA.
############################################################################
source ./globals

#
# Try to get allocation with bad credential
#
proc alloc_job { } {
	global env salloc bin_bash number max_job_delay
	set env(SLURM_MUNGE_AUTH_FAIL_TEST) 1
	set job_id 0
	set timeout $max_job_delay
	set salloc_pid [spawn $salloc -N1 $bin_bash]
	expect {
		-re "Granted job allocation ($number)" {
			set job_id $expect_out(1,string)
			send "exit\r"
			exp_continue
		}
		-re "error" {
			log_debug "Error is expected, no worries"
			exp_continue
		}
		timeout {
			slow_kill [expr 0 - $salloc_pid]
			cancel_job $job_id
			fail "salloc not responding"
		}
		eof {
			wait
		}
	}
	return $job_id
}

#
# Check if we have auth/munge configured
#
log_user 0
set auth_munge 0
spawn $scontrol show config
expect {
	-re "AuthType *= auth/munge" {
		set auth_munge 1
		exp_continue
	}
	timeout {
		fail "scontrol not responding"
	}
	eof {
		wait
	}
}
log_user 1
if {$auth_munge == 0} {
	skip "Not running auth/munge, test is not applicable"
}

set job_id [alloc_job]
if {$job_id != 0} {
	log_warn "Allocation granted with bad Munge credential. This happens rarely, when the Slurm test modifies a byte that Munge does not use. Try one more time.."
	sleep 1
	set job_id [alloc_job]
	if {$job_id != 0} {
		fail "Allocation granted with bad Munge credential. This happens rarely, when the Slurm test modifies a byte that Munge does not use"
	}
}
