def test_token_endpoint(self): authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = self.provider.sdb sid = _sdb.access_token.key(user="******", areq=authreq) access_grant = _sdb.access_token(sid=sid) _sdb[sid] = { "oauth_state": "authz", "sub": "sub", "authzreq": "", "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz" } # Construct Access token request areq = AccessTokenRequest(code=access_grant, redirect_uri="http://example.com/authz", client_id="client1", client_secret="hemlighet", grant_type='authorization_code') with LogCapture(level=logging.DEBUG) as logcap: resp = self.provider.token_endpoint(request=areq.to_urlencoded()) atr = AccessTokenResponse().deserialize(resp.message, "json") assert _eq(atr.keys(), ['access_token', 'token_type', 'refresh_token']) expected = ( 'body: code=<REDACTED>&client_secret=<REDACTED>&grant_type' '=authorization_code' ' &client_id=client1&redirect_uri=http%3A%2F%2Fexample.com%2Fauthz') assert _eq(parse_qs(logcap.records[1].msg[6:]), parse_qs(expected[6:])) expected = {u'code': '<REDACTED>', u'client_secret': '<REDACTED>', u'redirect_uri': u'http://example.com/authz', u'client_id': 'client1', u'grant_type': 'authorization_code'} # Don't try this at home, kids! # We have to eval() to a dict here because otherwise the arbitrary # ordering of the string causes the test to fail intermittently. assert _eq(eval(logcap.records[2].msg[4:]), expected) assert _eq(logcap.records[3].msg, 'Verified Client ID: client1') expected = {'redirect_uri': u'http://example.com/authz', 'client_secret': '<REDACTED>', 'code': u'<REDACTED>', 'client_id': 'client1', 'grant_type': 'authorization_code'} assert eval(logcap.records[4].msg[20:]) == expected expected = {'code': '<REDACTED>', 'authzreq': '', 'sub': 'sub', 'access_token': '<REDACTED>', 'token_type': 'Bearer', 'redirect_uri': 'http://example.com/authz', 'code_used': True, 'client_id': 'client1', 'oauth_state': 'token', 'refresh_token': '<REDACTED>', 'access_token_scope': '?'} assert _eq(eval(logcap.records[5].msg[7:]), expected) expected = {'access_token': u'<REDACTED>', 'token_type': 'Bearer', 'refresh_token': '<REDACTED>'} assert _eq(eval(logcap.records[6].msg[21:]), expected)
def verify_endpoint(self, request="", cookie=None, **kwargs): _req = parse_qs(request) try: areq = parse_qs(_req["query"][0]) except KeyError: return BadRequest() authn, acr = self.pick_auth(areq=areq) kwargs["cookie"] = cookie return authn.verify(_req, **kwargs)
def verify_endpoint(self, request="", cookie=None, **kwargs): _req = parse_qs(request) try: areq = parse_qs(_req["query"][0]) except KeyError: return BadRequest('Could not verify endpoint') authn, acr = self.pick_auth(areq=areq) kwargs["cookie"] = cookie return authn.verify(_req, **kwargs)
def test_parse_qs_encoding(self): result = urllib_parse.parse_qs("key=\u0141%E9", encoding="latin-1") self.assertEqual(result, {'key': ['\u0141\xE9']}) result = urllib_parse.parse_qs("key=\u0141%C3%A9", encoding="utf-8") self.assertEqual(result, {'key': ['\u0141\xE9']}) result = urllib_parse.parse_qs("key=\u0141%C3%A9", encoding="ascii") self.assertEqual(result, {'key': ['\u0141\ufffd\ufffd']}) result = urllib_parse.parse_qs("key=\u0141%E9-", encoding="ascii") self.assertEqual(result, {'key': ['\u0141\ufffd-']}) result = urllib_parse.parse_qs("key=\u0141%E9-", encoding="ascii", errors="ignore") self.assertEqual(result, {'key': ['\u0141-']})
def template_args(self, end_point_index=0, **kwargs): """ Method to override if necessary, dependent on the page layout and context :param kwargs: :return: dictionary of parameters used to build the Authn page """ print("KWARGSTOT: ", kwargs) try: action = kwargs["action"] except KeyError: action = self.verification_endpoints[end_point_index] print("MANOLOOOOOOO: ", parse_qs(kwargs["request"])['url'][0]) argv = {"password": "", "action": action, "url": parse_qs(kwargs["request"])['url'][0]} for fro, to in self.param_map.items(): try: argv[to] = kwargs[fro] except KeyError: argv[to] = "" if "extra" in kwargs: for param in kwargs["extra"]: try: argv[param] = kwargs[param] except KeyError: argv[param] = "" try: _locs = kwargs["ui_locales"] except KeyError: argv.update(LOC["en"]) else: for loc in _locs: try: argv.update(LOC[loc]) except KeyError: pass else: break try: argv.update({ 'title': 'TOTP verification', 'form_action': self.verification_endpoints[end_point_index], 'username': parse_qs(kwargs["request"])["login"][0] }) # print("KWARGS2: ",kwargs) except KeyError: print("KWARGS: ", kwargs) return argv
def parse_discovery_service_request(self, url="", query=""): if url: part = urlparse(url) dsr = parse_qs(part[4]) elif query: dsr = parse_qs(query) else: dsr = {} # verify for key in ["isPassive", "return", "returnIDParam", "policy", 'entityID']: try: assert len(dsr[key]) == 1 dsr[key] = dsr[key][0] except KeyError: pass if "return" in dsr: part = urlparse(dsr["return"]) if part.query: qp = parse_qs(part.query) if "returnIDParam" in dsr: assert dsr["returnIDParam"] not in qp.keys() else: assert "entityID" not in qp.keys() else: # If metadata not used this is mandatory raise VerificationError("Missing mandatory parameter 'return'") if "policy" not in dsr: dsr["policy"] = IDPDISC_POLICY try: assert dsr["isPassive"] in ["true", "false"] except KeyError: pass if "isPassive" in dsr and dsr["isPassive"] == "true": dsr["isPassive"] = True else: dsr["isPassive"] = False if not "returnIDParam" in dsr: dsr["returnIDParam"] = "entityID" return dsr
def get_signed_id_tokens(conv): res = [] for item in conv.events.get_data(EV_RESPONSE): if isinstance(item, dict): ent = item else: try: ent = json.loads(item) except Exception as err: try: ent = parse_qs(item) except: continue else: try: res.append(ent['id_token'][0]) except KeyError: pass else: continue try: res.append(ent['id_token']) except KeyError: pass return res
def _get_post(self, environ): """ Get the posted information :param environ: A dictionary with environment variables """ body = '' try: length = int(environ.get('CONTENT_LENGTH', '0')) except ValueError: length = 0 if length != 0: body = environ['wsgi.input'].read(length) # get the POST variables environ[ 's2repoze.body'] = body # store the request body for later # use by pysaml2 environ['wsgi.input'] = StringIO(body) # restore the request body # as a stream so that everything seems untouched post = parse_qs(body) # parse the POST fields into a dict logger.debug('identify post: %s', post) return post
def webfinger(environ, events): query = parse_qs(environ["QUERY_STRING"]) _op = environ["oic.op"] try: if query["rel"] != [OIC_ISSUER]: events.store( EV_CONDITION, State('webfinger_parameters', ERROR, message='parameter rel wrong value: {}'.format( query['rel']))) return BadRequest('Parameter value error') else: resource = query["resource"][0] except KeyError as err: events.store( EV_CONDITION, State('webfinger_parameters', ERROR, message='parameter {} missing'.format(err))) resp = BadRequest("Missing parameter in request") else: wf = WebFinger() resp = Response(wf.response(subject=resource, base=_op.baseurl)) return resp
def do_verify(environ, start_response, _): query = parse_qs(get_post(environ)) logger.debug("do_verify: %s", query) try: _ok, user = verify_username_and_password(query) except KeyError: _ok = False user = None if not _ok: resp = Unauthorized("Unknown user or wrong password") else: uid = rndstr(24) IDP.cache.uid2user[uid] = user IDP.cache.user2uid[user] = uid logger.debug("Register %s under '%s'", user, uid) kaka = set_cookie("idpauthn", "/", uid, query["authn_reference"][0]) lox = "%s?id=%s&key=%s" % (query["redirect_uri"][0], uid, query["key"][0]) logger.debug("Redirect => %s", lox) resp = Redirect(lox, headers=[kaka], content="text/html") return resp(environ, start_response)
def unpack_post(self): _dict = parse_qs(get_post(self.environ)) logger.debug("unpack_post:: %s", _dict) try: return dict([(k, v[0]) for k, v in _dict.items()]) except Exception: return None
def test_verify_unauthorized(self, srv): form = create_return_form_env("user", "secret", "QUERY") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, state = authn.verify(parse_qs(form)) assert isinstance(response, Unauthorized)
def basic_entity_configuration(self, io): q = parse_qs(io.environ.get('QUERY_STRING')) # construct profile profile = to_profile(q) _ent_conf = create_model(profile, ent_info_path=self.ent_info) state = {} if not do_discovery(profile): _ent_conf['client']['provider_info']['issuer'] = q['iss'][0] if not do_registration(profile): # need to create a redirect_uri, means I need to register a port _port = self.assigned_ports.register_port(q['iss'][0], q['tag'][0]) _ent_conf['client']['registration_response'][ 'redirect_uris'] = '{}:{}/authz_cb'.format( self.test_tool_base[:-1], _port) _ent_conf['tool']['tag'] = q['tag'][0] _ent_conf['tool']['issuer'] = q['iss'][0] _ent_conf['tool']['profile'] = profile _qiss = quote_plus(q['iss'][0]) _qtag = quote_plus(q['tag'][0]) io.rest.write(_qiss, _qtag, _ent_conf) return '{}form/update/{}/{}'.format(self.baseurl, _qiss, _qtag)
def _generate_code_for_jdbc(self, code): parsed = urlparse(self.metadata['url']) qs_parsed = parse_qs(parsed.query) driver = self.SUPPORTED_DRIVERS.get(parsed.scheme) if driver is None: raise ValueError( _('Database {} not supported').format(parsed.scheme)) if not self.metadata.get('command'): raise ValueError( _('No command nor table specified for data source.')) code_jdbc = dedent(""" query = '{table}' if query.strip()[:6].upper() == 'SELECT': # Add parentheses required by Spark query = '(' + query + ') AS tb' {out} = spark_session.read.format('jdbc').load( driver='{driver}', url='jdbc:{scheme}://{server}:{port}{db}', user='******', password='******', dbtable=query) """.format(scheme=parsed.scheme, server=parsed.hostname, db=parsed.path, port=parsed.port, driver=driver, user=qs_parsed.get('user', [''])[0], password=qs_parsed.get('password', [''])[0], table=self.metadata.get('command'), out=self.output)) code.append(code_jdbc)
def _parse_signature(self, request): if "Http-Signature" in request["headers"]: return request["headers"]["Http-Signature"] elif "body" in request: return parse_qs(request["body"])["http_signature"][0] return None
def create_redirect(self, query): """ Performs the redirect to the CAS server. :rtype : Response :param query: All query parameters to be added to the return_to URL after successful authentication. :return: A redirect response to the CAS server. """ try: req = parse_qs(query) acr = req['acr_values'][0] except KeyError: acr = None nonce = uuid.uuid4().get_urn() service_url = urlencode( {self.CONST_SERVICE: self.get_service_url(nonce, acr)}) cas_url = self.cas_server + self.CONST_CASLOGIN + service_url cookie = self.create_cookie( '{"' + self.CONST_NONCE + '": "' + base64.b64encode( nonce) + '", "' + self.CONST_QUERY + '": "' + base64.b64encode(query) + '"}', self.CONST_CAS_COOKIE, self.CONST_CAS_COOKIE) return SeeOther(cas_url, headers=[cookie])
def test_verify(self, srv): form = create_return_form_env("user", "hemligt", "query=foo") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") with LogCapture(level=logging.DEBUG) as logcap: response, success = authn.verify(parse_qs(form)) assert query_string_compare( response.message.split("?")[1], "query=foo&upm_answer=true") headers = dict(response.headers) assert headers["Set-Cookie"].startswith('xyzxyz=') expected = { u'query': [u'query=foo'], u'login': ['user'], u'password': '******' } # We have to use eval() here to avoid intermittent # failures from dict ordering assert eval(logcap.records[0].msg[7:-1]) == expected expected = { u'query': [u'query=foo'], u'login': ['user'], u'password': '******' } assert eval(logcap.records[1].msg[5:]) == expected assert logcap.records[2].msg == 'Password verification succeeded.' expected = {u'query': [u'foo'], 'upm_answer': 'true'} assert eval(logcap.records[3].msg[8:]) == expected
def parse_query(self, query): """ Parse a GET query string and convert it into a POST-style text block. """ qry = parse_qs(query) sql_qry = dict(DEFAULT_PARAMS) required = list(REQUIRED_PARAMS) for k, v in qry.items(): k = PARAM_SUBSTITUTIONS.get(k, k) if k not in sql_qry: raise QueryError("Unrecognized query parameter: '%s'" % k) elif len(v) > 1: raise QueryError("Multiple '%s' parameters not allowed." % k) else: if k in required: required.remove(k) sql_qry[k] = v[0] if len(required) > 0 and self.endpoint != 'summary': raise QueryError( "Missing parameter%s: %s" % ("" if len(required) == 1 else "s", ", ".join(required))) # Build a string for the matching request as a POST body bulk = [] for k in BULK_PARAM_KEYS: bulk.append("%s=%s" % (k, sql_qry[k])) bulk.append(" ".join( (sql_qry['network'], sql_qry['station'], sql_qry['location'], sql_qry['channel'], sql_qry['starttime'], sql_qry['endtime']))) return "\n".join(bulk)
def verify(self, request, **kwargs): """ Verifies that the given totp was correct :param request: Either the query part of a URL a urlencoded body of a HTTP message or a parse such. :param kwargs: Catch whatever else is sent. :return: redirect back to where ever the base applications wants the user after authentication. """ if isinstance(request, six.string_types): _dict = parse_qs(request) elif isinstance(request, dict): _dict = request else: raise ValueError("Wrong type of input") # verify totp try: # Do verification totp_generator = pyotp.TOTP(self.get_totp_secret_key(_dict["username"][0])) assert (True == totp_generator.verify(_dict["totp"][0])) except (AssertionError, KeyError): resp = Unauthorized("Wrong TOTP") ##resp = Unauthorized("Unknown user or wrong password") kwargs["request"] = request kwargs["form_action"] = kwargs["url"] argv = self.templ_arg_func(0, **kwargs) argv['wrong_value'] = 1 argv['form_action'] = kwargs["baseurl"] + "/totp_login" argv['username'] = _dict['username'][0] argv['acr'] = argv['form_action'] argv['title'] = 'TOTP verification' self.nerror = self.nerror + 1 if (self.nerror>=3): self.nerror = 0 argv['wrong_value'] = 4 mte = self.template_lookup.get_template('totp_form.mako') resp.message = mte.render(**argv).decode("utf-8") return resp, False else: # If I remove this header, authentication enters in a infinite loop. headers = [self.create_cookie(_dict["username"][0], "upm")] try: _qp = _dict["query"][0] except KeyError: _qp = self.get_multi_auth_cookie(kwargs['cookie']) try: return_to = self.generate_return_url(kwargs["return_to"], _qp) except KeyError: try: return_to = self.generate_return_url(self.return_to, _qp, kwargs["path"]) except KeyError: return_to = self.generate_return_url(self.return_to, _qp) return SeeOther(return_to, headers=headers), True
def client_info_endpoint(self, method="GET", **kwargs): """ Operations on this endpoint are switched through the use of different HTTP methods :param method: HTTP method used for the request :param kwargs: keyword arguments :return: A Response instance """ _query = parse_qs(kwargs['query']) try: _id = _query["client_id"][0] except KeyError: return BadRequest("Missing query component") try: assert _id in self.cdb except AssertionError: return Unauthorized() # authenticated client try: _ = self.verify_client(kwargs['environ'], kwargs['request'], "bearer_header", client_id=_id) except (AuthnFailure, UnknownAssertionType): return Unauthorized() if method == "GET": return self.client_info(_id) elif method == "PUT": try: _request = ClientUpdateRequest().from_json(kwargs['request']) except ValueError as err: return BadRequest(str(err)) try: _request.verify() except InvalidRedirectUri as err: msg = ClientRegistrationError(error="invalid_redirect_uri", error_description="%s" % err) return BadRequest(msg.to_json(), content="application/json") except (MissingPage, VerificationError) as err: msg = ClientRegistrationError(error="invalid_client_metadata", error_description="%s" % err) return BadRequest(msg.to_json(), content="application/json") try: self.client_info_update(_id, _request) return self.client_info(_id) except ModificationForbidden: return Forbidden() elif method == "DELETE": try: del self.cdb[_id] except KeyError: return Unauthorized() else: return NoContent()
def handle(self, environ, tester, service, binding): _sh = tester.sh qs = get_post(environ).decode('utf8') resp = dict([(k, v[0]) for k, v in parse_qs(qs).items()]) filename = self.kwargs['profile_handler'](_sh).log_path( _sh['conv'].test_id) return tester.do_next(resp, filename)
def test_authenticated_token(self): _state, location = self.cons.begin("openid", response_type="token", path="http://localhost:8087") resp = self.provider.authorization_endpoint( request=urlparse(location).query) parsed = parse_qs(urlparse(resp.message).fragment) assert parsed["token_type"][0] == "Bearer" assert "access_token" in parsed
def from_urlencoded(self, urlencoded, **kwargs): """ from a string of the application/x-www-form-urlencoded format creates a class instance :param urlencoded: The string :return: An instance of the cls class """ # parse_qs returns a dictionary with keys and values. The values are # always lists even if there is only one value in the list. # keys only appears once. if isinstance(urlencoded, six.string_types): pass elif isinstance(urlencoded, list): urlencoded = urlencoded[0] _spec = self.c_param for key, val in parse_qs(urlencoded).items(): try: (typ, _, _, _deser, null_allowed) = _spec[key] except KeyError: try: _key, lang = key.split("#") (typ, _, _, _deser, null_allowed) = _spec[_key] except (ValueError, KeyError): try: (typ, _, _, _deser, null_allowed) = _spec['*'] except KeyError: if len(val) == 1: val = val[0] self._dict[key] = val continue if isinstance(typ, list): if _deser: self._dict[key] = _deser(val[0], "urlencoded") else: self._dict[key] = val else: # must be single value if len(val) == 1: if _deser: self._dict[key] = _deser(val[0], "urlencoded") elif isinstance(val[0], typ): self._dict[key] = val[0] else: try: self._dict[key] = typ(val[0]) except KeyError: raise ParameterError(key) else: raise TooManyValues('{}'.format(key)) return self
def verify(self, request, **kwargs): """ Verifies that the given username and password was correct :param request: Either the query part of a URL a urlencoded body of a HTTP message or a parse such. :param kwargs: Catch whatever else is sent. :return: redirect back to where ever the base applications wants the user after authentication. """ logger.debug("verify(%s)" % sanitize(request)) if isinstance(request, six.string_types): _dict = compact(parse_qs(request)) elif isinstance(request, dict): _dict = request else: raise ValueError("Wrong type of input") logger.debug("dict: %s" % sanitize(_dict)) # verify username and password try: self._verify(_dict["password"], _dict["login"]) # dict origin except TypeError: try: self._verify(_dict["password"][0], _dict["login"][0]) except (AssertionError, KeyError) as err: logger.debug("Password verification failed: {}".format(err)) resp = Unauthorized("Unknown user or wrong password") return resp, False else: try: _qp = _dict["query"] except KeyError: _qp = self.get_multi_auth_cookie(kwargs['cookie']) except (AssertionError, KeyError) as err: logger.debug("Password verification failed: {}".format(err)) resp = Unauthorized("Unknown user or wrong password") return resp, False else: try: _qp = _dict["query"] except KeyError: _qp = self.get_multi_auth_cookie(kwargs['cookie']) logger.debug("Password verification succeeded.") # if "cookie" not in kwargs or self.srv.cookie_name not in kwargs["cookie"]: headers = [self.create_cookie(_dict["login"], "upm")] try: return_to = self.generate_return_url(kwargs["return_to"], _qp) except KeyError: try: return_to = self.generate_return_url(self.return_to, _qp, kwargs["path"]) except KeyError: return_to = self.generate_return_url(self.return_to, _qp) return SeeOther(return_to, headers=headers), True
def application(environ, start_response): session = environ['beaker.session'] path = environ.get('PATH_INFO', '').lstrip('/') if path == "robots.txt": return static(environ, start_response, "static/robots.txt") if path.startswith("static/"): return static(environ, start_response, path) if path == "logout": session.invalidate() resp = SeeOther("static/log_out_message.html") return resp(environ, start_response) if path == "as": session["callback"] = True request = parse_qs(get_or_post(environ)) _cli = CONSUMER[unquote(request["authzsrv"][0])] session["client"] = _cli resp = SeeOther(_cli.begin(RP_CONF.BASE, path)) return resp(environ, start_response) if path == "rp": session["callback"] = True request = parse_qs(get_or_post(environ)) _cli = CONSUMER[unquote(request["iss"][0])] session["client"] = _cli resp = SeeOther(_cli.begin(RP_CONF.BASE, path)) return resp(environ, start_response) if path == "authz_cb": _cli = session["client"] request = get_or_post(environ) aresp = _cli.handle_authorization_response(request) rargs = {"code": aresp["code"]} atresp = _cli.do_access_token_request(request_args=rargs) #extra_args=None, http_args=None,) # Access token should be stored somewhere for later usage Token[atresp["state"]] = atresp resp = Response("Got access token: %s" % atresp["access_token"]) return resp(environ, start_response) return as_choice(environ, start_response)
def _verify_redirect_uri(self, areq): """ MUST NOT contain a fragment MAY contain query component :return: An error response if the redirect URI is faulty otherwise None """ try: _redirect_uri = unquote(areq["redirect_uri"]) part = urlparse(_redirect_uri) if part.fragment: raise URIError("Contains fragment") (_base, _query) = splitquery(_redirect_uri) if _query: _query = parse_qs(_query) match = False for regbase, rquery in self.cdb[str(areq["client_id"])][ "redirect_uris"]: if _base == regbase or _redirect_uri.startswith(regbase): # every registered query component must exist in the # redirect_uri if rquery: for key, vals in rquery.items(): assert key in _query for val in vals: assert val in _query[key] # and vice versa, every query component in the redirect_uri # must be registered if _query: if rquery is None: raise ValueError for key, vals in _query.items(): assert key in rquery for val in vals: assert val in rquery[key] match = True break if not match: raise RedirectURIError("Doesn't match any registered uris") # ignore query components that are not registered return None except Exception as err: logger.error("Faulty redirect_uri: %s" % areq["redirect_uri"]) try: _cinfo = self.cdb[str(areq["client_id"])] except KeyError: logger.info("Unknown client: %s" % areq["client_id"]) raise UnknownClient(areq["client_id"]) else: logger.info("Registered redirect_uris: %s" % _cinfo) raise RedirectURIError( "Faulty redirect_uri: %s" % areq["redirect_uri"])
def test_authenticated_as(self, srv): form = create_return_form_env("user", "hemligt", "QUERY") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, success = authn.verify(compact(parse_qs(form))) headers = dict(response.headers) user, timestamp = authn.authenticated_as(headers["Set-Cookie"]) assert user == {"uid": "user"}
def test_authenticated_as(self, srv): form = create_return_form_env("user", "hemligt", "QUERY") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, success = authn.verify(parse_qs(form)) headers = dict(response.headers) user, timestamp = authn.authenticated_as(headers["Set-Cookie"]) assert user == {"uid": "user"}
def test_authenticated_none(self): _state, location = self.cons.begin("openid", response_type="none", path="http://localhost:8087") resp = self.provider.authorization_endpoint( request=location.split("?")[1]) parsed = urlparse(resp.message) assert "{}://{}{}".format(parsed.scheme, parsed.netloc, parsed.path) == "http://localhost:8087/authz" assert "state" in parse_qs(parsed.query)
def test_verify(self, srv): form = create_return_form_env("user", "hemligt", "query=foo") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, success = authn.verify(parse_qs(form)) assert query_string_compare(response.message.split("?")[1], "query=foo&upm_answer=true") headers = dict(response.headers) assert headers["Set-Cookie"].startswith('xyzxyz=')
def verify_outcome(msg, prefix, lista): """ Number of permutations are dependent on number of claims :param prefix: prefix string :param lista: list of claims=value :return: list of possible strings """ assert msg.startswith(prefix) qsl = ['{}={}'.format(k, v[0]) for k, v in parse_qs(msg[len(prefix):]).items()] return set(qsl) == set(lista)
def test_verify(self, srv): form = create_return_form_env("user", "hemligt", "query=foo") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, success = authn.verify(parse_qs(form)) assert query_string_compare( response.message.split("?")[1], "query=foo&upm_answer=true") headers = dict(response.headers) assert headers["Set-Cookie"].startswith('xyzxyz=')
def _parse_access_token(self, request, **kwargs): if "access_token" in request["query"]: return request["query"]["access_token"] elif "access_token" in request["body"]: return parse_qs(request["body"])["access_token"][0] elif "Authorization" in request["headers"] and request["headers"][ "Authorization"]: auth_header = request["headers"]["Authorization"] if auth_header.startswith("pop "): return auth_header[len("pop "):] return None
def test_not_authenticated(self, srv): form = create_return_form_env("user", "hemligt", "QUERY") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, state = authn.verify(parse_qs(form)) headers = dict(response.headers) kaka = headers["Set-Cookie"] kaka = kaka.replace("1", "x") assert authn.authenticated_as(kaka) == (None, 0)
def pack_redirect_uri(redirect_uris): ruri = [] for uri in redirect_uris: if urlparse(uri).fragment: print("Faulty redirect uri, contains fragment", file=sys.stderr) base, query = splitquery(uri) if query: ruri.append([base, parse_qs(query)]) else: ruri.append([base, query]) return ruri
def webfinger(self, environ, start_response): query = parse_qs(environ["QUERY_STRING"]) try: assert query["rel"] == [OIC_ISSUER] resource = query["resource"][0] except KeyError: resp = BadRequest("Missing parameter in request") else: wf = WebFinger() resp = Response(wf.response(subject=resource, base=self.oas.baseurl)) return resp(environ, start_response)
def test_not_authenticated(self, srv): form = create_return_form_env("user", "hemligt", "QUERY") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, state = authn.verify(compact(parse_qs(form))) headers = dict(response.headers) kaka = headers["Set-Cookie"] kaka = kaka.replace("1", "x") assert authn.authenticated_as(kaka) == (None, 0)
def webfinger(self, environ, start_response): query = parse_qs(environ["QUERY_STRING"]) try: assert query["rel"] == [OIC_ISSUER] resource = query["resource"][0] except KeyError: resp = BadRequest("Missing parameter in request") else: wf = WebFinger() resp = Response( wf.response(subject=resource, base=self.oas.baseurl)) return resp(environ, start_response)
def sign_http_args(method, url, headers, body=''): p = urlparse(url) kwargs = {'path': p.path, 'host': p.netloc, 'headers': headers, 'method': method} if body: kwargs['body'] = body query_params = parse_qs(p.query) kwargs['query_params'] = query_params return kwargs
def test_authorization_endpoint_id_token(self): bib = { "scope": ["openid"], "state": "id-6da9ca0cc23959f5f33e8becd9b08cae", "redirect_uri": "http://localhost:8087/authz", "response_type": ["code", "id_token"], "client_id": "a1b2c3", "nonce": "Nonce", "prompt": ["none"] } req = AuthorizationRequest(**bib) areq = AuthorizationRequest(response_type="code", client_id="client_1", redirect_uri="http://example.com/authz", scope=["openid"], state="state000") sdb = self.provider.sdb ae = AuthnEvent("userX", "salt") sid = sdb.create_authz_session(ae, areq) sdb.do_sub(sid, "client_salt") _info = sdb[sid] # All this is jut removed when the id_token is constructed # The proper information comes from the session information _user_info = IdToken(iss="https://foo.example.om", sub="foo", aud=bib["client_id"], exp=epoch_in_a_while(minutes=10), acr="2", nonce=bib["nonce"]) idt = self.provider.id_token_as_signed_jwt(_info, access_token="access_token", user_info=_user_info) req["id_token"] = idt query_string = req.to_urlencoded() # client_id not in id_token["aud"] so login required resp = self.provider.authorization_endpoint(request=query_string, cookie="FAIL") parsed_resp = parse_qs(urlparse(resp.message).fragment) assert parsed_resp["error"][0] == "login_required" req["client_id"] = "client_1" query_string = req.to_urlencoded() # client_id is in id_token["aud"] so no login required resp = self.provider.authorization_endpoint(request=query_string, cookie="FAIL") assert resp.message.startswith("http://localhost:8087/authz")
def create_return_url(base, query, **kwargs): """ Add a query string plus extra parameters to a base URL which may contain a query part already. :param base: redirect_uri may contain a query part, no fragment allowed. :param query: Old query part as a string :param kwargs: extra query parameters :return: """ part = urlsplit(base) if part.fragment: raise ValueError("Base URL contained parts it shouldn't") for key, values in parse_qs(query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values if part.query: for key, values in parse_qs(part.query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values _pre = base.split("?")[0] else: _pre = base logger.debug("kwargs: %s" % kwargs) if kwargs: return "%s?%s" % (_pre, url_encode_params(kwargs)) else: return _pre
def create_return_url(base, query, **kwargs): """ Add a query string plus extra parameters to a base URL which may contain a query part already. :param base: redirect_uri may contain a query part, no fragment allowed. :param query: Old query part as a string :param kwargs: extra query parameters :return: """ part = urlsplit(base) if part.fragment: raise ValueError("Base URL contained parts it shouldn't") for key, values in parse_qs(query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values if part.query: for key, values in parse_qs(part.query).items(): if key in kwargs: if isinstance(kwargs[key], six.string_types): kwargs[key] = [kwargs[key]] kwargs[key].extend(values) else: kwargs[key] = values _pre = base.split("?")[0] else: _pre = base logger.debug("kwargs: %s" % sanitize(kwargs)) if kwargs: return "%s?%s" % (_pre, url_encode_params(kwargs)) else: return _pre
def verify(self, request, cookie, **kwargs): """ Verifies if the authentication was successful. :rtype : Response :param request: Contains the request parameters. :param cookie: Cookies sent with the request. :param kwargs: Any other parameters. :return: If the authentication was successful: a redirect to the return_to url. Otherwise a unauthorized response. :raise: ValueError """ logger.debug("verify(%s)" % request) if isinstance(request, six.string_types): _dict = parse_qs(request) elif isinstance(request, dict): _dict = request else: raise ValueError("Wrong type of input") try: cas_cookie, _ts, _typ = self.getCookieValue(cookie, self.CONST_CAS_COOKIE) data = json.loads(cas_cookie) nonce = base64.b64decode(data[self.CONST_NONCE]) if nonce != _dict[self.CONST_NONCE][0]: logger.warning( 'Someone tried to login without a correct nonce!') return Unauthorized("You are not authorized!") acr = None try: acr = _dict["acr_values"][0] except KeyError: pass uid = self.handle_callback(_dict[self.CONST_TICKET], self.get_service_url(nonce, acr)) if uid is None or uid == "": logger.info('Someone tried to login, but was denied by CAS!') return Unauthorized("You are not authorized!") cookie = self.create_cookie(uid, "casm") return_to = self.generate_return_url(self.return_to, uid) if '?' in return_to: return_to += "&" else: return_to += "?" return_to += base64.b64decode(data[self.CONST_QUERY]) return SeeOther(return_to, headers=[cookie]) except: logger.fatal('Metod verify in user_cas.py had a fatal exception.', exc_info=True) return Unauthorized("You are not authorized!")
def urlhandler_acs_post(self, sh, environ, local_webenv, path, start_response, tester, webio): formdata = get_post(environ).decode('utf8') resp = dict([(k, v[0]) for k, v in parse_qs(formdata).items()]) try: test_id = sh['conv'].test_id except KeyError as err: test_id = None if not test_id: """ Do we have been initialized already, or is the user just on the wrong page ? """ if not resp: return tester.display_test_list() """ In other words: we've been contacted by robobrowser and are in a different environment now, than the code expects us to be. .... Hopefully, trickery and recreating of the environment will lead mostly to more intended effects than unintended ones. This is unfinished business: You can add other bindings here, to expand what RB can be used to test. """ try: txt = resp['SAMLResponse'] xmlstr = Entity.unravel(txt, BINDING_HTTP_POST) except Exception as e: msg = 'Decoding not supported in the SP' raise Exception(msg) rsp = samlp.any_response_from_string(xmlstr) original_request_id = rsp.in_response_to requester_session = self.session_store.get_session_by_conv_id(original_request_id) # recreating the environment. lets hope it is somewhat reentrant resistant sh = requester_session webio = WebIO(session=sh, **local_webenv) webio.environ = environ webio.start_response = start_response tester = Tester(webio, sh, **local_webenv) profile_handler = local_webenv['profile_handler'] _sh = profile_handler(sh) # filename = self.webenv['profile_handler'](sh).log_path(test_id) # _sh.session.update({'conv': 'foozbar'}) logfilename = _sh.log_path(test_id) content = do_next(tester, resp, sh, webio, logfilename, path) return content
def authorization_endpoint(self, request="", cookie=None, **kwargs): _req = parse_qs(request) _response = provider.Provider.authorization_endpoint(self, request, cookie, **kwargs) # This is just for logging purposes try: _resp = self.server.http_request(_req["request_uri"][0]) except KeyError: pass else: if _resp.status_code == 200: self.events.store("Request_uri content", _resp.text) return _response
def test_authenticated_token(self): _session_db = {} cons = Consumer(_session_db, client_config=CLIENT_CONFIG, server_info=SERVER_INFO, **CONSUMER_CONFIG) sid, location = cons.begin("http://localhost:8087", "http://localhost:8088/authorization", "token") QUERY_STRING = location.split("?")[1] resp = self.provider.authorization_endpoint(QUERY_STRING) auth_resp = parse_qs(urlparse(resp.message).fragment) assert "access_token" in auth_resp assert auth_resp["token_type"][0] == "Bearer"
def test_authorization_endpoint(self): bib = {"scope": ["openid"], "state": "id-6da9ca0cc23959f5f33e8becd9b08cae", "redirect_uri": "http://localhost:8087/authz", "response_type": ["code"], "client_id": "a1b2c3", "nonce": "Nonce"} arq = AuthorizationRequest(**bib) resp = self.provider.authorization_endpoint(request=arq.to_urlencoded()) parsed = parse_qs(urlparse(resp.message).query) assert parsed["scope"] == ["openid"] assert parsed["state"][0] == "id-6da9ca0cc23959f5f33e8becd9b08cae" assert "code" in parsed