Ejemplo n.º 1
0
    def test_start_auth_name_id_policy(self, sp_conf):
        """
        Performs a complete test for the module satosa.backends.saml2. The flow should be accepted.
        """
        samlbackend = SamlBackend(
            None, INTERNAL_ATTRIBUTES, {
                "config": sp_conf,
                "disco_srv": "https://my.dicso.com/role/idp.ds",
                "state_id": "saml_backend_test_id"
            })
        test_state_key = "sauyghj34589fdh"

        state = State()
        state.add(test_state_key, "my_state")
        context = Context()
        context.state = state

        internal_req = InternalRequest(UserIdHashType.transient, None)
        resp = samlbackend.start_auth(context, internal_req)

        assert resp.status == "303 See Other", "Must be a redirect to the discovery server."

        disco_resp = parse_qs(urlparse(resp.message).query)
        sp_disco_resp = \
            sp_conf["service"]["sp"]["endpoints"]["discovery_response"][0][0]
        assert "return" in disco_resp and disco_resp["return"][0].startswith(sp_disco_resp), \
            "Not a valid return url in the call to the discovery server"
        assert "entityID" in disco_resp and disco_resp["entityID"][0] == sp_conf["entityid"], \
            "Not a valid entity id in the call to the discovery server"

        request_info_tmp = context.state
        assert request_info_tmp.get(
            test_state_key) == "my_state", "Wrong state!"
Ejemplo n.º 2
0
    def test_start_auth_name_id_policy(self, sp_conf):
        """
        Performs a complete test for the module satosa.backends.saml2. The flow should be accepted.
        """
        samlbackend = SamlBackend(None, INTERNAL_ATTRIBUTES, {"config": sp_conf,
                                                              "disco_srv": "https://my.dicso.com/role/idp.ds",
                                                              "state_id": "saml_backend_test_id"})
        test_state_key = "sauyghj34589fdh"

        state = State()
        state.add(test_state_key, "my_state")
        context = Context()
        context.state = state

        internal_req = InternalRequest(UserIdHashType.transient, None)
        resp = samlbackend.start_auth(context, internal_req)

        assert resp.status == "303 See Other", "Must be a redirect to the discovery server."

        disco_resp = parse_qs(urlparse(resp.message).query)
        sp_disco_resp = \
            sp_conf["service"]["sp"]["endpoints"]["discovery_response"][0][0]
        assert "return" in disco_resp and disco_resp["return"][0].startswith(sp_disco_resp), \
            "Not a valid return url in the call to the discovery server"
        assert "entityID" in disco_resp and disco_resp["entityID"][0] == sp_conf["entityid"], \
            "Not a valid entity id in the call to the discovery server"

        request_info_tmp = context.state
        assert request_info_tmp.get(test_state_key) == "my_state", "Wrong state!"
Ejemplo n.º 3
0
    def test_urlstate_length_should_fit_in_browser_cookie(self):
        """
        Performs a test that the state class works as intended.

        :return:
        """
        enc_key = "Ireallyliketoencryptthisdictionary!"
        state = State()
        my_dict_frontend = get_dict(11, get_str(10), get_str(10))
        my_dict_consent = get_dict(1, get_str(10), get_str(100))
        my_dict_hash = get_dict(1, get_str(10), get_str(15))
        my_dict_router = get_dict(1, get_str(10), get_str(10))
        my_dict_backend = get_dict(10, get_str(10), get_str(10))
        state["my_dict_frontend"] = my_dict_frontend
        state["my_dict_consent"] = my_dict_consent
        state["my_dict_hash"] = my_dict_hash
        state["my_dict_router"] = my_dict_router
        state["my_dict_backend"] = my_dict_backend
        urlstate = state.urlstate(enc_key)
        # Some browsers only support 2000bytes, and since state is not the only parameter it should
        # not be greater then half that size.
        urlstate_len = len(quote_plus(urlstate))
        print("Size of state on the url is:%s" % urlstate_len)
        assert urlstate_len < 1000, "Urlstate is way to long!"
        state = State(urlstate, enc_key)
        assert state["my_dict_frontend"] == my_dict_frontend
        assert state["my_dict_consent"] == my_dict_consent
        assert state["my_dict_hash"] == my_dict_hash
        assert state["my_dict_router"] == my_dict_router
        assert state["my_dict_backend"] == my_dict_backend
Ejemplo n.º 4
0
    def test_urlstate_length_should_fit_in_browser_cookie(self):
        """
        Performs a test that the state class works as intended.

        :return:
        """
        enc_key = "Ireallyliketoencryptthisdictionary!"
        state = State()
        my_dict_frontend = get_dict(11, get_str(10), get_str(10))
        my_dict_consent = get_dict(1, get_str(10), get_str(100))
        my_dict_hash = get_dict(1, get_str(10), get_str(15))
        my_dict_router = get_dict(1, get_str(10), get_str(10))
        my_dict_backend = get_dict(10, get_str(10), get_str(10))
        state["my_dict_frontend"] = my_dict_frontend
        state["my_dict_consent"] = my_dict_consent
        state["my_dict_hash"] = my_dict_hash
        state["my_dict_router"] = my_dict_router
        state["my_dict_backend"] = my_dict_backend
        urlstate = state.urlstate(enc_key)
        # Some browsers only support 2000bytes, and since state is not the only parameter it should
        # not be greater then half that size.
        urlstate_len = len(quote_plus(urlstate))
        print("Size of state on the url is:%s" % urlstate_len)
        assert urlstate_len < 1000, "Urlstate is way to long!"
        state = State(urlstate, enc_key)
        assert state["my_dict_frontend"] == my_dict_frontend
        assert state["my_dict_consent"] == my_dict_consent
        assert state["my_dict_hash"] == my_dict_hash
        assert state["my_dict_router"] == my_dict_router
        assert state["my_dict_backend"] == my_dict_backend
Ejemplo n.º 5
0
    def test_start_auth_no_request_info(self, sp_conf):
        """
        Performs a complete test for the module satosa.backends.saml2. The flow should be accepted.
        """
        disco_srv = "https://my.dicso.com/role/idp.ds"
        samlbackend = SamlBackend(
            None, INTERNAL_ATTRIBUTES, {
                "config": sp_conf,
                "disco_srv": disco_srv,
                "state_id": "saml_backend_test_id"
            })
        internal_data = InternalRequest(None, None)

        state = State()
        context = Context()
        context.state = state
        resp = samlbackend.start_auth(context, internal_data)
        assert resp.status == "303 See Other", "Must be a redirect to the discovery server."
        assert resp.message.startswith("https://my.dicso.com/role/idp.ds"), \
            "Redirect to wrong URL."

        # create_name_id_policy_transient()
        state = State()
        context = Context()
        context.state = state
        user_id_hash_type = UserIdHashType.transient
        internal_data = InternalRequest(user_id_hash_type, None)
        resp = samlbackend.start_auth(context, internal_data)
        assert resp.status == "303 See Other", "Must be a redirect to the discovery server."
Ejemplo n.º 6
0
    def test_start_auth_disco(self, sp_conf, idp_conf):
        """
        Performs a complete test for the module satosa.backends.saml2. The flow should be accepted.
        """
        samlbackend = SamlBackend(lambda context, internal_resp: (context, internal_resp),
                                  INTERNAL_ATTRIBUTES, {"config": sp_conf,
                                                        "disco_srv": "https://my.dicso.com/role/idp.ds",
                                                        "state_id": "saml_backend_test_id"})
        test_state_key = "test_state_key_456afgrh"
        response_binding = BINDING_HTTP_REDIRECT
        fakeidp = FakeIdP(USERS, config=IdPConfig().load(idp_conf, metadata_construction=False))

        internal_req = InternalRequest(UserIdHashType.persistent, "example.se/sp.xml")

        state = State()
        state.add(test_state_key, "my_state")
        context = Context()
        context.state = state

        resp = samlbackend.start_auth(context, internal_req)
        assert resp.status == "303 See Other", "Must be a redirect to the discovery server."

        disco_resp = parse_qs(urlparse(resp.message).query)

        info = parse_qs(urlparse(disco_resp["return"][0]).query)
        info[samlbackend.idp_disco_query_param] = idp_conf["entityid"]
        context = Context()
        context.request = info
        context.state = state
        resp = samlbackend.disco_response(context)
        assert resp.status == "303 See Other"
        req_params = dict(parse_qsl(urlparse(resp.message).query))
        url, fake_idp_resp = fakeidp.handle_auth_req(
                req_params["SAMLRequest"],
                req_params["RelayState"],
                BINDING_HTTP_REDIRECT,
                "testuser1",
                response_binding=response_binding)
        context = Context()
        context.request = fake_idp_resp
        context.state = state
        context, internal_resp = samlbackend.authn_response(context, response_binding)
        assert isinstance(context, Context), "Not correct instance!"
        assert context.state.get(test_state_key) == "my_state", "Not correct state!"
        assert internal_resp.auth_info.auth_class_ref == PASSWORD, "Not correct authentication!"
        _dict = internal_resp.get_attributes()
        expected_data = {'surname': ['Testsson 1'], 'mail': ['*****@*****.**'],
                         'displayname': ['Test Testsson'], 'givenname': ['Test 1'],
                         'edupersontargetedid': ['one!for!all']}
        for key in _dict:
            assert expected_data[key] == _dict[key]
Ejemplo n.º 7
0
    def test_with_pyoidc(self):
        responses.add(responses.POST,
                      "https://graph.facebook.com/v2.5/oauth/access_token",
                      body=json.dumps({
                          "access_token": "qwerty",
                          "token_type": "bearer",
                          "expires_in": 9999999999999
                      }),
                      adding_headers={"set-cookie": "TEST=testing; path=/"},
                      status=200,
                      content_type='application/json')
        responses.add(responses.GET,
                      "https://graph.facebook.com/v2.5/me",
                      match_querystring=False,
                      body=json.dumps(FB_RESPONSE),
                      status=200,
                      content_type='application/json')

        context = Context()
        context.path = 'facebook/sso/redirect'
        context.state = State()
        internal_request = InternalRequest(UserIdHashType.transient,
                                           'http://localhost:8087/sp.xml')
        get_state = Mock()
        get_state.return_value = STATE
        resp = self.fb_backend.start_auth(context, internal_request, get_state)
        context.cookie = resp.headers[0][1]
        context.request = {"code": FB_RESPONSE_CODE, "state": STATE}
        self.fb_backend.auth_callback_func = self.verify_callback
        self.fb_backend.authn_response(context)
Ejemplo n.º 8
0
    def test_consent_not_given(self, internal_response, internal_request,
                               consent_verify_endpoint_regex,
                               consent_registration_endpoint_regex):
        consent_config = SATOSAConfig(self.satosa_config)
        consent_module = ConsentModule(consent_config, identity_callback)
        expected_ticket = "my_ticket"

        responses.add(responses.GET, consent_verify_endpoint_regex, status=401)
        responses.add(responses.GET,
                      consent_registration_endpoint_regex,
                      status=200,
                      body=expected_ticket)

        context = Context()
        state = State()
        context.state = state
        consent_module.save_state(internal_request, state)

        resp = consent_module.manage_consent(context, internal_response)

        self.assert_redirect(resp, expected_ticket)
        self.assert_registstration_req(responses.calls[1].request,
                                       consent_config.CONSENT["sign_key"])

        context = Context()
        context.state = state
        # Verify endpoint of consent service still gives 401 (no consent given)
        context, internal_response = consent_module._handle_consent_response(
            context)
        assert not internal_response.get_attributes()
Ejemplo n.º 9
0
 def setup(self, signing_key_path):
     self.account_linking_config = {
         "enable": True,
         "rest_uri": "https://localhost:8167",
         "redirect": "https://localhost:8167/approve",
         "endpoint": "handle_account_linking",
         "sign_key": signing_key_path,
         "verify_ssl": False
     }
     self.satosa_config = {
         "BASE": "https://proxy.example.com",
         "USER_ID_HASH_SALT": "qwerty",
         "COOKIE_STATE_NAME": "SATOSA_SATE",
         "STATE_ENCRYPTION_KEY": "ASDasd123",
         "PLUGIN_PATH": "",
         "BACKEND_MODULES": "",
         "FRONTEND_MODULES": "",
         "INTERNAL_ATTRIBUTES": {},
         "ACCOUNT_LINKING": self.account_linking_config
     }
     self.callback_func = MagicMock()
     self.context = Context()
     state = State()
     self.context.state = state
     auth_info = AuthenticationInformation("auth_class_ref", "timestamp",
                                           "issuer")
     self.internal_response = InternalResponse(auth_info=auth_info)
Ejemplo n.º 10
0
    def _save_state(self, resp, context):
        """
        Saves a state from context to cookie

        :type resp: satosa.response.Response
        :type context: satosa.context.Context

        :param resp: The response
        :param context: Session context
        """
        if context.state.should_delete():
            # Save empty state with a max age of 0
            cookie = state_to_cookie(State(), self.config.COOKIE_STATE_NAME,
                                     "/", self.config.STATE_ENCRYPTION_KEY, 0)
        else:
            cookie = state_to_cookie(context.state,
                                     self.config.COOKIE_STATE_NAME, "/",
                                     self.config.STATE_ENCRYPTION_KEY)

        if isinstance(resp, Response):
            resp.add_cookie(cookie)
        else:
            try:
                resp.headers.append(tuple(cookie.output().split(": ", 1)))
            except:
                satosa_logging(
                    LOGGER, logging.WARN,
                    "can't add cookie to response '%s'" % resp.__class__,
                    context.state)
                pass
Ejemplo n.º 11
0
 def generate_state(self, op_base):
     state = State()
     state_id = TestConfiguration.get_instance().rp_config.STATE_ID
     state_data = {
         StateKeys.OP: PROVIDER,
         StateKeys.NONCE: "9YraWpJAmVp4L3NJ",
         StateKeys.TOKEN_ENDPOINT: TestConfiguration.get_instance().rp_config.OP_URL + "token",
         StateKeys.CLIENT_ID: "client_1",
         StateKeys.CLIENT_SECRET: "2222222222",
         StateKeys.JWKS_URI:
             TestConfiguration.get_instance().rp_config.OP_URL + "static/jwks.json",
         StateKeys.USERINFO_ENDPOINT:
             TestConfiguration.get_instance().rp_config.OP_URL + "userinfo",
         StateKeys.STATE: FakeOP.STATE
     }
     state.add(state_id, state_data)
     return state
Ejemplo n.º 12
0
 def test_redirect_to_login_at_auth_endpoint(self):
     self.fake_op.setup_webfinger_endpoint()
     self.fake_op.setup_opienid_config_endpoint()
     self.fake_op.setup_client_registration_endpoint()
     context = Context()
     context.state = State()
     auth_response = self.openid_backend.start_auth(context, None)
     assert auth_response._status == Redirect._status
Ejemplo n.º 13
0
    def test_state_to_cookie_produces_cookie_without_max_age_for_state_that_should_be_deleted(self):
        state_key = "27614gjkrn"
        saved_data = "data"
        state = State()
        state[state_key] = saved_data
        state.delete = True

        cookie_name = "state_cookie"
        path = "/"
        encrypt_key = "2781y4hef90"

        cookie = state_to_cookie(state, cookie_name, path, encrypt_key)
        cookie_str = cookie[cookie_name].OutputString()

        parsed_cookie = SimpleCookie(cookie_str)
        assert not parsed_cookie[cookie_name].value
        assert parsed_cookie[cookie_name]["max-age"] == '0'
Ejemplo n.º 14
0
def _get_id(requestor, user_id, hash_type):
    state = State()

    internal_request = InternalRequest(hash_type, requestor)

    UserIdHasher.save_state(internal_request, state)

    return UserIdHasher.hash_id(SALT, user_id, requestor, state)
Ejemplo n.º 15
0
 def test_set_state_in_start_auth_and_use_in_redirect_endpoint(self):
     self.fake_op.setup_webfinger_endpoint()
     self.fake_op.setup_opienid_config_endpoint()
     self.fake_op.setup_client_registration_endpoint()
     context = Context()
     context.state = State()
     self.openid_backend.start_auth(context, None)
     context = self.setup_fake_op_endpoints(FakeOP.STATE)
     self.openid_backend.redirect_endpoint(context)
Ejemplo n.º 16
0
    def test_state_to_cookie_produces_cookie_without_max_age_for_state_that_should_be_deleted(
            self):
        state_key = "27614gjkrn"
        saved_data = "data"
        state = State()
        state[state_key] = saved_data
        state.delete = True

        cookie_name = "state_cookie"
        path = "/"
        encrypt_key = "2781y4hef90"

        cookie = state_to_cookie(state, cookie_name, path, encrypt_key)
        cookie_str = cookie[cookie_name].OutputString()

        parsed_cookie = SimpleCookie(cookie_str)
        assert not parsed_cookie[cookie_name].value
        assert parsed_cookie[cookie_name]["max-age"] == '0'
Ejemplo n.º 17
0
 def test_frontend(path, provider, receiver, endpoint):
     context = Context()
     context.state = State()
     context.path = path
     spec = router.endpoint_routing(context)
     assert spec[0] == receiver
     assert spec[1] == endpoint
     assert context.target_frontend == receiver
     assert context.target_backend == provider
Ejemplo n.º 18
0
def test_state_cookie():
    """
    Test that the state can be converted between cookie and state
    """
    state_key = "27614gjkrn"
    saved_data = "data"
    state = State()
    state.add(state_key, saved_data)

    cookie_name = "state_cookie"
    path = "/"
    encrypt_key = "2781y4hef90"

    cookie = state_to_cookie(state, cookie_name, path, encrypt_key)
    cookie_str = cookie.output()
    loaded_state = cookie_to_state(cookie_str, cookie_name, encrypt_key)

    assert loaded_state.get(state_key) == saved_data
Ejemplo n.º 19
0
def test_state_cookie():
    """
    Test that the state can be converted between cookie and state
    """
    state_key = "27614gjkrn"
    saved_data = "data"
    state = State()
    state.add(state_key, saved_data)

    cookie_name = "state_cookie"
    path = "/"
    encrypt_key = "2781y4hef90"

    cookie = state_to_cookie(state, cookie_name, path, encrypt_key)
    cookie_str = cookie.output()
    loaded_state = cookie_to_state(cookie_str, cookie_name, encrypt_key)

    assert loaded_state.get(state_key) == saved_data
Ejemplo n.º 20
0
    def test_redirect_to_idp_if_only_one_idp_in_metadata(self, sp_conf, idp_conf):
        sp_conf["metadata"]["inline"] = [create_metadata_from_config_dict(idp_conf)]
        samlbackend = SamlBackend(None, INTERNAL_ATTRIBUTES,
                                  {"config": sp_conf, "state_id": "saml_backend_test_id"})

        state = State()
        state.add("test", "state")
        context = Context()
        context.state = state
        internal_req = InternalRequest(UserIdHashType.transient, None)

        resp = samlbackend.start_auth(context, internal_req)

        assert resp.status == "303 See Other"
        parsed = urlparse(resp.message)
        assert "{parsed.scheme}://{parsed.netloc}{parsed.path}".format(
                parsed=parsed) == \
               idp_conf["service"]["idp"]["endpoints"]["single_sign_on_service"][0][0]
        assert "SAMLRequest" in parse_qs(parsed.query)
Ejemplo n.º 21
0
    def test_acr_mapping_per_idp_in_authn_response(self, idp_conf, sp_conf):
        expected_loa = "LoA1"
        loa = {
            "": "http://eidas.europa.eu/LoA/low",
            idp_conf["entityid"]: expected_loa
        }

        base = self.construct_base_url_from_entity_id(idp_conf["entityid"])
        conf = {
            "idp_config": idp_conf,
            "endpoints": ENDPOINTS,
            "base": base,
            "state_id": "state_id",
            "acr_mapping": loa
        }

        samlfrontend = SamlFrontend(None, INTERNAL_ATTRIBUTES, conf)
        samlfrontend.register_endpoints(["foo"])

        idp_metadata_str = create_metadata_from_config_dict(
            samlfrontend.config)
        sp_conf["metadata"]["inline"].append(idp_metadata_str)
        fakesp = FakeSP(None,
                        config=SPConfig().load(sp_conf,
                                               metadata_construction=False))

        auth_info = AuthenticationInformation(PASSWORD, "2015-09-30T12:21:37Z",
                                              idp_conf["entityid"])
        internal_response = InternalResponse(auth_info=auth_info)
        context = Context()
        context.state = State()

        resp_args = {
            "name_id_policy": NameIDPolicy(format=NAMEID_FORMAT_TRANSIENT),
            "in_response_to": None,
            "destination": "",
            "sp_entity_id": None,
            "binding": BINDING_HTTP_REDIRECT
        }
        request_state = samlfrontend.save_state(context, resp_args, "")
        context.state.add(conf["state_id"], request_state)

        resp = samlfrontend.handle_authn_response(context, internal_response)
        resp_dict = parse_qs(urlparse(resp.message).query)
        resp = fakesp.parse_authn_request_response(
            resp_dict['SAMLResponse'][0], BINDING_HTTP_REDIRECT)

        assert len(resp.assertion.authn_statement) == 1
        authn_context_class_ref = resp.assertion.authn_statement[
            0].authn_context.authn_context_class_ref
        assert authn_context_class_ref.text == expected_loa
Ejemplo n.º 22
0
    def _load_state(self, context):
        """
        Load a state to the context

        :type context: satosa.context.Context
        :param context: Session context
        """
        try:
            state = cookie_to_state(context.cookie,
                                    self.config.COOKIE_STATE_NAME,
                                    self.config.STATE_ENCRYPTION_KEY)
        except SATOSAStateError:
            state = State()
        context.state = state
Ejemplo n.º 23
0
 def test_test_restore_state_with_separate_backends(self):
     openid_backend_1 = OpenIdBackend(
         MagicMock, INTERNAL_ATTRIBUTES,
         TestConfiguration.get_instance().config)
     openid_backend_2 = OpenIdBackend(
         MagicMock, INTERNAL_ATTRIBUTES,
         TestConfiguration.get_instance().config)
     self.fake_op.setup_webfinger_endpoint()
     self.fake_op.setup_opienid_config_endpoint()
     self.fake_op.setup_client_registration_endpoint()
     context = Context()
     context.state = State()
     openid_backend_1.start_auth(context, None)
     context = self.setup_fake_op_endpoints(FakeOP.STATE)
     openid_backend_2.redirect_endpoint(context)
Ejemplo n.º 24
0
    def test_redirect_to_idp_if_only_one_idp_in_metadata(
            self, sp_conf, idp_conf):
        sp_conf["metadata"]["inline"] = [
            create_metadata_from_config_dict(idp_conf)
        ]
        samlbackend = SamlBackend(None, INTERNAL_ATTRIBUTES, {
            "config": sp_conf,
            "state_id": "saml_backend_test_id"
        })

        state = State()
        state.add("test", "state")
        context = Context()
        context.state = state
        internal_req = InternalRequest(UserIdHashType.transient, None)

        resp = samlbackend.start_auth(context, internal_req)

        assert resp.status == "303 See Other"
        parsed = urlparse(resp.message)
        assert "{parsed.scheme}://{parsed.netloc}{parsed.path}".format(
                parsed=parsed) == \
               idp_conf["service"]["idp"]["endpoints"]["single_sign_on_service"][0][0]
        assert "SAMLRequest" in parse_qs(parsed.query)
Ejemplo n.º 25
0
 def generate_state(self, op_base):
     state = State()
     state_id = TestConfiguration.get_instance().rp_config.STATE_ID
     state_data = {
         StateKeys.OP:
         PROVIDER,
         StateKeys.NONCE:
         "9YraWpJAmVp4L3NJ",
         StateKeys.TOKEN_ENDPOINT:
         TestConfiguration.get_instance().rp_config.OP_URL + "token",
         StateKeys.CLIENT_ID:
         "client_1",
         StateKeys.CLIENT_SECRET:
         "2222222222",
         StateKeys.JWKS_URI:
         TestConfiguration.get_instance().rp_config.OP_URL +
         "static/jwks.json",
         StateKeys.USERINFO_ENDPOINT:
         TestConfiguration.get_instance().rp_config.OP_URL + "userinfo",
         StateKeys.STATE:
         FakeOP.STATE
     }
     state.add(state_id, state_data)
     return state
Ejemplo n.º 26
0
    def test_consent_prev_given(self, internal_response, internal_request,
                                consent_verify_endpoint_regex):
        consent_config = SATOSAConfig(self.satosa_config)
        consent_module = ConsentModule(consent_config, identity_callback)

        responses.add(responses.GET,
                      consent_verify_endpoint_regex,
                      status=200,
                      body=json.dumps(FILTER))

        context = Context()
        state = State()
        context.state = state
        consent_module.save_state(internal_request, state)
        context, internal_response = consent_module.manage_consent(
            context, internal_response)
        assert context
        assert "displayName" in internal_response.get_attributes()
Ejemplo n.º 27
0
    def test_encode_decode_of_state(self):
        """
        Test that the state can be converted between cookie and state
        """
        state_key = "27614gjkrn"
        saved_data = "data"
        state = State()
        state[state_key] = saved_data

        cookie_name = "state_cookie"
        path = "/"
        encrypt_key = "2781y4hef90"

        cookie = state_to_cookie(state, cookie_name, path, encrypt_key)
        cookie_str = cookie[cookie_name].OutputString()
        loaded_state = cookie_to_state(cookie_str, cookie_name, encrypt_key)

        assert loaded_state[state_key] == saved_data
Ejemplo n.º 28
0
def test_module_routing(router_fixture):
    router, frontends, backends = router_fixture
    state = State()

    def test_routing(path, provider, receiver, _):
        context = Context()
        context.path = path
        context.state = state
        router.endpoint_routing(context)

        backend = router.backend_routing(context)
        assert backend == backends[provider]

        frontend = router.frontend_routing(context)
        assert frontend == frontends[receiver]
        assert context.target_frontend == receiver

    foreach_frontend_endpoint(test_routing)
Ejemplo n.º 29
0
 def test_authn_response(self):
     context = Context()
     context.path = 'facebook/sso/redirect'
     context.state = State()
     internal_request = InternalRequest(UserIdHashType.transient,
                                        'http://localhost:8087/sp.xml')
     get_state = Mock()
     get_state.return_value = STATE
     resp = self.fb_backend.start_auth(context, internal_request, get_state)
     context.cookie = resp.headers[0][1]
     context.request = {"code": FB_RESPONSE_CODE, "state": STATE}
     # context.request = json.dumps(context.request)
     self.fb_backend.auth_callback_func = self.verify_callback
     tmp_consumer = self.fb_backend.get_consumer()
     tmp_consumer.do_access_token_request = self.verify_do_access_token_request
     self.fb_backend.get_consumer = Mock()
     self.fb_backend.get_consumer.return_value = tmp_consumer
     self.fb_backend.request_fb = self.verify_request_fb
     self.fb_backend.authn_response(context)
Ejemplo n.º 30
0
    def test_consent_handles_connection_error(self, internal_response,
                                              internal_request,
                                              consent_verify_endpoint_regex):
        consent_config = SATOSAConfig(self.satosa_config)
        consent_module = ConsentModule(consent_config, identity_callback)

        state = State()
        context = Context()
        context.state = state
        consent_module.save_state(internal_request, state)
        with responses.RequestsMock(
                assert_all_requests_are_fired=True) as rsps:
            rsps.add(responses.GET,
                     consent_verify_endpoint_regex,
                     body=requests.ConnectionError("No connection"))
            context, internal_response = consent_module.manage_consent(
                context, internal_response)

        assert context
        assert not internal_response.get_attributes()
Ejemplo n.º 31
0
    def setUp(self):
        context = Context()
        context.state = State()

        config = {
            'disco_endpoints': [
                '.*/disco',
            ],
        }

        plugin = DiscoToTargetIssuer(
            config=config,
            name='test_disco_to_target_issuer',
            base_url='https://satosa.example.org',
        )
        plugin.next = lambda ctx, data: (ctx, data)

        self.config = config
        self.context = context
        self.plugin = plugin
Ejemplo n.º 32
0
 def test_start_auth(self):
     context = Context()
     context.path = 'facebook/sso/redirect'
     context.state = State()
     internal_request = InternalRequest(UserIdHashType.transient,
                                        'http://localhost:8087/sp.xml')
     get_state = Mock()
     get_state.return_value = STATE
     resp = self.fb_backend.start_auth(context, internal_request, get_state)
     # assert resp.headers[0][0] == "Set-Cookie", "Not the correct return cookie"
     # assert len(resp.headers[0][1]) > 1, "Not the correct return cookie"
     resp_url = resp.message.split("?")
     test_url = FB_REDIRECT_URL.split("?")
     resp_attr = parse_qs(resp_url[1])
     test_attr = parse_qs(test_url[1])
     assert resp_url[0] == test_url[0]
     assert len(resp_attr) == len(test_attr), "Redirect url is not correct!"
     for key in test_attr:
         assert key in resp_attr, "Redirect url is not correct!"
         assert test_attr[key] == resp_attr[
             key], "Redirect url is not correct!"
Ejemplo n.º 33
0
def test_micro_service():
    """
    Test the micro service flow
    """
    data_list = ["1", "2", "3"]
    service_list = []
    for d in data_list:
        service = MicroService()
        service.process = create_process_func(d)
        service_list.append(service)

    service_queue = build_micro_service_queue(service_list)
    test_data = "test_data"
    context = Context()
    context.state = State()
    data = service_queue.process_service_queue(context, test_data)

    for d in data_list:
        test_data = "{}{}".format(test_data, d)

    assert data == test_data
Ejemplo n.º 34
0
    def setUp(self):
        context = Context()
        context.state = State()

        config = {
            'default_backend': 'default_backend',
            'target_mapping': {
                'mapped_idp.example.org': 'mapped_backend',
            },
        }

        plugin = DecideBackendByTargetIssuer(
            config=config,
            name='test_decide_service',
            base_url='https://satosa.example.org',
        )
        plugin.next = lambda ctx, data: (ctx, data)

        self.config = config
        self.context = context
        self.plugin = plugin
Ejemplo n.º 35
0
    def test_consent_full_flow(self, internal_response, internal_request,
                               consent_verify_endpoint_regex,
                               consent_registration_endpoint_regex):
        consent_config = SATOSAConfig(self.satosa_config)
        consent_module = ConsentModule(consent_config, identity_callback)
        expected_ticket = "my_ticket"

        context = Context()
        state = State()
        context.state = state
        consent_module.save_state(internal_request, state)

        with responses.RequestsMock() as rsps:
            rsps.add(responses.GET, consent_verify_endpoint_regex, status=401)
            rsps.add(responses.GET,
                     consent_registration_endpoint_regex,
                     status=200,
                     body=expected_ticket)
            resp = consent_module.manage_consent(context, internal_response)

            self.assert_redirect(resp, expected_ticket)
            self.assert_registstration_req(rsps.calls[1].request,
                                           consent_config.CONSENT["sign_key"])

        with responses.RequestsMock() as rsps:
            # Now consent has been given, consent service returns 200 OK
            rsps.add(responses.GET,
                     consent_verify_endpoint_regex,
                     status=200,
                     body=json.dumps(FILTER))

            context = Context()
            context.state = state
            context, internal_response = consent_module._handle_consent_response(
                context)

        assert internal_response.get_attributes()["displayName"] == ["Test"]
        assert internal_response.get_attributes()["co"] == ["example"]
        assert "sn" not in internal_response.get_attributes(
        )  # 'sn' should be filtered
Ejemplo n.º 36
0
    def setup_for_authn_req(self, idp_conf, sp_conf, nameid_format):
        base = self.construct_base_url_from_entity_id(idp_conf["entityid"])
        config = {
            "idp_config": idp_conf,
            "endpoints": ENDPOINTS,
            "base": base,
            "state_id": "state_id"
        }
        sp_metadata_str = create_metadata_from_config_dict(sp_conf)
        idp_conf["metadata"]["inline"] = [sp_metadata_str]

        samlfrontend = SamlFrontend(
            lambda context, internal_req: (context, internal_req),
            INTERNAL_ATTRIBUTES, config)
        samlfrontend.register_endpoints(["saml"])

        idp_metadata_str = create_metadata_from_config_dict(
            samlfrontend.config)
        sp_conf["metadata"]["inline"].append(idp_metadata_str)

        fakesp = FakeSP(None,
                        config=SPConfig().load(sp_conf,
                                               metadata_construction=False))
        context = Context()
        context.state = State()
        context.request = parse.parse_qs(
            urlparse(
                fakesp.make_auth_req(samlfrontend.config["entityid"],
                                     nameid_format)).query)
        tmp_dict = {}
        for val in context.request:
            if isinstance(context.request[val], list):
                tmp_dict[val] = context.request[val][0]
            else:
                tmp_dict[val] = context.request[val]
        context.request = tmp_dict

        return context, samlfrontend
Ejemplo n.º 37
0
def test_mirco_service_error():
    """
    Test that the process_service_queue raises a SATOSAAuthenticationError if anything goes wrong with a micro service
    """
    data_list = ["1", "2", "3"]
    service_list = []

    fail_service = MicroService()
    fail_service.process = create_process_fail_func("4")
    service_list.append(fail_service)

    for d in data_list:
        service = MicroService()
        service.process = create_process_func(d)
        service_list.append(service)

    service_queue = build_micro_service_queue(service_list)
    test_data = "test_data"
    context = Context()
    context.state = State()

    with pytest.raises(SATOSAAuthenticationError):
        service_queue.process_service_queue(context, test_data)
Ejemplo n.º 38
0
 def create_state(self, auth_req):
     state = State()
     state.add(type(self.instance).__name__, {"oidc_request": auth_req.to_urlencoded()})
     return state
Ejemplo n.º 39
0
def test_simple_test():
    """
    Performs a test that the state class works as intended.

    :return:
    """
    enc_key = "Ireallyliketoencryptthisdictionary!"
    state = State()
    my_dict_frontend = get_dict(10, get_str(10), get_str(10))
    my_dict_frontend["resp_attr"] = get_str(100)
    assert len(my_dict_frontend) == 11, "The dictionary is not correct!"
    my_dict_consent = get_dict(1, get_str(10), get_str(100))
    assert len(my_dict_consent) == 1, "The dictionary is not correct!"
    my_dict_hash = get_dict(1, get_str(10), get_str(15))
    assert len(my_dict_hash) == 1, "The dictionary is not correct!"
    my_dict_router = get_dict(1, get_str(10), get_str(10))
    assert len(my_dict_router) == 1, "The dictionary is not correct!"
    my_dict_backend = get_dict(10, get_str(10), get_str(10))
    assert len(my_dict_backend) == 10, "The dictionary is not correct!"
    state.add("my_dict_frontend", my_dict_frontend)
    state.add("my_dict_consent", my_dict_consent)
    state.add("my_dict_hash", my_dict_hash)
    state.add("my_dict_router", my_dict_router)
    state.add("my_dict_backend", my_dict_backend)
    urlstate = state.urlstate(enc_key)
    # Some browsers only support 2000bytes, and since state is not the only parameter it should
    # not be greater then half that size.
    urlstate_len = len(quote_plus(urlstate))
    print("Size of state on the url is:%s" % urlstate_len)
    assert urlstate_len < 1000, "Urlstate is way to long!"
    state = State(urlstate, enc_key)
    tmp_dict_frontend = state.get("my_dict_frontend")
    tmp_dict_consent = state.get("my_dict_consent")
    tmp_dict_hash = state.get("my_dict_hash")
    tmp_dict_router = state.get("my_dict_router")
    tmp_dict_backend = state.get("my_dict_backend")
    compare_dict(tmp_dict_frontend, my_dict_frontend)
    compare_dict(tmp_dict_consent, my_dict_consent)
    compare_dict(tmp_dict_hash, my_dict_hash)
    compare_dict(tmp_dict_router, my_dict_router)
    compare_dict(tmp_dict_backend, my_dict_backend)