Skip to content

Commit

Permalink
Merge pull request #2 from ARGOeu-Metrics/devel
Browse files Browse the repository at this point in the history
Version 0.1.0
  • Loading branch information
themiszamani authored Jun 9, 2022
2 parents 8015ce0 + 6ee63bc commit de943db
Show file tree
Hide file tree
Showing 12 changed files with 474 additions and 1 deletion.
59 changes: 59 additions & 0 deletions Jenkinsfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
pipeline {
agent any
options {
checkoutToSubdirectory('argo-probe-oidc')
}
environment {
PROJECT_DIR="argo-probe-oidc"
GIT_COMMIT=sh(script: "cd ${WORKSPACE}/$PROJECT_DIR && git log -1 --format=\"%H\"",returnStdout: true).trim()
GIT_COMMIT_HASH=sh(script: "cd ${WORKSPACE}/$PROJECT_DIR && git log -1 --format=\"%H\" | cut -c1-7",returnStdout: true).trim()
GIT_COMMIT_DATE=sh(script: "date -d \"\$(cd ${WORKSPACE}/$PROJECT_DIR && git show -s --format=%ci ${GIT_COMMIT_HASH})\" \"+%Y%m%d%H%M%S\"",returnStdout: true).trim()

}
stages {
stage ('Build'){
parallel {
stage ('Build Centos 7') {
agent {
docker {
image 'argo.registry:5000/epel-7-ams'
args '-u jenkins:jenkins'
}
}
steps {
echo 'Building Rpm...'
withCredentials(bindings: [sshUserPrivateKey(credentialsId: 'jenkins-rpm-repo', usernameVariable: 'REPOUSER', \
keyFileVariable: 'REPOKEY')]) {
sh "/home/jenkins/build-rpm.sh -w ${WORKSPACE} -b ${BRANCH_NAME} -d centos7 -p ${PROJECT_DIR} -s ${REPOKEY}"
}
archiveArtifacts artifacts: '**/*.rpm', fingerprint: true
}
post {
always {
cleanWs()
}
}
}
}
}
}
post {
always {
cleanWs()
}
success {
script{
if ( env.BRANCH_NAME == 'master' || env.BRANCH_NAME == 'devel' ) {
slackSend( message: ":rocket: New version for <$BUILD_URL|$PROJECT_DIR>:$BRANCH_NAME Job: $JOB_NAME !")
}
}
}
failure {
script{
if ( env.BRANCH_NAME == 'master' || env.BRANCH_NAME == 'devel' ) {
slackSend( message: ":rain_cloud: Build Failed for <$BUILD_URL|$PROJECT_DIR>:$BRANCH_NAME Job: $JOB_NAME")
}
}
}
}
}
3 changes: 3 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
include src/*
include modules/*
include argo-probe-oidc.spec
23 changes: 23 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
PKGNAME=argo-probe-oidc
SPECFILE=${PKGNAME}.spec
PKGVERSION=$(shell grep -s '^Version:' $(SPECFILE) | sed -e 's/Version: *//')

dist:
rm -rf dist
python setup.py sdist
mv dist/${PKGNAME}-${PKGVERSION}.tar.gz .
rm -rf dist

srpm: dist
rpmbuild -ts --define='dist .el6' ${PKGNAME}-${PKGVERSION}.tar.gz

rpm: dist
rpmbuild -ta ${PKGNAME}-${PKGVERSION}.tar.gz

sources: dist

clean:
rm -rf ${PKGNAME}-${PKGVERSION}.tar.gz
rm -f MANIFEST
rm -rf dist

69 changes: 68 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,68 @@
# argo-probe-oidc-token
# argo-probe-oidc

The package contains metrics to handle OIDC tokens. There are two metrics:

* `fetch-access-token`
* `check-refresh-token-expiration`

The former is used for fetching the OIDC access token, and the latter is used to check the validity of the refresh token which is needed for fetching of the access token.

## Synopsis

### fetch-access-token

The probe `fetch-access-token` has several arguments.

```
# /usr/libexec/argo/probes/oidc/fetch-access-token --help
usage: fetch-access-token [-h] [-u URL] --client_id CLIENT_ID --client_secret
CLIENT_SECRET --refresh_token REFRESH_TOKEN
[--token_file TOKEN_FILE] [-t TIMEOUT]
Nagios probe for fetching OIDC tokens.
optional arguments:
-h, --help show this help message and exit
-u URL, --url URL URL from which the token is fetched
--client_id CLIENT_ID
The identifier of the client
--client_secret CLIENT_SECRET
The secret value of the client
--refresh_token REFRESH_TOKEN
The value of the refresh token
--token_file TOKEN_FILE
File for storing obtained token
-t TIMEOUT, --timeout TIMEOUT
timeout
```

Example execution of the probe:

```
/usr/libexec/argo/probes/oidc/fetch-access-token -u https://aai.egi.eu/auth/realms/egi/protocol/openid-connect/token --client_id <client_id> --client_secret <client_secret> --refresh_token <refresh_token> --token_file /path/to/oidc_token_file -t 60
OK - Access token fetched successfully.
```

### check-refresh-token-expiration

The probe `check-refresh-token-expiration` has two arguments.

```
# /usr/libexec/argo/probes/oidc/check-refresh-token-expiration --help
usage: check-refresh-token-expiration [-h] --token TOKEN [-t TIMEOUT]
Nagios probe for checking refresh token expiration
optional arguments:
-h, --help show this help message and exit
--token TOKEN Refresh token
-t TIMEOUT, --timeout TIMEOUT
timeout
```

Example execution of the probe:

```
# /usr/libexec/argo/probes/oidc/check-refresh-token-expiration --token <refresh_token> -t 30
OK - Refresh token valid.
```
41 changes: 41 additions & 0 deletions argo-probe-oidc.spec
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# sitelib
%{!?python_sitelib: %global python_sitelib %(%{__python} -c "from distutils.sysconfig import get_python_lib; print get_python_lib()")}
%define dir /usr/libexec/argo/probes/oidc

Name: argo-probe-oidc
Summary: ARGO probes for handling of OIDC tokens.
Version: 0.1.0
Release: 1%{?dist}
License: ASL 2.0
Source0: %{name}-%{version}.tar.gz
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root
BuildArch: noarch
Requires: python-requests, python-argparse, python-jwt

%description
This package includes probes for fetching OIDC access token and checking refresh token validity.

%prep
%setup -q

%build
%{__python} setup.py build

%install
rm -rf %{buildroot}
%{__python} setup.py install --skip-build --root %{buildroot} --record=INSTALLED_FILES
install -d -m 755 %{buildroot}/%{dir}
install -d -m 755 %{buildroot}/%{python_sitelib}/argo_probe_oidc

%clean
rm -rf %{buildroot}

%files -f INSTALLED_FILES
%defattr(-,root,root,-)
%{python_sitelib}/argo_probe_oidc
%{dir}


%changelog
* Thu Jun 9 2022 Katarina Zailac <kzailac@gmail.com> - 0.1.0-1%{?dist}
- Initial version
45 changes: 45 additions & 0 deletions modules/NagiosResponse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class NagiosResponse(object):
_msgBagWarning = []
_msgBagCritical = []
_msgBagOk = []
_okMsg = ""
_code = None

OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3

def __init__(self, ok_msg=""):
self._code = self.OK
self._okMsg = ok_msg

def writeWarningMessage(self, msg):
self._msgBagWarning.append(msg)

def writeOkMessage(self, msg):
self._msgBagOk.append(msg)

def writeCriticalMessage(self, msg):
self._msgBagCritical.append(msg)

def setCode(self, code):
self._code = code

def getCode(self):
return self._code

def getMsg(self):
if self._code == self.WARNING:
return "WARNING - " + self._toString(self._msgBagWarning)
elif self._code == self.CRITICAL:
return "CRITICAL - " + self._toString(self._msgBagCritical)
elif self._code == self.OK:
msg = self._okMsg if self._okMsg else self._toString(self._msgBagOk)
return "OK - " + msg
else:
return "UNKNOWN!"

def _toString(self, msgArray):
return ' / '.join(msgArray)

Empty file added modules/__init__.py
Empty file.
116 changes: 116 additions & 0 deletions modules/fetch_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#!/usr/bin/env python
import argparse
import grp
import os
import pwd
import sys

import requests

from NagiosResponse import NagiosResponse


def main():
parser = argparse.ArgumentParser(
description="Nagios probe for fetching OIDC tokens."
)
parser.add_argument(
"-u", "--url", dest="url", type=str,
default="https://aai.egi.eu/oidc/token",
help="URL from which the token is fetched"
)
parser.add_argument(
"--client_id", dest="client_id", type=str, required=True,
help="The identifier of the client"
)
parser.add_argument(
"--client_secret", dest="client_secret", type=str, required=True,
help="The secret value of the client"
)
parser.add_argument(
"--refresh_token", dest="refresh_token", type=str, required=True,
help="The value of the refresh token"
)
parser.add_argument(
"--token_file", dest="token_file", type=str,
default="/etc/nagios/globus/oidc",
help="File for storing obtained token"
)
parser.add_argument(
"-t", "--timeout", dest="timeout", type=int, default=60,
help="timeout"
)
args = parser.parse_args()

nagios = NagiosResponse("Access token fetched successfully.")

try:
response = requests.post(
args.url,
auth=(args.client_id, args.client_secret),
data={
"client_id": args.client_id,
"client_secret": args.client_secret,
"grant_type": "refresh_token",
"refresh_token": args.refresh_token,
"scope": "openid email profile eduperson_entitlement"
},
timeout=args.timeout
)
response.raise_for_status()

access_token = response.json()["access_token"]

with open(args.token_file, "w") as f:
f.write(access_token)

try:
uid = pwd.getpwnam("nagios").pw_uid

except KeyError:
nagios.writeCriticalMessage("No user named 'nagios'")
nagios.setCode(nagios.CRITICAL)
print nagios.getMsg()
sys.exit(nagios.getCode())

try:
gid = grp.getgrnam("nagios").gr_gid

except KeyError:
nagios.writeCriticalMessage("No group named 'nagios'")
nagios.setCode(nagios.CRITICAL)
print nagios.getMsg()
sys.exit(nagios.getCode())

os.chown(args.token_file, uid, gid)

print nagios.getMsg()
sys.exit(nagios.getCode())

except (
requests.exceptions.HTTPError,
requests.exceptions.ConnectionError,
requests.exceptions.RequestException,
ValueError,
KeyError
) as e:
nagios.writeCriticalMessage(str(e))
nagios.setCode(nagios.CRITICAL)
print nagios.getMsg()
sys.exit(nagios.getCode())

except IOError as e:
nagios.writeCriticalMessage("Error creating file: " + str(e))
nagios.setCode(nagios.CRITICAL)
print nagios.getMsg()
sys.exit(nagios.getCode())

except Exception as e:
nagios.writeCriticalMessage(str(e))
nagios.setCode(nagios.CRITICAL)
print nagios.getMsg()
sys.exit(nagios.getCode())


if __name__ == "__main__":
main()
Loading

0 comments on commit de943db

Please sign in to comment.