4
\$\begingroup\$

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?

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:[email protected]) are handled.

Going to http://[email protected], 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.")
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
  1. First off, easy task, add a docstring to your function, validate_javascript_origins, and describe this function, and its arguments, preferably in detail.
  2. Finally, if you're worried about input like [email protected], 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.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.