Skip to content

Instantly share code, notes, and snippets.

@llamasoft
Last active September 27, 2019 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llamasoft/92f02f7d5b132e9715a2ee8c1f20d5c7 to your computer and use it in GitHub Desktop.
Save llamasoft/92f02f7d5b132e9715a2ee8c1f20d5c7 to your computer and use it in GitHub Desktop.
HVAC URL Escape Demo
import hvac
import pprint
import six.moves.urllib.parse as urllib
client = hvac.Client("http://localhost:8200")
def quote_path(path):
"""Returns a string that's safe to use as a path."""
# Yes, safe = "/" is the default, but I pass it here just to make it obvious.
return urllib.quote(path, safe = "/")
def quote_value(value):
"""Returns a string that's safe to use as a single value."""
# Similar to `quote_path` but also escapes "/".
# NOTE: we can't use `quote_plus` because it changes spaces to "+"
# which Vault treats as a literal plus.
return urllib.quote(value, safe = "")
# Absolute worst-case example of an annoying value
problem_value = "escape value/url?test%1"
print("Problem Name: {}".format( problem_value ))
print("Path-Safe Name: {}".format( quote_path(problem_value) ))
print("Value-Safe Name: {}".format( quote_value(problem_value) ))
print("")
# Create the user with some troublesome characters in their name
resp = client.secrets.identity.create_or_update_entity(
name = problem_value,
policies = ["demo"],
metadata = {
"problem": "true"
}
)
print("Newly created Entity:")
pprint.pprint(resp["data"])
print("")
# Attempting to read back the Entity by name results in a `hvac.exceptions.InvalidPath`.
try:
resp = client.secrets.identity.read_entity_by_name(
name = problem_value
)
print("Unquoted Entity name:")
pprint.pprint(resp["data"])
print("")
except Exception as ex:
print("Got {} exception reading Entity: {!r}".format(ex.__class__, ex))
print("")
# Attempting to read back the Entity works after manually URL quoting
resp = client.secrets.identity.read_entity_by_name(
name = quote_value(problem_value)
)
print("Quoted Entity name:")
pprint.pprint(resp["data"])
print("")
# Removing the demo Entity
client.secrets.identity.delete_entity_by_name(
name = quote_value(problem_value)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment