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

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