From a2d069f7554ea1a193a9f3b208690c6353789ad0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Franti=C5=A1ek=20Dvo=C5=99=C3=A1k?= <valtri@civ.zcu.cz>
Date: Wed, 7 Feb 2024 10:22:42 +0000
Subject: [PATCH] Helper script for loging in to vault service

---
 vault-login.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 70 insertions(+)
 create mode 100755 vault-login.py

diff --git a/vault-login.py b/vault-login.py
new file mode 100755
index 0000000..a206a1d
--- /dev/null
+++ b/vault-login.py
@@ -0,0 +1,70 @@
+#! /bin/python3
+
+#
+# Get the OIDC access token using service client credentials and login into
+# Hashicorp Vault.
+#
+
+import json
+import os
+import re
+import requests
+import shutil
+import subprocess
+import sys
+
+payload = {
+    "grant_type": "client_credentials",
+    "scope": "openid profile eduperson_entitlement email voperson_id",
+}
+token_url = "https://aai.egi.eu/auth/realms/egi/protocol/openid-connect/token"
+userinfo_url = \
+        "https://aai.egi.eu/auth/realms/egi/protocol/openid-connect/userinfo"
+
+# input
+if "CLIENT_ID" in os.environ:
+    payload["client_id"] = os.environ["CLIENT_ID"]
+else:
+    payload["client_id"] = input("OIDC Client ID: ")
+if "CLIENT_SECRET" in os.environ:
+    payload["client_secret"] = os.environ["CLIENT_SECRET"]
+else:
+    payload["client_secret"] = input("OIDC Client Secret: ")
+
+# get OIDC token
+r = requests.post(token_url, data=payload)
+data = json.loads(r.text)
+if 'access_token' not in data:
+    print('Error getting access token')
+    sys.exit(1)
+print("# export OIDC_ACCESS_TOKEN='%s'" % data["access_token"])
+
+# get vault token
+token = None
+p = subprocess.Popen([
+    shutil.which("vault"),
+    "write",
+    "auth/jwt/login",
+    "jwt=%s" % data["access_token"],
+    ], stdout=subprocess.PIPE)
+for line in p.stdout:
+    print('# %s' % line.decode("UTF-8").rstrip())
+    m = re.search(r'^token\s+(.*)', line.decode("UTF-8"))
+    if m is not None:
+        token = m.group(1)
+retval = p.wait()
+if token is None:
+    print('Error signing to vault (no token returned)')
+    sys.exit(1)
+print("export VAULT_TOKEN='%s'" % token)
+if retval != 0:
+    print('Error signing to vault (code %d returned)' % retval)
+    sys.exit(1)
+
+# store vault token
+token_path = os.path.expanduser('~/.vault-token')
+with open(token_path, 'w') as f:
+    pass
+os.chmod(token_path, 0o600)
+with open(token_path, 'w') as f:
+    f.write(token)
-- 
GitLab