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

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