Blame SOURCES/bz2102024-fence_ibm_vpc-add-token-cache-support.patch

776db4
From bccac64a5135815ada30d385ab573409f1176905 Mon Sep 17 00:00:00 2001
776db4
From: Oyvind Albrigtsen <oalbrigt@redhat.com>
776db4
Date: Thu, 7 Jul 2022 14:18:21 +0200
776db4
Subject: [PATCH 1/3] build: make xml-check: ignore detected paths in *_file
776db4
 parameters not matching saved metadata
776db4
776db4
---
776db4
 make/agentpycheck.mk                          | 2 +-
776db4
 83 files changed, 1 insertion(+), 108 deletions(-)
776db4
776db4
diff --git a/make/agentpycheck.mk b/make/agentpycheck.mk
776db4
index f686c4c89..4044dbad3 100644
776db4
--- a/make/agentpycheck.mk
776db4
+++ b/make/agentpycheck.mk
776db4
@@ -1,5 +1,5 @@
776db4
 DATADIR:=$(abs_top_srcdir)/tests/data/metadata
776db4
-AWK_VAL='BEGIN {store=-1} /name=".*_path"/ {store=2} {if (store!=0) {print}; store--}'
776db4
+AWK_VAL='BEGIN {store=-1} /name=".*_path"/ || /name=".*_file"/ {store=2} {if (store!=0) {print}; store--}'
776db4
 
776db4
 TEST_TARGET=$(filter-out $(TEST_TARGET_SKIP),$(TARGET))
776db4
 
776db4
From 1b7f3cc431ca53962506e6d96e7a4938c4388416 Mon Sep 17 00:00:00 2001
776db4
From: Oyvind Albrigtsen <oalbrigt@redhat.com>
776db4
Date: Fri, 1 Jul 2022 13:29:16 +0200
776db4
Subject: [PATCH 2/3] build: add FENCETMPDIR for state files
776db4
776db4
---
776db4
 Makefile.am                  |  3 ++-
776db4
 configure.ac                 | 30 ++++++++++++++++++++++++++++++
776db4
 m4/PKG_CHECK_VAR.m4          | 24 ++++++++++++++++++++++++
776db4
 make/fencebuild.mk           |  1 +
776db4
 systemd/Makefile.am          | 24 ++++++++++++++++++++++++
776db4
 systemd/fence-agents.conf.in |  1 +
776db4
 7 files changed, 97 insertions(+), 2 deletions(-)
776db4
 create mode 100644 m4/PKG_CHECK_VAR.m4
776db4
 create mode 100644 systemd/Makefile.am
776db4
 create mode 100644 systemd/fence-agents.conf.in
776db4
776db4
diff --git a/Makefile.am b/Makefile.am
776db4
index c1091b93a..1d115e5aa 100644
776db4
--- a/Makefile.am
776db4
+++ b/Makefile.am
776db4
@@ -23,7 +23,7 @@ TARFILES		= $(PACKAGE_NAME)-$(VERSION).tar.bz2 \
776db4
 
776db4
 ACLOCAL_AMFLAGS		= -I m4
776db4
 
776db4
-SUBDIRS			= lib agents doc
776db4
+SUBDIRS			= lib agents doc systemd
776db4
 
776db4
 .PHONY: $(SUBDIRS)
776db4
 
776db4
@@ -34,6 +34,7 @@ doc: agents
776db4
 install-exec-local:
776db4
 			$(INSTALL) -d $(DESTDIR)/$(LOGDIR)
776db4
 			$(INSTALL) -d $(DESTDIR)/$(CLUSTERVARRUN)
776db4
+			$(INSTALL) -d -m 1755 $(DESTDIR)$(FENCETMPDIR)
776db4
 
776db4
 uninstall-local:
776db4
 			rmdir $(DESTDIR)/$(LOGDIR) || :;
776db4
diff --git a/configure.ac b/configure.ac
776db4
index 1bad8e3b0..d7afb8dbe 100644
776db4
--- a/configure.ac
776db4
+++ b/configure.ac
776db4
@@ -135,10 +135,38 @@ AC_ARG_WITH([agents],
776db4
 	[ AGENTS_LIST="$withval" ],
776db4
 	[ AGENTS_LIST="all" ])
776db4
 
776db4
+FENCETMPDIR=${localstatedir}/run/fence-agents
776db4
+AC_ARG_WITH(fencetmpdir,
776db4
+    [  --with-fencetmpdir=DIR      directory for fence agents state files [${FENCETMPDIR}]],
776db4
+    [ FENCETMPDIR="$withval" ])
776db4
+
776db4
+# Expand $prefix
776db4
+eval FENCETMPDIR="`eval echo ${FENCETMPDIR}`"
776db4
+AC_DEFINE_UNQUOTED(FENCETMPDIR,"$FENCETMPDIR", Where Fence agents keep state files)
776db4
+AC_SUBST(FENCETMPDIR)
776db4
+
776db4
+
776db4
 if test "x$AGENTS_LIST" = x; then
776db4
 	AC_ERROR([No agents selected])
776db4
 fi
776db4
 
776db4
+# PKG_CHECK_MODULES will fail if systemd is not found by default, so make sure
776db4
+# we set the proper vars and deal with it
776db4
+PKG_CHECK_MODULES([systemd], [systemd], [HAS_SYSTEMD=yes], [HAS_SYSTEMD=no])
776db4
+if test "x$HAS_SYSTEMD" == "xyes"; then
776db4
+	PKG_CHECK_VAR([SYSTEMD_TMPFILES_DIR], [systemd], [tmpfilesdir])
776db4
+	if test "x$SYSTEMD_TMPFILES_DIR" == "x"; then
776db4
+		AC_MSG_ERROR([Unable to detect systemd tmpfiles directory automatically])
776db4
+	fi
776db4
+
776db4
+	# sanitize systed vars when using non standard prefix
776db4
+	if test "$prefix" != "/usr"; then
776db4
+		SYSTEMD_TMPFILES_DIR="$prefix/$SYSTEMD_TMPFILES_DIR"
776db4
+		AC_SUBST([SYSTEMD_TMPFILES_DIR])
776db4
+	fi
776db4
+fi
776db4
+AM_CONDITIONAL(HAVE_SYSTEMD, [test "x$HAS_SYSTEMD" == xyes ])
776db4
+
776db4
 FENCE_KDUMP=0
776db4
 if echo "$AGENTS_LIST" | grep -q -E "all|kdump"; then
776db4
 	case "$host_os" in
776db4
@@ -552,6 +580,8 @@ AM_EXTRA_RECURSIVE_TARGETS([xml-check xml-upload])
776db4
 AC_CONFIG_FILES([Makefile
776db4
 		 agents/Makefile
776db4
 		 lib/Makefile
776db4
+		 systemd/Makefile
776db4
+		 systemd/fence-agents.conf
776db4
 		 doc/Makefile])
776db4
 
776db4
 AC_OUTPUT
776db4
diff --git a/m4/PKG_CHECK_VAR.m4 b/m4/PKG_CHECK_VAR.m4
776db4
new file mode 100644
776db4
index 000000000..2221a69eb
776db4
--- /dev/null
776db4
+++ b/m4/PKG_CHECK_VAR.m4
776db4
@@ -0,0 +1,24 @@
776db4
+dnl PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
776db4
+dnl [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
776db4
+dnl -------------------------------------------
776db4
+dnl Since: 0.28
776db4
+dnl
776db4
+dnl Retrieves the value of the pkg-config variable for the given module.
776db4
+dnl
776db4
+dnl Origin (declared license: GPLv2+ with less restrictive exception):
776db4
+dnl https://cgit.freedesktop.org/pkg-config/tree/pkg.m4.in?h=pkg-config-0.29.1#n261
776db4
+dnl (AS_VAR_COPY replaced with backward-compatible equivalent and guard
776db4
+dnl to prefer system-wide variant by Jan Pokorny <jpokorny@redhat.com>)
776db4
+
776db4
+m4_ifndef([PKG_CHECK_VAR],[
776db4
+AC_DEFUN([PKG_CHECK_VAR],
776db4
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
776db4
+AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl
776db4
+
776db4
+_PKG_CONFIG([$1], [variable="][$3]["], [$2])
776db4
+dnl AS_VAR_COPY([$1], [pkg_cv_][$1])
776db4
+$1=AS_VAR_GET([pkg_cv_][$1])
776db4
+
776db4
+AS_VAR_IF([$1], [""], [$5], [$4])dnl
776db4
+])dnl PKG_CHECK_VAR
776db4
+])dnl m4_ifndef
776db4
diff --git a/make/fencebuild.mk b/make/fencebuild.mk
776db4
index 762db62c4..9a3c6d6dd 100644
776db4
--- a/make/fencebuild.mk
776db4
+++ b/make/fencebuild.mk
776db4
@@ -8,6 +8,7 @@ define gen_agent_from_py
776db4
 		-e 's#@''LOGDIR@#${LOGDIR}#g' \
776db4
 		-e 's#@''SBINDIR@#${sbindir}#g' \
776db4
 		-e 's#@''LIBEXECDIR@#${libexecdir}#g' \
776db4
+		-e 's#@''FENCETMPDIR@#${FENCETMPDIR}#g' \
776db4
 		-e 's#@''IPMITOOL_PATH@#${IPMITOOL_PATH}#g' \
776db4
 		-e 's#@''OPENSTACK_PATH@#${OPENSTACK_PATH}#g' \
776db4
 		-e 's#@''AMTTOOL_PATH@#${AMTTOOL_PATH}#g' \
776db4
diff --git a/systemd/Makefile.am b/systemd/Makefile.am
776db4
new file mode 100644
776db4
index 000000000..aa3a01679
776db4
--- /dev/null
776db4
+++ b/systemd/Makefile.am
776db4
@@ -0,0 +1,24 @@
776db4
+#
776db4
+# Copyright (C) 2017 Oyvind Albrigtsen
776db4
+#
776db4
+# This program is free software; you can redistribute it and/or
776db4
+# modify it under the terms of the GNU General Public License
776db4
+# as published by the Free Software Foundation; either version 2
776db4
+# of the License, or (at your option) any later version.
776db4
+# 
776db4
+# This program is distributed in the hope that it will be useful,
776db4
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
776db4
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
776db4
+# GNU General Public License for more details.
776db4
+# 
776db4
+# You should have received a copy of the GNU General Public License
776db4
+# along with this program; if not, write to the Free Software
776db4
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
776db4
+#
776db4
+
776db4
+MAINTAINERCLEANFILES    = Makefile.in
776db4
+
776db4
+if HAVE_SYSTEMD
776db4
+tmpfilesdir		= $(SYSTEMD_TMPFILES_DIR)
776db4
+tmpfiles_DATA		= fence-agents.conf
776db4
+endif
776db4
diff --git a/systemd/fence-agents.conf.in b/systemd/fence-agents.conf.in
776db4
new file mode 100644
776db4
index 000000000..4181287da
776db4
--- /dev/null
776db4
+++ b/systemd/fence-agents.conf.in
776db4
@@ -0,0 +1 @@
776db4
+d @FENCETMPDIR@ 1755 root root
776db4
776db4
From d5a12d9c30b66eb8720e037c4dce5fe0f3ad7dbb Mon Sep 17 00:00:00 2001
776db4
From: Oyvind Albrigtsen <oalbrigt@redhat.com>
776db4
Date: Thu, 30 Jun 2022 13:20:37 +0200
776db4
Subject: [PATCH 3/3] fence_ibm_vpc: add token cache support
776db4
776db4
---
776db4
 agents/ibm_vpc/fence_ibm_vpc.py         | 126 ++++++++++++++++++++----
776db4
 tests/data/metadata/fence_ibm_vpc.xml   |   4 +
776db4
 3 files changed, 110 insertions(+), 22 deletions(-)
776db4
776db4
diff --git a/agents/ibm_vpc/fence_ibm_vpc.py b/agents/ibm_vpc/fence_ibm_vpc.py
776db4
index 3da3ce056..847010584 100755
776db4
--- a/agents/ibm_vpc/fence_ibm_vpc.py
776db4
+++ b/agents/ibm_vpc/fence_ibm_vpc.py
776db4
@@ -4,9 +4,10 @@
776db4
 import pycurl, io, json
776db4
 import logging
776db4
 import atexit
776db4
+import hashlib
776db4
 sys.path.append("@FENCEAGENTSLIBDIR@")
776db4
 from fencing import *
776db4
-from fencing import fail, run_delay, EC_LOGIN_DENIED, EC_STATUS
776db4
+from fencing import fail, run_delay, EC_LOGIN_DENIED, EC_STATUS, EC_GENERIC_ERROR
776db4
 
776db4
 state = {
776db4
 	 "running": "on",
776db4
@@ -22,7 +23,7 @@ def get_list(conn, options):
776db4
 
776db4
 	try:
776db4
 		command = "instances?version=2021-05-25&generation=2&limit={}".format(options["--limit"])
776db4
-		res = send_command(conn, command)
776db4
+		res = send_command(conn, options, command)
776db4
 	except Exception as e:
776db4
 		logging.debug("Failed: Unable to get list: {}".format(e))
776db4
 		return outlets
776db4
@@ -38,7 +39,7 @@ def get_list(conn, options):
776db4
 def get_power_status(conn, options):
776db4
 	try:
776db4
 		command = "instances/{}?version=2021-05-25&generation=2".format(options["--plug"])
776db4
-		res = send_command(conn, command)
776db4
+		res = send_command(conn, options, command)
776db4
 		result = state[res["status"]]
776db4
 		if options["--verbose-level"] > 1:
776db4
 			logging.debug("Result:\n{}".format(json.dumps(res, indent=2)))
776db4
@@ -57,27 +58,71 @@ def set_power_status(conn, options):
776db4
 
776db4
 	try:
776db4
 		command = "instances/{}/actions?version=2021-05-25&generation=2".format(options["--plug"])
776db4
-		send_command(conn, command, "POST", action, 201)
776db4
+		send_command(conn, options, command, "POST", action, 201)
776db4
 	except Exception as e:
776db4
 		logging.debug("Failed: Unable to set power to {} for {}".format(options["--action"], e))
776db4
 		fail(EC_STATUS)
776db4
 
776db4
 def get_bearer_token(conn, options):
776db4
+	import os, errno
776db4
+
776db4
+	try:
776db4
+		# FIPS requires usedforsecurity=False and might not be
776db4
+		# available on all distros: https://bugs.python.org/issue9216
776db4
+		hash = hashlib.sha256(options["--apikey"].encode("utf-8"), usedforsecurity=False).hexdigest()
776db4
+	except (AttributeError, TypeError):
776db4
+		hash = hashlib.sha256(options["--apikey"].encode("utf-8")).hexdigest()
776db4
+	file_path = options["--token-file"].replace("[hash]", hash)
776db4
 	token = None
776db4
+
776db4
+	if not os.path.isdir(os.path.dirname(file_path)):
776db4
+		os.makedirs(os.path.dirname(file_path))
776db4
+
776db4
+	# For security, remove file with potentially elevated mode
776db4
 	try:
776db4
-		conn.setopt(pycurl.HTTPHEADER, [
776db4
-			"Content-Type: application/x-www-form-urlencoded",
776db4
-			"User-Agent: curl",
776db4
-		])
776db4
-		token = send_command(conn, "https://iam.cloud.ibm.com/identity/token", "POST", "grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey={}".format(options["--apikey"]))["access_token"]
776db4
-	except Exception:
776db4
-		logging.error("Failed: Unable to authenticate")
776db4
-		fail(EC_LOGIN_DENIED)
776db4
+		os.remove(file_path)
776db4
+	except OSError:
776db4
+		pass
776db4
+
776db4
+	try:
776db4
+		oldumask = os.umask(0)
776db4
+		file_handle = os.open(file_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
776db4
+	except OSError as e:
776db4
+		if e.errno == errno.EEXIST:  # Failed as the file already exists.
776db4
+			logging.error("Failed: File already exists: {}".format(e))
776db4
+			sys.exit(EC_GENERIC_ERROR)
776db4
+		else:  # Something unexpected went wrong
776db4
+			logging.error("Failed: Unable to open file: {}".format(e))
776db4
+			sys.exit(EC_GENERIC_ERROR)
776db4
+	else:  # No exception, so the file must have been created successfully.
776db4
+		with os.fdopen(file_handle, 'w') as file_obj:
776db4
+			try:
776db4
+				conn.setopt(pycurl.HTTPHEADER, [
776db4
+					"Content-Type: application/x-www-form-urlencoded",
776db4
+					"User-Agent: curl",
776db4
+				])
776db4
+				token = send_command(conn, options, "https://iam.cloud.ibm.com/identity/token", "POST", "grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey={}".format(options["--apikey"]))["access_token"]
776db4
+			except Exception as e:
776db4
+				logging.error("Failed: Unable to authenticate: {}".format(e))
776db4
+				fail(EC_LOGIN_DENIED)
776db4
+			file_obj.write(token)
776db4
+	finally:
776db4
+		os.umask(oldumask)
776db4
 
776db4
 	return token
776db4
 
776db4
+def set_bearer_token(conn, bearer_token):
776db4
+	conn.setopt(pycurl.HTTPHEADER, [
776db4
+		"Content-Type: application/json",
776db4
+		"Authorization: Bearer {}".format(bearer_token),
776db4
+		"User-Agent: curl",
776db4
+	])
776db4
+
776db4
+	return conn
776db4
+
776db4
 def connect(opt):
776db4
 	conn = pycurl.Curl()
776db4
+	bearer_token = ""
776db4
 
776db4
 	## setup correct URL
776db4
 	conn.base_url = "https://" + opt["--region"] + ".iaas.cloud.ibm.com/v1/"
776db4
@@ -91,21 +136,28 @@ def connect(opt):
776db4
 	conn.setopt(pycurl.PROXY, "{}".format(opt["--proxy"]))
776db4
 
776db4
 	# get bearer token
776db4
-	bearer_token = get_bearer_token(conn, opt)
776db4
+	try:
776db4
+		try:
776db4
+			# FIPS requires usedforsecurity=False and might not be
776db4
+			# available on all distros: https://bugs.python.org/issue9216
776db4
+			hash = hashlib.sha256(opt["--apikey"].encode("utf-8"), usedforsecurity=False).hexdigest()
776db4
+		except (AttributeError, TypeError):
776db4
+			hash = hashlib.sha256(opt["--apikey"].encode("utf-8")).hexdigest()
776db4
+		f = open(opt["--token-file"].replace("[hash]", hash))
776db4
+		bearer_token = f.read()
776db4
+		f.close()
776db4
+	except IOError:
776db4
+		bearer_token = get_bearer_token(conn, opt)
776db4
 
776db4
 	# set auth token for later requests
776db4
-	conn.setopt(pycurl.HTTPHEADER, [
776db4
-		"Content-Type: application/json",
776db4
-		"Authorization: Bearer {}".format(bearer_token),
776db4
-		"User-Agent: curl",
776db4
-	])
776db4
+	conn = set_bearer_token(conn, bearer_token)
776db4
 
776db4
 	return conn
776db4
 
776db4
 def disconnect(conn):
776db4
 	conn.close()
776db4
 
776db4
-def send_command(conn, command, method="GET", action=None, expected_rc=200):
776db4
+def send_command(conn, options, command, method="GET", action=None, expected_rc=200):
776db4
 	if not command.startswith("https"):
776db4
 		url = conn.base_url + command
776db4
 	else:
776db4
@@ -130,6 +182,26 @@ def send_command(conn, command, method="GET", action=None, expected_rc=200):
776db4
 		raise(e)
776db4
 
776db4
 	rc = conn.getinfo(pycurl.HTTP_CODE)
776db4
+
776db4
+	# auth if token has expired
776db4
+	if rc in [400, 401, 415]:
776db4
+		tokenconn = pycurl.Curl()
776db4
+		token = get_bearer_token(tokenconn, options)
776db4
+		tokenconn.close()
776db4
+		conn = set_bearer_token(conn, token)
776db4
+
776db4
+		# flush web_buffer
776db4
+		web_buffer.close()
776db4
+		web_buffer = io.BytesIO()
776db4
+		conn.setopt(pycurl.WRITEFUNCTION, web_buffer.write)
776db4
+
776db4
+		try:
776db4
+			conn.perform()
776db4
+		except Exception as e:
776db4
+			raise(e)
776db4
+
776db4
+		rc = conn.getinfo(pycurl.HTTP_CODE)
776db4
+
776db4
 	result = web_buffer.getvalue().decode("UTF-8")
776db4
 
776db4
 	web_buffer.close()
776db4
@@ -173,7 +245,7 @@ def define_new_opts():
776db4
 	all_opt["proxy"] = {
776db4
                 "getopt" : ":",
776db4
                 "longopt" : "proxy",
776db4
-                "help" : "--proxy=[http://<URL>:<PORT>]          Proxy: 'http://<URL>:<PORT>'",
776db4
+                "help" : "--proxy=[http://<URL>:<PORT>]  Proxy: 'http://<URL>:<PORT>'",
776db4
                 "required" : "0",
776db4
 		"default": "",
776db4
                 "shortdesc" : "Network proxy",
776db4
@@ -188,14 +260,26 @@ def define_new_opts():
776db4
 		"shortdesc" : "Number of nodes returned by API",
776db4
 		"order" : 0
776db4
 	}
776db4
+	all_opt["token_file"] = {
776db4
+		"getopt" : ":",
776db4
+		"longopt" : "token-file",
776db4
+		"help" : "--token-file=[path]            Path to the token cache file\n"
776db4
+			"\t\t\t\t  (Default: @FENCETMPDIR@/fence_ibm_vpc/[hash].token)\n"
776db4
+			"\t\t\t\t  [hash] will be replaced by a hashed value",
776db4
+		"required" : "0",
776db4
+		"default": "@FENCETMPDIR@/fence_ibm_vpc/[hash].token",
776db4
+		"shortdesc" : "Path to the token cache file",
776db4
+		"order" : 0
776db4
+	}
776db4
 
776db4
 
776db4
 def main():
776db4
 	device_opt = [
776db4
 		"apikey",
776db4
 		"region",
776db4
-		"limit",
776db4
 		"proxy",
776db4
+		"limit",
776db4
+		"token_file",
776db4
 		"port",
776db4
 		"no_password",
776db4
 	]
776db4
diff --git a/tests/data/metadata/fence_ibm_vpc.xml b/tests/data/metadata/fence_ibm_vpc.xml
776db4
index acf4925fc..c35bc4619 100644
776db4
--- a/tests/data/metadata/fence_ibm_vpc.xml
776db4
+++ b/tests/data/metadata/fence_ibm_vpc.xml
776db4
@@ -23,6 +23,10 @@
776db4
 		<content type="string"  />
776db4
 		<shortdesc lang="en">Region</shortdesc>
776db4
 	</parameter>
776db4
+	<parameter name="token_file" unique="0" required="0">
776db4
+		<getopt mixed="--token-file=[path]" />
776db4
+		<shortdesc lang="en">Path to the token cache file</shortdesc>
776db4
+	</parameter>
776db4
 	<parameter name="action" unique="0" required="1">
776db4
 		<getopt mixed="-o, --action=[action]" />
776db4
 		<content type="string" default="reboot"  />