Exemplo n.º 1
0
def send_job(repo, server, cycles="", duration="", nodes="", redirect_url=""):
    mac_user = os.environ.get("MACAUTH_USER")
    mac_secret = os.environ.get("MACAUTH_SECRET")
    request = Request.blank(server.rstrip("/") + "/test")
    request.method = "POST"
    params = {
        "repo": repo,
        "cycles": cycles,
        "duration": duration,
        "nodes": nodes,
        "redirect_url": redirect_url,
        "api_call": 1,
    }

    request.body = urllib.urlencode(params)
    request.environ["CONTENT_TYPE"] = "application/x-www-form-urlencoded"

    if mac_user is not None:
        tokenid = tokenlib.make_token({"user": mac_user}, secret=mac_secret)
        key = tokenlib.get_token_secret(tokenid, secret=mac_secret)
        sign_request(request, tokenid, key)

    resp = request.get_response(proxy_exact_request)
    if resp.status_int == 401:
        raise ValueError("Authorization Failed!")

    job_id = resp.json["job_id"]
    return server.rstrip("/") + "/test/" + job_id
def send_job(repo, server, cycles='', duration='', nodes='', redirect_url=''):
    mac_user = os.environ.get('MACAUTH_USER')
    mac_secret = os.environ.get('MACAUTH_SECRET')
    request = Request.blank(server.rstrip('/') + '/test')
    request.method = 'POST'
    params = {
        'repo': repo,
        'cycles': cycles,
        'duration': duration,
        'nodes': nodes,
        'redirect_url': redirect_url,
        'api_call': 1
    }

    request.body = urllib.urlencode(params)
    request.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

    if mac_user is not None:
        tokenid = tokenlib.make_token({"user": mac_user}, secret=mac_secret)
        key = tokenlib.get_token_secret(tokenid, secret=mac_secret)
        sign_request(request, tokenid, key)

    resp = request.get_response(proxy_exact_request)
    if resp.status_int == 401:
        raise ValueError("Authorization Failed!")

    job_id = resp.json['job_id']
    return server.rstrip('/') + '/test/' + job_id
Exemplo n.º 3
0
 def _browse(self,
             url_in,
             params_in=None,
             description=None,
             ok_codes=None,
             method='post',
             *args,
             **kwds):
     # Automatically add a fresh MACAuth header to the request.
     if self.auth_token is not None:
         req = Request.blank(url_in)
         req.method = method.upper()
         if params_in and req.method in (
                 "GET",
                 "HEAD",
         ):
             qs_items = ("%s=%s" % item for item in params_in.iteritems())
             req.query_string = "&".join(qs_items)
         macauthlib.sign_request(req, self.auth_token, self.auth_secret)
         self.setHeader("Authorization", req.environ["HTTP_AUTHORIZATION"])
     # Log the start and end of the request, for debugging purposes.
     args = (url_in, params_in, description, ok_codes, method) + args
     self.logi("%s: %s" % (method.upper(), url_in))
     try:
         result = super(StressTest, self)._browse(*args, **kwds)
     except Exception, e:
         self.logi("    FAIL: " + url_in + " " + repr(e))
         raise
Exemplo n.º 4
0
 def setMACAuthHeader(self, method, url, token, secret):
     """Set the Sagrada MAC Auth header using the given credentials."""
     req = Request.blank(url)
     req.method = method
     macauthlib.sign_request(req, token, secret)
     self.clearHeaders()
     self.addHeader("Authorization", req.environ["HTTP_AUTHORIZATION"])
Exemplo n.º 5
0
 def setMACAuthHeader(self, method, url, token, secret):
     """Set the Sagrada MAC Auth header using the given credentials."""
     req = Request.blank(url)
     req.method = method
     macauthlib.sign_request(req, token, secret)
     self.clearHeaders()
     self.addHeader("Authorization", req.environ["HTTP_AUTHORIZATION"])
Exemplo n.º 6
0
 def _authHook(self,req):
     # This method will be used as a "pre-request hook" for the requests session.
     # It does MAC Authentication using the macauthlib library.
     # It will hook up sign_request() to be called on every request
     # using the current value of self.mac_key_id and self.mac_key
     macauthlib.sign_request(req, id=self.mac_key_id, key=self.mac_key, hashmod=hashlib.sha256)
     return req
 def test_authentication_without_nonce_fails(self):
     creds = self._get_credentials(username="******")
     req = Request.blank("/")
     macauthlib.sign_request(req, **creds)
     authz = req.environ["HTTP_AUTHORIZATION"]
     authz = authz.replace("nonce", "typonce")
     req.environ["HTTP_AUTHORIZATION"] = authz
     self.app.request(req, status=401)
 def test_authentication_without_nonce_fails(self):
     creds = self._get_credentials(username="******")
     req = Request.blank("/")
     macauthlib.sign_request(req, **creds)
     authz = req.environ["HTTP_AUTHORIZATION"]
     authz = authz.replace("nonce", "typonce")
     req.environ["HTTP_AUTHORIZATION"] = authz
     self.app.request(req, status=401)
Exemplo n.º 9
0
 def test_check_signature_fails_with_busted_signature(self):
     req = Request.blank("/")
     sign_request(req, "myid", "mykey")
     signature = parse_authz_header(req)["mac"]
     authz = req.environ["HTTP_AUTHORIZATION"]
     authz = authz.replace(signature, "XXX" + signature)
     req.environ["HTTP_AUTHORIZATION"] = authz
     self.assertFalse(check_signature(req, "mykey"))
Exemplo n.º 10
0
 def test_check_signature_fails_with_busted_signature(self):
     req = Request.blank("/")
     sign_request(req, "myid", "mykey")
     signature = parse_authz_header(req)["mac"]
     authz = req.environ["HTTP_AUTHORIZATION"]
     authz = authz.replace(signature, "XXX" + signature)
     req.environ["HTTP_AUTHORIZATION"] = authz
     self.assertFalse(check_signature(req, "mykey"))
 def test_authentication_with_busted_signature_fails(self):
     creds = self._get_credentials(username="******")
     req = Request.blank("/")
     macauthlib.sign_request(req, **creds)
     signature = macauthlib.utils.parse_authz_header(req)["mac"]
     authz = req.environ["HTTP_AUTHORIZATION"]
     authz = authz.replace(signature, "XXX" + signature)
     req.environ["HTTP_AUTHORIZATION"] = authz
     self.app.request(req, status=401)
 def test_authentication_with_busted_signature_fails(self):
     creds = self._get_credentials(username="******")
     req = Request.blank("/")
     macauthlib.sign_request(req, **creds)
     signature = macauthlib.utils.parse_authz_header(req)["mac"]
     authz = req.environ["HTTP_AUTHORIZATION"]
     authz = authz.replace(signature, "XXX" + signature)
     req.environ["HTTP_AUTHORIZATION"] = authz
     self.app.request(req, status=401)
Exemplo n.º 13
0
 def test_that_macauth_can_use_per_node_hostname_secrets(self):
     with tempfile.NamedTemporaryFile() as sf:
         # Write some secrets to a file.
         sf.write("host1,0001:secret11,0002:secret12\n")
         sf.write("host2,0001:secret21,0002:secret22\n")
         sf.flush()
         # Configure the plugin to load them.
         config2 = pyramid.testing.setUp()
         config2.add_settings(self.DEFAULT_SETTINGS)
         config2.add_settings({
             "who.plugin.macauth.secrets_file": sf.name,
         })
         config2.include("mozsvc.user.whoauth")
         config2.commit()
         # It should accept a request signed with the old secret on host1.
         req = self._make_request(config=config2, environ={
             "HTTP_HOST": "host1",
         })
         id = tokenlib.make_token({"userid": 42}, secret="secret11")
         key = tokenlib.get_token_secret(id, secret="secret11")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request signed with the new secret on host1.
         req = self._make_request(config=config2, environ={
             "HTTP_HOST": "host1",
         })
         id = tokenlib.make_token({"userid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should reject a request signed with secret from other host.
         req = self._make_request(config=config2, environ={
             "HTTP_HOST": "host2",
         })
         id = tokenlib.make_token({"userid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertRaises(Exception, authenticated_userid, req)
         # It should accept a request signed with the new secret on host2.
         req = self._make_request(config=config2, environ={
             "HTTP_HOST": "host2",
         })
         id = tokenlib.make_token({"userid": 42}, secret="secret22")
         key = tokenlib.get_token_secret(id, secret="secret22")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should reject unknown hostnames.
         req = self._make_request(config=config2, environ={
             "HTTP_HOST": "host3",
         })
         id = tokenlib.make_token({"userid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertRaises(Exception, authenticated_userid, req)
Exemplo n.º 14
0
 def test_check_signature_fails_with_far_future_timestamp(self):
     req = Request.blank("/")
     # Do an initial request so that the server can
     # calculate and cache our clock skew.
     ts = str(int(time.time()))
     req.authorization = ("MAC", {"ts": ts})
     sign_request(req, "myid", "mykey")
     self.assertTrue(check_signature(req, "mykey"))
     # Now do one with a far future timestamp.
     ts = str(int(time.time() + 1000))
     req.authorization = ("MAC", {"ts": ts})
     sign_request(req, "myid", "mykey")
     self.assertFalse(check_signature(req, "mykey"))
 def test_authentication_with_reused_nonce_fails(self):
     creds = self._get_credentials(username="******")
     # First request with that nonce should succeed.
     req = Request.blank("/")
     req.authorization = ("MAC", {"nonce": "PEPPER"})
     macauthlib.sign_request(req, **creds)
     r = self.app.request(req)
     self.assertEquals(r.body, "*****@*****.**")
     # Second request with that nonce should fail.
     req = Request.blank("/")
     req.authorization = ("MAC", {"nonce": "PEPPER"})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)
Exemplo n.º 16
0
 def test_check_signature_fails_with_far_future_timestamp(self):
     req = Request.blank("/")
     # Do an initial request so that the server can
     # calculate and cache our clock skew.
     ts = str(int(time.time()))
     req.authorization = ("MAC", {"ts": ts})
     sign_request(req, "myid", "mykey")
     self.assertTrue(check_signature(req, "mykey"))
     # Now do one with a far future timestamp.
     ts = str(int(time.time() + 1000))
     req.authorization = ("MAC", {"ts": ts})
     sign_request(req, "myid", "mykey")
     self.assertFalse(check_signature(req, "mykey"))
Exemplo n.º 17
0
 def test_check_signature_fails_with_reused_nonce(self):
     # First request with that nonce should succeed.
     req = Request.blank("/")
     req.authorization = ("MAC", {"nonce": "PEPPER"})
     sign_request(req, "myid", "mykey")
     self.assertTrue(check_signature(req, "mykey"))
     # Second request with that nonce should fail.
     req = Request.blank("/")
     req.authorization = ("MAC", {"nonce": "PEPPER"})
     sign_request(req, "myid", "mykey")
     self.assertFalse(check_signature(req, "mykey"))
     # But it will succeed if using a different nonce cache.
     self.assertTrue(check_signature(req, "mykey", nonces=NonceCache()))
Exemplo n.º 18
0
 def test_check_signature_fails_with_reused_nonce(self):
     # First request with that nonce should succeed.
     req = Request.blank("/")
     req.authorization = ("MAC", {"nonce": "PEPPER"})
     sign_request(req, "myid", "mykey")
     self.assertTrue(check_signature(req, "mykey"))
     # Second request with that nonce should fail.
     req = Request.blank("/")
     req.authorization = ("MAC", {"nonce": "PEPPER"})
     sign_request(req, "myid", "mykey")
     self.assertFalse(check_signature(req, "mykey"))
     # But it will succeed if using a different nonce cache.
     self.assertTrue(check_signature(req, "mykey", nonces=NonceCache()))
 def test_authentication_with_reused_nonce_fails(self):
     creds = self._get_credentials(username="******")
     # First request with that nonce should succeed.
     req = Request.blank("/")
     req.authorization = ("MAC", {"nonce": "PEPPER"})
     macauthlib.sign_request(req, **creds)
     r = self.app.request(req)
     self.assertEquals(r.body, "*****@*****.**")
     # Second request with that nonce should fail.
     req = Request.blank("/")
     req.authorization = ("MAC", {"nonce": "PEPPER"})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)
 def test_authentication_with_far_future_timestamp_fails(self):
     creds = self._get_credentials(username="******")
     req = Request.blank("/")
     # Do an initial request so that the server can
     # calculate and cache our clock skew.
     ts = str(int(time.time()))
     req.authorization = ("MAC", {"ts": ts})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=200)
     # Now do one with a far future timestamp.
     ts = str(int(time.time() + 1000))
     req.authorization = ("MAC", {"ts": ts})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)
 def test_authentication_with_far_future_timestamp_fails(self):
     creds = self._get_credentials(username="******")
     req = Request.blank("/")
     # Do an initial request so that the server can
     # calculate and cache our clock skew.
     ts = str(int(time.time()))
     req.authorization = ("MAC", {"ts": ts})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=200)
     # Now do one with a far future timestamp.
     ts = str(int(time.time() + 1000))
     req.authorization = ("MAC", {"ts": ts})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)
Exemplo n.º 22
0
 def test_authentication_with_expired_timestamp_fails(self):
     creds = self._get_credentials(username="******")
     req = self._make_request("/auth")
     # Do an initial request so that the server can
     # calculate and cache our clock skew.
     ts = str(int(time.time()))
     req.authorization = ("MAC", {"ts": ts})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=200)
     # Now do one with a really old timestamp.
     ts = str(int(time.time() - 1000))
     req.authorization = ("MAC", {"ts": ts})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)
Exemplo n.º 23
0
 def test_authentication_with_expired_timestamp_fails(self):
     req = self._make_request("/auth")
     creds = self._get_credentials(req, username="******")
     # Do an initial request so that the server can
     # calculate and cache our clock skew.
     ts = str(int(time.time()))
     req.authorization = ("MAC", {"ts": ts})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=200)
     # Now do one with a really old timestamp.
     ts = str(int(time.time() - 1000))
     req.authorization = ("MAC", {"ts": ts})
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)
Exemplo n.º 24
0
 def test_that_macauth_is_used_by_default(self):
     # Generate signed request.
     req = self.make_request()
     tokenid, key = self.policy.encode_mac_id(req, 42)
     macauthlib.sign_request(req, tokenid, key)
     # That should be enough to authenticate.
     self.assertEquals(authenticated_userid(req), 42)
     self.assertEquals(req.user.get("uid"), 42)
     # Check that it rejects invalid MAC ids.
     req = self.make_request()
     macauthlib.sign_request(req, tokenid, key)
     authz = req.environ["HTTP_AUTHORIZATION"]
     req.environ["HTTP_AUTHORIZATION"] = authz.replace(tokenid, "XXXXXX")
     self.assertRaises(HTTPUnauthorized, authenticated_userid, req)
     # And that the rejection gets raised when accessing request.user
     self.assertRaises(HTTPUnauthorized, getattr, req, "user")
Exemplo n.º 25
0
 def test_that_macauth_is_used_by_default(self):
     # Generate signed request.
     req = self.make_request()
     tokenid, key = self.policy.encode_mac_id(req, 42)
     macauthlib.sign_request(req, tokenid, key)
     # That should be enough to authenticate.
     self.assertEquals(authenticated_userid(req), 42)
     self.assertEquals(req.user.get("uid"), 42)
     # Check that it rejects invalid MAC ids.
     req = self.make_request()
     macauthlib.sign_request(req, tokenid, key)
     authz = req.environ["HTTP_AUTHORIZATION"]
     req.environ["HTTP_AUTHORIZATION"] = authz.replace(tokenid, "XXXXXX")
     self.assertRaises(HTTPUnauthorized, authenticated_userid, req)
     # And that the rejection gets raised when accessing request.user
     self.assertRaises(HTTPUnauthorized, getattr, req, "user")
Exemplo n.º 26
0
 def test_passing_filelike_as_request_object(self):
     req = StringIO.StringIO(TEST_REQ)
     assert not check_signature(req, TEST_KEY, nonces=False)
     req = StringIO.StringIO(TEST_REQ)
     authz = sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     req = StringIO.StringIO(TEST_REQ_SIGNED)
     assert check_signature(req, TEST_KEY, nonces=False)
Exemplo n.º 27
0
 def test_passing_filelike_as_request_object(self):
     req = StringIO.StringIO(TEST_REQ)
     assert not check_signature(req, TEST_KEY, nonces=False)
     req = StringIO.StringIO(TEST_REQ)
     authz = sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     req = StringIO.StringIO(TEST_REQ_SIGNED)
     assert check_signature(req, TEST_KEY, nonces=False)
Exemplo n.º 28
0
 def test_that_macauth_is_used_by_default(self):
     # Grab the MACAuth plugin so we can sign requests.
     policy = self.config.registry.queryUtility(IAuthenticationPolicy)
     api_factory = policy.api_factory
     mac_plugin = api_factory.authenticators[1][1]
     # Generate signed request.
     req = self._make_request()
     id, key = mac_plugin.encode_mac_id(req, {"userid": 42})
     macauthlib.sign_request(req, id, key)
     # That should be enough to authenticate.
     self.assertEquals(authenticated_userid(req), 42)
     # Check that it rejects invalid MAC ids.
     req = self._make_request()
     macauthlib.sign_request(req, id, key)
     authz = req.environ["HTTP_AUTHORIZATION"]
     req.environ["HTTP_AUTHORIZATION"] = authz.replace(id, "XXX" + id)
     self.assertRaises(Exception, authenticated_userid, req)
 def test_access_to_public_urls(self):
     # Request with no credentials is allowed access.
     req = Request.blank("/public")
     resp = self.app.request(req)
     self.assertEquals(resp.body, "public")
     # Request with valid credentials is allowed access.
     creds = self._get_credentials(username="******")
     req = Request.blank("/public")
     macauthlib.sign_request(req, **creds)
     resp = self.app.request(req)
     self.assertEquals(resp.body, "public")
     # Request with invalid credentials gets a 401.
     req = Request.blank("/public")
     macauthlib.sign_request(req, **creds)
     signature = macauthlib.utils.parse_authz_header(req)["mac"]
     authz = req.environ["HTTP_AUTHORIZATION"]
     authz = authz.replace(signature, "XXX" + signature)
     req.environ["HTTP_AUTHORIZATION"] = authz
     resp = self.app.request(req, status=401)
Exemplo n.º 30
0
 def _browse(self, url_in, params_in=None, description=None, ok_codes=None,
             method='post', *args, **kwds):
     # Automatically add a fresh MACAuth header to the request.
     if self.auth_token is not None:
         req = Request.blank(url_in)
         req.method = method.upper()
         if params_in and req.method in ("GET", "HEAD",):
             qs_items = ("%s=%s" % item for item in params_in.iteritems())
             req.query_string = "&".join(qs_items)
         macauthlib.sign_request(req, self.auth_token, self.auth_secret)
         self.setHeader("Authorization", req.environ["HTTP_AUTHORIZATION"])
     # Log the start and end of the request, for debugging purposes.
     args = (url_in, params_in, description, ok_codes, method) + args
     self.logi("%s: %s" % (method.upper(), url_in))
     try:
         result = super(StressTest, self)._browse(*args, **kwds)
     except Exception, e:
         self.logi("    FAIL: " + url_in + " " + repr(e))
         raise
 def test_access_to_public_urls(self):
     # Request with no credentials is allowed access.
     req = Request.blank("/public")
     resp = self.app.request(req)
     self.assertEquals(resp.body, "public")
     # Request with valid credentials is allowed access.
     creds = self._get_credentials(username="******")
     req = Request.blank("/public")
     macauthlib.sign_request(req, **creds)
     resp = self.app.request(req)
     self.assertEquals(resp.body, "public")
     # Request with invalid credentials gets a 401.
     req = Request.blank("/public")
     macauthlib.sign_request(req, **creds)
     signature = macauthlib.utils.parse_authz_header(req)["mac"]
     authz = req.environ["HTTP_AUTHORIZATION"]
     authz = authz.replace(signature, "XXX" + signature)
     req.environ["HTTP_AUTHORIZATION"] = authz
     resp = self.app.request(req, status=401)
Exemplo n.º 32
0
 def test_passing_requests_request_as_request_object(self):
     req = requests.Request(
         url="http://example.com/resource/1",
         method="POST",
         params=[("b", "1"), ("a", "2")],
         data="hello world",
     )
     assert not check_signature(req, TEST_KEY, nonces=False)
     authz = sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     assert check_signature(req, TEST_KEY, nonces=False)
Exemplo n.º 33
0
 def test_passing_requests_request_as_request_object(self):
     req = requests.Request(
         url="http://example.com/resource/1",
         method="POST",
         params=[("b", "1"), ("a", "2")],
         data="hello world",
     )
     assert not check_signature(req, TEST_KEY, nonces=False)
     authz = sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     assert check_signature(req, TEST_KEY, nonces=False)
Exemplo n.º 34
0
 def test_passing_environ_dict_as_request_object(self):
     req = {
         "wsgi.url_scheme": "http",
         "REQUEST_METHOD": "POST",
         "HTTP_HOST": "example.com",
         "HTTP_CONTENT_LENGTH": "11",
         "PATH_INFO": "/resource/1",
         "QUERY_STRING": "b=1&a=2",
         "wsgi.input": StringIO.StringIO("hello world")
     }
     assert not check_signature(req, TEST_KEY, nonces=False)
     authz = sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     assert check_signature(req, TEST_KEY, nonces=False)
Exemplo n.º 35
0
 def test_passing_environ_dict_as_request_object(self):
     req = {
         "wsgi.url_scheme": "http",
         "REQUEST_METHOD": "POST",
         "HTTP_HOST": "example.com",
         "HTTP_CONTENT_LENGTH": "11",
         "PATH_INFO": "/resource/1",
         "QUERY_STRING": "b=1&a=2",
         "wsgi.input": StringIO.StringIO("hello world")
     }
     assert not check_signature(req, TEST_KEY, nonces=False)
     authz = sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     assert check_signature(req, TEST_KEY, nonces=False)
Exemplo n.º 36
0
def send_job(repo, server, cycles='', duration='', nodes='', redirect_url=''):
    mac_user = os.environ.get('MACAUTH_USER')
    mac_secret = os.environ.get('MACAUTH_SECRET')
    request = Request.blank(server.rstrip('/') + '/test')
    request.method = 'POST'
    params = {'repo': repo, 'cycles': cycles, 'duration': duration,
              'nodes': nodes, 'redirect_url': redirect_url,
              'api_call': 1}

    request.body = urllib.urlencode(params)
    request.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

    if mac_user is not None:
        tokenid = tokenlib.make_token({"user": mac_user}, secret=mac_secret)
        key = tokenlib.get_token_secret(tokenid, secret=mac_secret)
        sign_request(request, tokenid, key)

    resp = request.get_response(proxy_exact_request)
    if resp.status_int == 401:
        raise ValueError("Authorization Failed!")

    job_id = resp.json['job_id']
    return server.rstrip('/') + '/test/' + job_id
 def test_authenticated_request_works(self):
     creds = self._get_credentials(username="******")
     req = Request.blank("/")
     macauthlib.sign_request(req, **creds)
     r = self.app.request(req)
     self.assertEquals(r.body, "*****@*****.**")
Exemplo n.º 38
0
 def __call__(self, req):
     sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert check_signature(req, TEST_KEY, nonces=False)
     assert TEST_SIG in req.headers['Authorization']
     raise RuntimeError("aborting the request")
Exemplo n.º 39
0
 def pre_request_hook(req):
     sign_request(req, TEST_ID, TEST_KEY)
     assert check_signature(req, TEST_KEY, nonces=False)
     raise RuntimeError("aborting the request")
Exemplo n.º 40
0
def auth_hook(req):
    macauthlib.sign_request(req, **CREDENTIALS)
    return req
Exemplo n.º 41
0
 def test_that_macauth_can_use_per_node_hostname_secrets(self):
     with tempfile.NamedTemporaryFile() as sf:
         # Write some secrets to a file.
         sf.write("http://host1.com,0001:secret11,0002:secret12\n")
         sf.write("https://host2.com,0001:secret21,0002:secret22\n")
         sf.write("https://host3.com:444,0001:secret31,0002:secret32\n")
         sf.flush()
         # Configure the plugin to load them.
         config2 = pyramid.testing.setUp()
         config2.add_settings(DEFAULT_SETTINGS)
         config2.add_settings({
             "macauth.secrets_file": sf.name,
         })
         config2.include("mozsvc.user")
         config2.commit()
         # It should accept a request signed with the old secret on host1.
         req = self.make_request(config=config2,
                                 environ={
                                     "HTTP_HOST": "host1.com",
                                 })
         id = tokenlib.make_token({"uid": 42}, secret="secret11")
         key = tokenlib.get_token_secret(id, secret="secret11")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request signed with the new secret on host1.
         req = self.make_request(config=config2,
                                 environ={
                                     "HTTP_HOST": "host1.com",
                                 })
         id = tokenlib.make_token({"uid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should reject a request signed with secret from other host.
         req = self.make_request(config=config2,
                                 environ={
                                     "HTTP_HOST": "host2.com",
                                 })
         id = tokenlib.make_token({"uid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertRaises(HTTPUnauthorized, authenticated_userid, req)
         # It should reject a request over plain http when host2 is ssl.
         req = self.make_request(config=config2,
                                 environ={
                                     "HTTP_HOST": "host2.com",
                                 })
         id = tokenlib.make_token({"uid": 42}, secret="secret22")
         key = tokenlib.get_token_secret(id, secret="secret22")
         macauthlib.sign_request(req, id, key)
         self.assertRaises(HTTPUnauthorized, authenticated_userid, req)
         # It should accept a request signed with the new secret on host2.
         req = self.make_request(config=config2,
                                 environ={
                                     "HTTP_HOST": "host2.com",
                                     "wsgi.url_scheme": "https",
                                 })
         id = tokenlib.make_token({"uid": 42}, secret="secret22")
         key = tokenlib.get_token_secret(id, secret="secret22")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request to host1 with an explicit port number.
         # Use some trickery to give host_url a value with default port.
         req = ExpandoRequest(
             self.make_request(config=config2,
                               environ={
                                   "HTTP_HOST": "host1.com:80",
                                   "wsgi.url_scheme": "http",
                               }))
         req.host_url = "http://host1.com:80"
         id = tokenlib.make_token({"uid": 42}, secret="secret11")
         key = tokenlib.get_token_secret(id, secret="secret11")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request to host2 with an explicit port number.
         # Use some trickery to give host_url a value with default port.
         req = ExpandoRequest(
             self.make_request(config=config2,
                               environ={
                                   "HTTP_HOST": "host2.com:443",
                                   "wsgi.url_scheme": "https",
                               }))
         req.host_url = "https://host2.com:443"
         id = tokenlib.make_token({"uid": 42}, secret="secret22")
         key = tokenlib.get_token_secret(id, secret="secret22")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request to host3 on a custom port.
         req = self.make_request(config=config2,
                                 environ={
                                     "HTTP_HOST": "host3.com:444",
                                     "wsgi.url_scheme": "https",
                                 })
         id = tokenlib.make_token({"uid": 42}, secret="secret32")
         key = tokenlib.get_token_secret(id, secret="secret32")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should reject unknown hostnames.
         req = self.make_request(config=config2,
                                 environ={
                                     "HTTP_HOST": "host4.com",
                                 })
         id = tokenlib.make_token({"uid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertRaises(HTTPUnauthorized, authenticated_userid, req)
Exemplo n.º 42
0
 def test_authentication_fails_when_macid_has_no_userid(self):
     req = self._make_request("/auth")
     creds = self._get_credentials(req, hello="world")
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)
Exemplo n.º 43
0
 def new_do_request(req, *args, **kwds):
     macauthlib.sign_request(req, self.auth_token, self.auth_secret)
     return orig_do_request(req, *args, **kwds)
Exemplo n.º 44
0
 def test_check_signature_fails_with_non_mac_scheme(self):
     req = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
     req = Request.from_bytes(req)
     sign_request(req, "myid", "mykey")
     req.authorization = ("OAuth", req.authorization[1])
     self.assertFalse(check_signature(req, "mykey"))
Exemplo n.º 45
0
 def test_sign_request_throws_away_other_auth_params(self):
     req = Request.blank("/")
     req.authorization = ("Digest", {"response": "helloworld"})
     sign_request(req, "id", "key")
     self.assertEquals(req.authorization[0], "MAC")
Exemplo n.º 46
0
 def test_passing_webob_request_as_request_object(self):
     req = webob.Request.from_bytes(TEST_REQ)
     assert not check_signature(req, TEST_KEY, nonces=False)
     authz = sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     assert check_signature(req, TEST_KEY, nonces=False)
Exemplo n.º 47
0
 def test_check_signature_fails_with_non_mac_scheme(self):
     req = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
     req = Request.from_bytes(req)
     sign_request(req, "myid", "mykey")
     req.authorization = ("OAuth", req.authorization[1])
     self.assertFalse(check_signature(req, "mykey"))
Exemplo n.º 48
0
 def new_do_request(req, *args, **kwds):
     macauthlib.sign_request(req, self.auth_token, self.auth_secret)
     return orig_do_request(req, *args, **kwds)
Exemplo n.º 49
0
 def test_that_req_user_can_be_replaced(self):
     req = self.make_request()
     tokenid, key = self.policy.encode_mac_id(req, 42)
     macauthlib.sign_request(req, tokenid, key)
     req.user = {"uid": 7}
     self.assertEquals(req.user, {"uid": 7})
 def test_authenticated_request_works(self):
     creds = self._get_credentials(username="******")
     req = Request.blank("/")
     macauthlib.sign_request(req, **creds)
     r = self.app.request(req)
     self.assertEquals(r.body, "*****@*****.**")
Exemplo n.º 51
0
 def pre_request_hook(req):
     sign_request(req, TEST_ID, TEST_KEY)
     assert check_signature(req, TEST_KEY, nonces=False)
     raise RuntimeError("aborting the request")
 def test_authentication_fails_when_macid_has_no_userid(self):
     creds = self._get_credentials(hello="world")
     req = Request.blank("/")
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)
Exemplo n.º 53
0
 def test_passing_bytestring_as_request_object(self):
     assert not check_signature(TEST_REQ, TEST_KEY, nonces=False)
     authz = sign_request(TEST_REQ, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     assert check_signature(TEST_REQ_SIGNED, TEST_KEY, nonces=False)
Exemplo n.º 54
0
 def _make_signed_request(self, userid, *args, **kwds):
     req = self._make_request(*args, **kwds)
     creds = self._get_credentials(req, userid=userid)
     macauthlib.sign_request(req, **creds)
     return req
Exemplo n.º 55
0
 def test_passing_webob_request_as_request_object(self):
     req = webob.Request.from_bytes(TEST_REQ)
     assert not check_signature(req, TEST_KEY, nonces=False)
     authz = sign_request(req, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     assert check_signature(req, TEST_KEY, nonces=False)
Exemplo n.º 56
0
 def test_that_macauth_can_use_per_node_hostname_secrets(self):
     with tempfile.NamedTemporaryFile() as sf:
         # Write some secrets to a file.
         sf.write("http://host1.com,0001:secret11,0002:secret12\n")
         sf.write("https://host2.com,0001:secret21,0002:secret22\n")
         sf.write("https://host3.com:444,0001:secret31,0002:secret32\n")
         sf.flush()
         # Configure the plugin to load them.
         config2 = pyramid.testing.setUp()
         config2.add_settings(DEFAULT_SETTINGS)
         config2.add_settings({
             "macauth.secrets_file": sf.name,
         })
         config2.include("mozsvc.user")
         config2.commit()
         # It should accept a request signed with the old secret on host1.
         req = self.make_request(config=config2, environ={
             "HTTP_HOST": "host1.com",
         })
         id = tokenlib.make_token({"uid": 42}, secret="secret11")
         key = tokenlib.get_token_secret(id, secret="secret11")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request signed with the new secret on host1.
         req = self.make_request(config=config2, environ={
             "HTTP_HOST": "host1.com",
         })
         id = tokenlib.make_token({"uid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should reject a request signed with secret from other host.
         req = self.make_request(config=config2, environ={
             "HTTP_HOST": "host2.com",
         })
         id = tokenlib.make_token({"uid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertRaises(HTTPUnauthorized, authenticated_userid, req)
         # It should reject a request over plain http when host2 is ssl.
         req = self.make_request(config=config2, environ={
             "HTTP_HOST": "host2.com",
         })
         id = tokenlib.make_token({"uid": 42}, secret="secret22")
         key = tokenlib.get_token_secret(id, secret="secret22")
         macauthlib.sign_request(req, id, key)
         self.assertRaises(HTTPUnauthorized, authenticated_userid, req)
         # It should accept a request signed with the new secret on host2.
         req = self.make_request(config=config2, environ={
             "HTTP_HOST": "host2.com",
             "wsgi.url_scheme": "https",
         })
         id = tokenlib.make_token({"uid": 42}, secret="secret22")
         key = tokenlib.get_token_secret(id, secret="secret22")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request to host1 with an explicit port number.
         # Use some trickery to give host_url a value with default port.
         req = ExpandoRequest(self.make_request(config=config2, environ={
             "HTTP_HOST": "host1.com:80",
             "wsgi.url_scheme": "http",
         }))
         req.host_url = "http://host1.com:80"
         id = tokenlib.make_token({"uid": 42}, secret="secret11")
         key = tokenlib.get_token_secret(id, secret="secret11")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request to host2 with an explicit port number.
         # Use some trickery to give host_url a value with default port.
         req = ExpandoRequest(self.make_request(config=config2, environ={
             "HTTP_HOST": "host2.com:443",
             "wsgi.url_scheme": "https",
         }))
         req.host_url = "https://host2.com:443"
         id = tokenlib.make_token({"uid": 42}, secret="secret22")
         key = tokenlib.get_token_secret(id, secret="secret22")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should accept a request to host3 on a custom port.
         req = self.make_request(config=config2, environ={
             "HTTP_HOST": "host3.com:444",
             "wsgi.url_scheme": "https",
         })
         id = tokenlib.make_token({"uid": 42}, secret="secret32")
         key = tokenlib.get_token_secret(id, secret="secret32")
         macauthlib.sign_request(req, id, key)
         self.assertEquals(authenticated_userid(req), 42)
         # It should reject unknown hostnames.
         req = self.make_request(config=config2, environ={
             "HTTP_HOST": "host4.com",
         })
         id = tokenlib.make_token({"uid": 42}, secret="secret12")
         key = tokenlib.get_token_secret(id, secret="secret12")
         macauthlib.sign_request(req, id, key)
         self.assertRaises(HTTPUnauthorized, authenticated_userid, req)
Exemplo n.º 57
0
 def test_passing_bytestring_as_request_object(self):
     assert not check_signature(TEST_REQ, TEST_KEY, nonces=False)
     authz = sign_request(TEST_REQ, TEST_ID, TEST_KEY, params=TEST_PARAMS)
     assert TEST_SIG in authz
     assert check_signature(TEST_REQ_SIGNED, TEST_KEY, nonces=False)
Exemplo n.º 58
0
 def test_that_req_user_can_be_replaced(self):
     req = self.make_request()
     tokenid, key = self.policy.encode_mac_id(req, 42)
     macauthlib.sign_request(req, tokenid, key)
     req.user = {"uid": 7}
     self.assertEquals(req.user, {"uid": 7})
Exemplo n.º 59
0
 def test_sign_request_throws_away_other_auth_params(self):
     req = Request.blank("/")
     req.authorization = ("Digest", {"response": "helloworld"})
     sign_request(req, "id", "key")
     self.assertEquals(req.authorization[0], "MAC")
 def test_authentication_fails_when_macid_has_no_userid(self):
     creds = self._get_credentials(hello="world")
     req = Request.blank("/")
     macauthlib.sign_request(req, **creds)
     self.app.request(req, status=401)