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

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