-
Notifications
You must be signed in to change notification settings - Fork 0
/
pritunl-api-shell
executable file
·71 lines (60 loc) · 2.51 KB
/
pritunl-api-shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env bash
# Pritunl API shell wrapper for secure and simplified command-line requests
# Usage: <this-script> <method> <path> [payload]
# Enable error handling: exit on error, unset variables, and pipefail
set -euo pipefail
# Check if the required arguments are provided
if [ $# -eq 0 ]; then
# Display usage examples and exit
echo "Usage: ${0} <method> <path> [payload]"
echo ""
echo "Examples:"
echo " ${0} GET /entity-uri"
echo " ${0} POST /entity-uri '{\"name\":\"New Entity\"}'"
echo " ${0} PUT /entity-uri '{\"name\":\"Update Entity\"}'"
echo " ${0} DELETE /entity-uri"
exit 1
fi
# Load API credentials and base URL from environment variables
base_url=${PRITUNL_BASE_URL:-} # Get the base URL from the environment variable
api_token=${PRITUNL_API_TOKEN:-} # Get the API token from the environment variable
api_secret=${PRITUNL_API_SECRET:-} # Get the API secret from the environment variable
# Generate authentication timestamp and nonce
auth_timestamp=$(date +%s) # Get the current timestamp in seconds
auth_nonce=$(uuidgen | tr -d -) # Generate a random nonce without hyphens
# Construct the authentication string and signature
auth_string="$api_token&$auth_timestamp&$auth_nonce&${1^^}&$2" # Create the authentication string
hmacv=$(echo -n "$auth_string" | openssl dgst -sha256 -hmac "$api_secret" -binary) # Generate the HMAC signature
auth_signature=$(echo -n "$hmacv" | base64 -w 0) # Encode the signature in base64
# Set the API request headers
headers=(
-H "Auth-Token: $api_token" # API token header
-H "Auth-Timestamp: $auth_timestamp" # Timestamp header
-H "Auth-Nonce: $auth_nonce" # Nonce header
-H "Auth-Signature: $auth_signature" # Signature header
-H "Content-Type: application/json" # JSON content type header
)
api_path=${base_url}${2} # Construct the full API path
request_payload="${3:-}" # Get the request payload (if provided)
# Make the API request using curl
response=$(curl -sSL -X "$1" "${headers[@]}" "${api_path}" -d "${request_payload}") # Make the API request
# Check the response code
if [ $? -ne 0 ]; then
# Output the raw error response
echo "$response" >&2
exit 1
fi
# Pretty-print the output using jq if available
if command -v jq &> /dev/null; then
# Check if the response is valid JSON
if ! echo "$response" | jq -e . >/dev/null 2>&1; then
# If not valid JSON, output the raw error response
echo "$response" >&2
exit 1
fi
# Use jq to format the output
echo "$response" | jq
else
# Output the raw response
echo "$response"
fi