Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Example of a generic Bash script, equipped with error handling and input validation, to efficiently decode and process Base64-encoded JSON strings using the `jq` tool.
Example command to simulate how the script will be executed by the Gateway:
#!/usr/bin/env bash
# This script expects a Base64-encoded JSON string as input.
# It decodes the string, extracts and exports some values from the JSON,
# and then decodes another Base64 string to extract and print a specific value.
# Example Usage to test: history -c && echo "BASE64STRING==" | /path/to/script.sh
# Ensure the script exits in case of a non-zero status from any command
# and ensure that pipeline commands return the exit status of the last command to fail.
set -o pipefail -e
# Read the input into the 'params' variable
IFS= read -r params
# Validate input
if [[ -z "$params" ]]; then
echo "Error: No input provided."
exit 1
fi
# Check if input is a valid Base64 string
if ! echo "$params" | base64 -d &> /dev/null; then
echo "Error: Invalid Base64 input."
exit 1
fi
# Decode the Base64-encoded JSON string
json=$(echo "$params" | base64 -d)
# Validate JSON
if ! echo "$json" | jq empty &> /dev/null; then
echo "Error: Invalid JSON."
exit 1
fi
# Check for the existence of the 'jq' tool, which is required for parsing JSON
if ! command -v jq &> /dev/null; then
echo "Error: jq is not installed. Please install jq and try again."
exit 1
fi
# Check for required keys
for key in providerRecordUid resourceRecordUid userRecordUid newPassword oldPassword user records; do
if ! echo "$json" | jq -e ."$key" &> /dev/null; then
echo "Error: Key '$key' not found in JSON."
exit 1
fi
done
# Extract and export key-value pairs from the JSON string
eval $( echo "$json" | jq -r 'keys[] as $k | "export \($k)=\(.[$k])"' )
# Print the exported values to the terminal
echo "providerRecordUid=$providerRecordUid"
echo "resourceRecordUid=$resourceRecordUid"
echo "userRecordUid=$userRecordUid"
echo "newPassword=$newPassword"
echo "oldPassword=$oldPassword"
echo "user=$user"
# Decode the 'records' variable, which is expected to be another Base64-encoded JSON string
recordJson=$(echo "$records" | base64 -d)
# Validate inner record JSON
if ! echo "$recordJson" | jq empty &> /dev/null; then
echo "Error: Invalid JSON in records."
exit 1
fi
# Extract and print the title associated with the 'providerRecordUid'
title=$(echo "$recordJson" | jq -r ".array[] | select(.uid==\"$providerRecordUid\").title")
echo "Provider Title=$title"
history -c && echo "ewogICAgInByb3ZpZGVyUmVjb3JkVWlkIjogIjEyMzQ1IiwKICAgICJyZXNvdXJjZVJlY29yZFVpZCI6ICI2Nzg5MCIsCiAgICAidXNlclJlY29yZFVpZCI6ICIxMTIyMzMiLAogICAgIm5ld1Bhc3N3b3JkIjogIm5ld1Bhc3MxMjMiLAogICAgIm9sZFBhc3N3b3JkIjogIm9sZFBhc3M0NTYiLAogICAgInVzZXIiOiAidXNlcm5hbWUiLAogICAgInJlY29yZHMiOiAiZXlKaGNuSmhlU0k2SUZ0N0luVnBaQ0k2SUNJeE1qTTBOU0lzSW5ScGRHeGxJam9nSWxCeWIzWnBaR1Z5SURFaWZWMTkiCn0K" | /path/to/script.sh
#!/usr/bin/env bash
# This will be executed as the following
# history -c && echo "BASE64STRING==" | /path/to/script.sh
# Without this the script might report a success
# if something fails in the script.
set -o pipefail -e
IFS= read -r params
json=$(echo "$params" | base64 -d)
# There is no built int JSON parser.
# In order to parse JSON, a tool like jq or fx is required.
$( echo "$json" | jq -r 'keys[] as $k | "export \($k)=\(.[$k])"' )
echo "providerRecordUid=$providerRecordUid"
echo "resourceRecordUid=$resourceRecordUid"
echo "userRecordUid=$userRecordUid"
echo "newPassword=$newPassword"
echo "oldPassword=$oldPassword"
echo "user=$user"
# Record data is another Base64 JSON. And values can be obtained by using 'jq'
recordJson=$(echo "$records" | base64 -d)
title=$(echo "$recordJson" | jq -r ".[] | select(.uid==\"$providerRecordUid\").title")
echo "Provider Title=$title"
# Parse data from record JSON with jq
UserRecordLogin=$(ksm secret get --json --uid=$userRecordUid | jq -r '.fields[] | select(.type == "login" or .label == "login").value[0]')
echo "UserRecordLogin=$UserRecordLogin"
# Requires ksm CLI binary installed and initialized with device config
# that provides access to the vault records
# Get data using notation
UserRecordTitle=$( ksm secret notation $userRecordUid/title )
UserRecordLogin=$( ksm secret notation $userRecordUid/field/login )
echo "UserRecordTitle=$UserRecordTitle"
echo "UserRecordLogin=$UserRecordLogin"
#!/usr/bin/env python3
import sys
import base64
import json
# Requires Keeper Secrets Manager Python SDK installed and initialized
# with device config that provides access to the vault records
# pip install keeper-secrets-manager-core
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
# sys.stdin is not an array, it can not subscripted (ie sys.stdin[0])
for base64_params in sys.stdin:
params = json.loads(base64.b64decode(base64_params).decode())
print(f"providerRecordUid={params.get('providerRecordUid')}")
print(f"resourceRecordUid={params.get('resourceRecordUid')}")
print(f"userRecordUid={params.get('userRecordUid')}")
print(f"newPassword={params.get('newPassword')}")
print(f"oldPassword={params.get('oldPassword')}")
print(f"user={params.get('user')}")
records = json.loads(base64.b64decode(params.get('records')).decode())
print("Provider Title="
f"{next((x for x in records if x['uid'] == params.get('providerRecordUid')), None).get('title')}")
record_keys = ('providerRecordUid', 'resourceRecordUid', 'userRecordUid')
record_uids = [params.get(x) for x in record_keys if x in params]
ksm = SecretsManager(config=FileKeyValueStorage(r'/path/ksm-config.json'))
resource_records = ksm.get_secrets(record_uids)
for record in resource_records:
print(f"Record UID: {record.uid}, Title: {record.title}")
break
while (Console.ReadLine() is string line)
{
var base64EncodedBytes = System.Convert.FromBase64String(line);
var json = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
var jsonDom = System.Text.Json.JsonSerializer.Deserialize<System.Text.Json.Nodes.JsonObject>(json)!;
var providerRecordUid = (string)jsonDom["providerRecordUid"]!;
var resourceRecordUid = (string)jsonDom["resourceRecordUid"]!;
var userRecordUid = (string)jsonDom["userRecordUid"]!;
var newPassword = (string)jsonDom["newPassword"]!;
var oldPassword = (string)jsonDom["oldPassword"]!;
var user = (string)jsonDom["user"]!;
Console.WriteLine($"providerRecordUid={providerRecordUid}\n" +
$"resourceRecordUid={resourceRecordUid}\n" +
$"userRecordUid={userRecordUid}\n" +
$"newPassword={newPassword}\n" +
$"oldPassword={oldPassword}\n" +
$"user={user}\n");
if (jsonDom["records"] != null)
{
base64EncodedBytes = System.Convert.FromBase64String((string)jsonDom["records"]!);
json = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
var recordsDom = System.Text.Json.JsonSerializer.Deserialize<System.Text.Json.Nodes.JsonArray>(json)!;
foreach (var item in recordsDom)
{
Console.WriteLine($"Title={item!["title"]}");
}
}
}
// Depends on Keeper.SecretsManager package
// dotnet add package Keeper.SecretsManager
using SecretsManager;
while (Console.ReadLine() is string line)
{
Console.WriteLine(line);
var base64EncodedBytes = System.Convert.FromBase64String(line);
var json = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
var jsonDom = System.Text.Json.JsonSerializer.Deserialize<System.Text.Json.Nodes.JsonObject>(json)!;
var providerRecordUid = (string)jsonDom["providerRecordUid"]!;
var resourceRecordUid = (string)jsonDom["resourceRecordUid"]!;
var userRecordUid = (string)jsonDom["userRecordUid"]!;
var newPassword = (string)jsonDom["newPassword"]!;
var oldPassword = (string)jsonDom["oldPassword"]!;
var user = (string)jsonDom["user"]!;
Console.WriteLine($"providerRecordUid={providerRecordUid}\n" +
$"resourceRecordUid={resourceRecordUid}\n" +
$"userRecordUid={userRecordUid}\n" +
$"newPassword={newPassword}\n" +
$"oldPassword={oldPassword}\n" +
$"user={user}\n");
//var storage = new LocalConfigStorage("config.json");
var storage = new InMemoryStorage("BASE64Config==");
var options = new SecretsManagerOptions(storage);
var recordUids = new string[] { providerRecordUid, resourceRecordUid, userRecordUid };
var secrets = await SecretsManagerClient.GetSecrets(options, recordUids);
foreach (var record in secrets.Records)
{
Console.WriteLine($"Record UID: {record.RecordUid}, Title: {record.Data.title}");
}
}
#!/usr/bin/env python3
import sys
import base64
import json
# sys.stdin is not an array, it can not subscripted (ie sys.stdin[0])
for base64_params in sys.stdin:
params = json.loads(base64.b64decode(base64_params).decode())
print(f"providerRecordUid={params.get('providerRecordUid')}")
print(f"resourceRecordUid={params.get('resourceRecordUid')}")
print(f"userRecordUid={params.get('userRecordUid')}")
print(f"newPassword={params.get('newPassword')}")
print(f"oldPassword={params.get('oldPassword')}")
print(f"user={params.get('user')}")
records = json.loads(base64.b64decode(params.get('records')).decode())
print("Provider Title="
f"{next((x for x in records if x['uid'] == params.get('providerRecordUid')), None).get('title')}")
break
# This will be executed as the following
# ECHO "BASE64STRING==" | .\script.ps1; Clear-History
Begin {
# Executes once before first item in pipeline is processed
}
Process {
# Stop if error. If not set, result value will be True and assumed there
# was no problems.
$ErrorActionPreference = "Stop"
# Executes once for each pipeline object
$JSON = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($_))
$Params=($JSON | ConvertFrom-Json)
Write-Output "providerRecordUid=$($Params.providerRecordUid)"
Write-Output "resourceRecordUid=$($Params.resourceRecordUid)"
Write-Output "userRecordUid=$($Params.userRecordUid)"
Write-Output "newPassword=$($Params.newPassword)"
Write-Output "oldPassword=$($Params.oldPassword)"
Write-Output "user=$($Params.user)"
$recordsJSON = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Params.records))
$records = ($recordsJSON | ConvertFrom-Json)
$title = ($records | Where-Object {$_.uid -eq $Params.providerRecordUid}).title
Write-Output "Provider Title=$title"
}
End {
# Executes once after last pipeline object is processed
}
#!/usr/bin/env bash
# This will be executed as the following
# history -c && echo "BASE64STRING==" | /path/to/script.sh
# Without this the script might report a success
# if something fails in the script.
set -o pipefail -e
IFS= read -r params
json=$(echo "$params" | base64 -d)
# There is no built int JSON parser.
# In order to parse JSON, a tool like jq or fx is required.
$( echo "$json" | jq -r 'keys[] as $k | "export \($k)=\(.[$k])"' )
# Requires htpasswd from apache2-utils (Ubuntu) or httpd-tools (CentOS)
# Note: -c option creates new file but if file already exists it overwrites and truncates
htpasswd -b ~/path/to/pwdfile $user $newPassword