Esempio n. 1
0
def test_grant_add_code():
    ar = AuthorizationResponse(code="code", state="state")

    grant = Grant()
    grant.add_code(ar)
    assert grant
    assert grant.code == "code"
Esempio n. 2
0
def test_grant_add_code():
    ar = AuthorizationResponse(code="code", state="state")

    grant = Grant()
    grant.add_code(ar)
    assert grant
    assert grant.code == "code"
Esempio n. 3
0
def test_bearer_body():
    client = Client("A")
    client.client_secret = "boarding pass"

    request_args = {"access_token": "Sesame"}

    cis = ResourceRequest()
    http_args = BearerBody(client).construct(cis, request_args)
    assert cis["access_token"] == "Sesame"
    print http_args
    assert http_args is None

    # ----------
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example",
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              scope=["inner", "outer"])

    grant.add_token(atr)
    client.grant["state"] = grant

    cis = ResourceRequest()
    http_args = BearerBody(client).construct(cis, {}, state="state",
                                             scope="inner")
    assert cis["access_token"] == "2YotnFZFEjr1zCsicMWpAA"
    print http_args
    assert http_args is None
Esempio n. 4
0
    def test_get_grant(self):
        resp = AuthorizationResponse(code="code", state="state")
        grant = Grant()
        grant.add_code(resp)

        self.client.grant["state"] = grant
        assert self.client.grant_from_state("state").code == "code"
Esempio n. 5
0
def test_grant():
    grant = Grant()
    assert grant
    assert grant.exp_in == 600

    grant = Grant(60)
    assert grant.exp_in == 60
Esempio n. 6
0
    def test_get_grant(self):
        resp = AuthorizationResponse(code="code", state="state")
        grant = Grant()
        grant.add_code(resp)

        self.client.grant["state"] = grant
        assert self.client.grant_from_state("state").code == "code"
Esempio n. 7
0
    def test_construct_access_token_req_expired_grant(self):
        resp = AuthorizationResponse(code="code", state="state")
        grant = Grant(-10)  # expired grant
        grant.add_code(resp)

        client = Client()
        client.grant["openid"] = grant
        with pytest.raises(GrantExpired):
            client.construct_AccessTokenRequest(state="openid")
Esempio n. 8
0
    def test_construct_access_token_req_expired_grant(self):
        resp = AuthorizationResponse(code="code", state="state")
        grant = Grant(-10)  # expired grant
        grant.add_code(resp)

        client = Client()
        client.grant["openid"] = grant
        with pytest.raises(GrantExpired):
            client.construct_AccessTokenRequest(state="openid")
Esempio n. 9
0
def test_grant_add_token():
    grant = Grant()
    grant.update(ACC_TOK_RESP)

    assert len(grant.tokens) == 1
    token = grant.tokens[0]

    assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
    assert token.token_type == "example"
    assert token.refresh_token == "tGzv3JOkF0XG5Qx2TlKWIA"
Esempio n. 10
0
def test_grant_add_token():
    grant = Grant()
    grant.update(ACC_TOK_RESP)

    assert len(grant.tokens) == 1
    token = grant.tokens[0]

    assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
    assert token.token_type == "example"
    assert token.refresh_token == "tGzv3JOkF0XG5Qx2TlKWIA"
Esempio n. 11
0
    def test_construct_access_token_req_override(self):
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.utc_time_sans_frac() + 30
        self.client.grant = {"xyz": grant}

        atr = self.client.construct_AccessTokenRequest(state="xyz")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == self.redirect_uri
Esempio n. 12
0
    def test_construct_access_token_req_override(self):
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.utc_time_sans_frac() + 30
        self.client.grant = {"xyz": grant}

        atr = self.client.construct_AccessTokenRequest(state="xyz")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == self.redirect_uri
Esempio n. 13
0
def test_client_get_grant():
    cli = Client()

    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    cli.grant["state"] = grant

    gr1 = cli.grant_from_state("state")

    assert gr1.code == "code"
Esempio n. 14
0
def test_get_access_token_request():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant(1)
    grant.add_code(resp)

    client = Client()
    client.grant["openid"] = grant
    time.sleep(2)
    try:
        client.construct_AccessTokenRequest(state="openid")
    except Exception, err:
        assert err.__class__.__name__ == "GrantExpired"
Esempio n. 15
0
    def test_construct_access_token_req_override(self):
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.utc_time_sans_frac() + 30
        self.client.grant = {"xyz": grant}

        atr = self.client.construct_AccessTokenRequest(state="xyz")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == self.redirect_uri
        assert atr['state_hash'] == 'Ngi8oeROpsTSaOttsCJgJpiSwLQrhrvx53pvoWw8koI='
Esempio n. 16
0
def test_get_access_token_request():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant(1)
    grant.add_code(resp)

    client = Client()
    client.grant["openid"] = grant
    time.sleep(2)
    try:
        client.construct_AccessTokenRequest(state="openid")
    except Exception, err:
        assert err.__class__.__name__ == "GrantExpired"
Esempio n. 17
0
def test_client_get_grant():
    cli = Client()

    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    cli.grant["state"] = grant

    gr1 = cli.grant_from_state("state")

    assert gr1.code == "code"
Esempio n. 18
0
    def test_construct_access_token_req(self):
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.utc_time_sans_frac() + 30
        self.client.grant = {"stat": grant}

        # scope is default=""
        atr = self.client.construct_AccessTokenRequest(state="stat")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == self.redirect_uri
        assert atr['state_hash'] == 'QEYNqMiCzceRg2-6dgCYcPlgoVEod5jx34r16WM5j4Q='
Esempio n. 19
0
    def test_get_access_token_request_override(self):
        self.client.reset()
        self.client.redirect_uris = ["http://client.example.com/authz"]
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.time_sans_frac() + 30
        self.client.grant = {"xyz": grant}

        atr = self.client.construct_AccessTokenRequest(state="xyz")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == "http://client.example.com/authz"
Esempio n. 20
0
    def test_get_access_token_request_1(self):
        self.client.reset()
        self.client.redirect_uris = ["http://client.example.com/authz"]
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.utc_time_sans_frac() + 30
        self.client.grant = {"stat": grant}

        # scope is default=""
        atr = self.client.construct_AccessTokenRequest(state="stat")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == "http://client.example.com/authz"
Esempio n. 21
0
def test_grant_resp():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    assert grant.code == "code"
    assert grant.grant_expiration_time != 0

    grant = Grant(1)
    grant.add_code(resp)
    time.sleep(2)

    assert grant.is_valid() is False

    grant = Grant.from_code(resp)
    assert grant.code == "code"
    assert grant.grant_expiration_time != 0
Esempio n. 22
0
def test_grant_access_token_1():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example",
                              expires_in=1,
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              xscope=["inner", "outer"])

    token = Token(atr)
    grant.tokens.append(token)

    print grant.keys()
    assert _eq(grant.keys(), [
        'tokens', 'id_token', 'code', 'exp_in', 'seed', 'grant_expiration_time'
    ])
    print token.keys()
    assert _eq(token.keys(), [
        'token_expiration_time', 'access_token', 'expires_in',
        'example_parameter', 'token_type', 'xscope', 'refresh_token', 'scope',
        'replaced'
    ])

    assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
    assert token.token_type == "example"
    assert token.refresh_token == "tGzv3JOkF0XG5Qx2TlKWIA"
    assert token.example_parameter == "example_value"
    assert token.xscope == ["inner", "outer"]
    assert token.token_expiration_time != 0

    time.sleep(2)
    assert token.is_valid() is False
Esempio n. 23
0
def test_grant_access_token_2():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example",
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              scope=["inner", "outer"])

    grant.add_token(atr)

    assert len(grant.tokens) == 1
    time.sleep(2)
    token = grant.tokens[0]
    assert token.is_valid() is True

    assert "%s" % grant != ""
Esempio n. 24
0
def test_bearer_body():
    client = Client("A")
    client.client_secret = "boarding pass"

    request_args = {"access_token": "Sesame"}

    cis = ResourceRequest()
    http_args = BearerBody(client).construct(cis, request_args)
    assert cis["access_token"] == "Sesame"
    print http_args
    assert http_args is None

    # ----------
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example",
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              scope=["inner", "outer"])

    grant.add_token(atr)
    client.grant["state"] = grant

    cis = ResourceRequest()
    http_args = BearerBody(client).construct(cis, {},
                                             state="state",
                                             scope="inner")
    assert cis["access_token"] == "2YotnFZFEjr1zCsicMWpAA"
    print http_args
    assert http_args is None
Esempio n. 25
0
def test_grant_access_token_1():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example", expires_in=1,
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              xscope=["inner", "outer"])

    token = Token(atr)
    grant.tokens.append(token)

    print grant.keys()
    assert _eq(grant.keys(), ['tokens', 'id_token', 'code', 'exp_in', 'seed',
                              'grant_expiration_time'])
    print token.keys()
    assert _eq(token.keys(), ['token_expiration_time', 'access_token',
                              'expires_in', 'example_parameter', 'token_type',
                              'xscope', 'refresh_token', 'scope',
                              'replaced'])

    assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
    assert token.token_type == "example"
    assert token.refresh_token == "tGzv3JOkF0XG5Qx2TlKWIA"
    assert token.example_parameter == "example_value"
    assert token.xscope == ["inner", "outer"]
    assert token.token_expiration_time != 0

    time.sleep(2)
    assert token.is_valid() is False
Esempio n. 26
0
    def test_get_access_token_refresh_with_refresh_token(self):
        self.client.grant["foo"] = Grant()
        _get = time_util.utc_time_sans_frac() + 60
        self.client.grant["foo"].grant_expiration_time = _get
        self.client.grant["foo"].code = "access_code"
        resp = AccessTokenResponse(refresh_token="refresh_with_me",
                                   access_token="access")
        token = Token(resp)
        self.client.grant["foo"].tokens.append(token)

        # Uses refresh_token from previous response
        atr = self.client.construct_RefreshAccessTokenRequest(token=token)

        assert atr["grant_type"] == "refresh_token"
        assert atr["refresh_token"] == "refresh_with_me"
Esempio n. 27
0
def test_grant_resp():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    assert grant.code == "code"
    assert grant.grant_expiration_time != 0

    grant = Grant(1)
    grant.add_code(resp)
    time.sleep(2)

    assert grant.is_valid() is False

    grant = Grant.from_code(resp)
    assert grant.code == "code"
    assert grant.grant_expiration_time != 0
Esempio n. 28
0
    def test_construct_TokenRevocationRequest(self):
        self.client.grant["foo"] = Grant()
        _get = time_util.utc_time_sans_frac() + 60
        self.client.grant["foo"].grant_expiration_time = _get
        self.client.grant["foo"].code = "access_code"
        resp = AccessTokenResponse(refresh_token="refresh_with_me",
                                   access_token="access")
        token = Token(resp)
        self.client.grant["foo"].tokens.append(token)

        state = "foo"
        query = "code=SplxlOBeZQQYbYS6WxSbIA&state={}".format(state)
        self.client.parse_response(AuthorizationResponse,
                                   info=query,
                                   sformat="urlencoded")

        req = self.client.construct_TokenRevocationRequest(state=state)
        assert _eq(req.keys(), ['token'])
        assert req["token"] == "access"
Esempio n. 29
0
    def begin(self, baseurl, request, response_type="", **kwargs):
        """ Begin the OAuth2 flow

        :param baseurl: The RPs base
        :param request: The Authorization query
        :param response_type: The response type the AS should use.
            Default 'code'.
        :return: A URL to which the user should be redirected
        """

        LOG_DEBUG("- begin -")

        # Store the request and the redirect uri used
        self.redirect_uris = ["%s%s" % (baseurl, self.authz_page)]
        self._request = request

        # Put myself in the dictionary of sessions, keyed on session-id
        if not self.seed:
            self.seed = rndstr()

        sid = stateID(request, self.seed)
        self.state = sid
        self.grant[sid] = Grant(seed=self.seed)
        self._backup(sid)
        self.sdb["seed:%s" % self.seed] = sid

        if not response_type:
            if self.response_type:
                response_type = self.response_type
            else:
                self.response_type = response_type = "code"

        location = self.request_info(AuthorizationRequest,
                                     method="GET",
                                     scope=self.scope,
                                     request_args={
                                         "state": sid,
                                         "response_type": response_type
                                     })[0]

        LOG_DEBUG("Redirecting to: %s" % (location, ))

        return location
Esempio n. 30
0
def test_grant_access_token_2():
    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example",
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              scope=["inner", "outer"])

    grant.add_token(atr)

    assert len(grant.tokens) == 1
    time.sleep(2)
    token = grant.tokens[0]
    assert token.is_valid() is True

    assert "%s" % grant != ""
Esempio n. 31
0
def test_grant_set_3():
    err = ErrorResponse(error="invalid_request")
    grant = Grant()
    grant.update(err)

    assert len(grant.tokens) == 0
Esempio n. 32
0
    def begin(self,
              scope="",
              response_type="",
              use_nonce=False,
              path="",
              **kwargs):
        """ Begin the OIDC flow

        :param scope: Defines which user info claims is wanted
        :param response_type: Controls the parameters returned in the
            response from the Authorization Endpoint
        :param use_nonce: If not implicit flow nonce is optional.
            This defines if it should be used anyway.
        :param path: The path part of the redirect URL
        :return: A 2-tuple, session identifier and URL to which the user
            should be redirected
        """
        _log_info = logger.info

        if self.debug:
            _log_info("- begin -")

        _page = self.config["authz_page"]
        if not path.endswith("/"):
            if _page.startswith("/"):
                self.redirect_uris = [path + _page]
            else:
                self.redirect_uris = ["%s/%s" % (path, _page)]
        else:
            if _page.startswith("/"):
                self.redirect_uris = [path + _page[1:]]
            else:
                self.redirect_uris = ["%s/%s" % (path, _page)]

        # Put myself in the dictionary of sessions, keyed on session-id
        if not self.seed:
            self.seed = rndstr()

        if not scope:
            scope = self.config["scope"]
        if not response_type:
            response_type = self.config["response_type"]

        sid = stateID(path, self.seed)
        self.grant[sid] = Grant(seed=self.seed)

        self._backup(sid)
        self.sdb["seed:%s" % self.seed] = sid

        args = {
            "client_id": self.client_id,
            "state": sid,
            "response_type": response_type,
            "scope": scope,
        }

        # nonce is REQUIRED in implicit flow,
        # OPTIONAL on code flow.
        if "token" in response_type or use_nonce:
            self.nonce = rndstr(12)
            args["nonce"] = self.nonce

        if "max_age" in self.config:
            args["max_age"] = self.config["max_age"]

        _claims = None
        if "user_info" in self.config:
            _claims = ClaimsRequest(userinfo=Claims(
                **self.config["user_info"]))
        if "id_token" in self.config:
            if _claims:
                _claims["id_token"] = Claims(**self.config["id_token"])
            else:
                _claims = ClaimsRequest(id_token=Claims(
                    **self.config["id_token"]))

        if _claims:
            args["claims"] = _claims

        if "request_method" in self.config:
            areq = self.construct_AuthorizationRequest(request_args=args,
                                                       extra_args=None,
                                                       request_param="request")

            if self.config["request_method"] == "file":
                id_request = areq["request"]
                del areq["request"]
                _filedir = self.config["temp_dir"]
                _webpath = self.config["temp_path"]
                _name = rndstr(10)
                filename = os.path.join(_filedir, _name)
                while os.path.exists(filename):
                    _name = rndstr(10)
                    filename = os.path.join(_filedir, _name)
                fid = open(filename, mode="w")
                fid.write(id_request)
                fid.close()
                _webname = "%s%s%s" % (path, _webpath, _name)
                areq["request_uri"] = _webname
                self.request_uri = _webname
                self._backup(sid)
        else:
            if "userinfo_claims" in args:  # can only be carried in an IDRequest
                raise PyoidcError("Need a request method")

            areq = self.construct_AuthorizationRequest(AuthorizationRequest,
                                                       request_args=args)

        location = areq.request(self.authorization_endpoint)

        if self.debug:
            _log_info("Redirecting to: %s" % location)

        return sid, location
Esempio n. 33
0
def test_grant_set_3():
    err = ErrorResponse(error="invalid_request")
    grant = Grant()
    grant.update(err)

    assert len(grant.tokens) == 0
Esempio n. 34
0
def test_grant_init():
    grant = Grant()
    assert grant.grant_expiration_time == 0

    grant = Grant()
    assert grant.grant_expiration_time == 0