patternpythonMinor
Validating JavaScript origins
Viewed 0 times
javascriptoriginsvalidating
Problem
I need to write a function in Python that makes sure the user entered a valid JavaScript origin. If I understand it correctly, the origin includes the scheme, hostname and port (port and scheme might be implicit, defaulting to 80 and http respectively), so would this be a correct way to validate it?
The origin will be used to pass as the preferredOrigin to window.postMessage.
The main thing I'm worried about is that I'm not sure how credentials in the url (username:password@example.com) are handled.
Going to
import urlparse
def validate_javascript_origin(origin):
parsed = urlparse.urlsplit(origin)
if parsed.scheme and parsed.scheme not in ["http", "https"]:
raise ValueError("Only the http and https url schemes are supported.")
if not parsed.netloc:
raise ValueError("The origin must include a hostname.")
if parsed.path or parsed.query or parsed.fragment:
raise ValueError("The origin must not contain a path, query string or fragment.")The origin will be used to pass as the preferredOrigin to window.postMessage.
The main thing I'm worried about is that I'm not sure how credentials in the url (username:password@example.com) are handled.
Going to
http://username@frederikcreemers.be, and getting location.originin javascript returns http://frederikcreemers.be, so the origin doesn't include credentials. Would it be sufficient to add a condition like this to the function above:if "@" in parsed.netloc:
raise ValueError("The origin must not contain credentials.")Solution
- First off, easy task, add a docstring to your function,
validate_javascript_origins, and describe this function, and its arguments, preferably in detail.
- Finally, if you're worried about input like
username@site.end, you should add the check for the@character. If it isn't valid input, or the input is interpreted in the wrong way, you should most definitely add this check.
Context
StackExchange Code Review Q#82165, answer score: 3
Revisions (0)
No revisions yet.