def test_token_taken_from_argument(self):
     auth_backend = MemoryAuthBackend([])
     cmd = self.make_command(auth_backend,
                             HOST='http://*****:*****@example.com/RPC2/',
                             no_check=True)
     cmd.invoke()
     self.assertEqual(
         'TOKEN',
         auth_backend.get_token_for_endpoint('user',
                                             'http://example.com/RPC2/'))
 def test_path_on_server_recorded(self):
     auth_backend = MemoryAuthBackend([])
     cmd = self.make_command(auth_backend,
                             HOST='https://*****:*****@example.com/path',
                             no_check=True)
     cmd.invoke()
     self.assertEqual(
         'TOKEN',
         auth_backend.get_token_for_endpoint(
             'user', 'https://example.com/path/RPC2/'))
Exemple #3
0
def _get_dashboard(server, token):
    if not server.endswith("/"):
        server = ''.join([server, "/"])

    # add backward compatible for 'dashboard/'-end URL
    # Fix it: it's going to be deleted after transition
    if server.endswith("dashboard/"):
        server = ''.join([server, "xml-rpc/"])
        logging.warning(
            "Please use whole endpoint URL not just end with 'dashboard/', "
            "'xml-rpc/' is added automatically now!!!")

    parsed_server = urlparse.urlparse(server)
    auth_backend = MemoryAuthBackend([])
    if parsed_server.username:
        if token:
            userless_server = '%s://%s' % (parsed_server.scheme,
                                           parsed_server.hostname)
            if parsed_server.port:
                userless_server += ':' + str(parsed_server.port)
            userless_server += parsed_server.path
            auth_backend = MemoryAuthBackend([(parsed_server.username,
                                               userless_server, token)])
        else:
            logging.warning(
                "specifying a user without a token is unlikely to work")
    else:
        if token:
            logging.warning(
                "specifying a token without a user is probably useless")

    srv = AuthenticatingServerProxy(server,
                                    allow_none=True,
                                    use_datetime=True,
                                    auth_backend=auth_backend)
    if server.endswith("xml-rpc/"):
        logging.error(
            "Please use RPC2 endpoint instead, xml-rpc is no longer supported")
        raise OperationFailed("xml-rpc endpoint is not supported.")
    elif server.endswith("RPC2/"):
        # include lava-server/RPC2/
        dashboard = srv.dashboard
    else:
        logging.warning(
            "The url seems not RPC2 or xml-rpc endpoints, please make sure it's a valid one!!!"
        )
        dashboard = srv.dashboard

    logging.debug("server RPC endpoint URL: %s" % server)
    return dashboard
 def test_token_taken_from_file(self):
     auth_backend = MemoryAuthBackend([])
     token_file = tempfile.NamedTemporaryFile('w')
     token_file.write("TOKEN")
     token_file.flush()
     cmd = self.make_command(auth_backend,
                             HOST='http://[email protected]',
                             no_check=True,
                             token_file=token_file.name)
     cmd.invoke()
     self.assertEqual(
         'TOKEN',
         auth_backend.get_token_for_endpoint('user',
                                             'http://example.com/RPC2/'))
 def test_token_taken_from_getpass(self):
     mocked_getpass = self.mocker.replace('getpass.getpass',
                                          passthrough=False)
     mocked_getpass(CONTAINS('Paste token'))
     self.mocker.result("TOKEN")
     self.mocker.replay()
     auth_backend = MemoryAuthBackend([])
     cmd = self.make_command(auth_backend,
                             HOST='http://[email protected]',
                             no_check=True)
     cmd.invoke()
     self.assertEqual(
         'TOKEN',
         auth_backend.get_token_for_endpoint('user',
                                             'http://example.com/RPC2/'))
    def invoke(self):
        uri = normalize_xmlrpc_url(self.args.HOST)
        parsed_host = urlparse.urlparse(uri)

        if parsed_host.username:
            username = parsed_host.username
        else:
            username = getpass.getuser()

        host = parsed_host.hostname
        if parsed_host.port:
            host += ':' + str(parsed_host.port)

        uri = '%s://%s@%s%s' % (parsed_host.scheme, username, host,
                                parsed_host.path)

        if self.args.token_file:
            if parsed_host.password:
                raise LavaCommandError(
                    "Token specified in url but --token-file also passed.")
            else:
                try:
                    token_file = open(self.args.token_file)
                except IOError as ex:
                    raise LavaCommandError("opening %r failed: %s" %
                                           (self.args.token_file, ex))
                token = token_file.read().strip()
        else:
            if parsed_host.password:
                token = parsed_host.password
            else:
                token = getpass.getpass("Paste token for %s: " % uri)

        userless_uri = '%s://%s%s' % (parsed_host.scheme, host,
                                      parsed_host.path)

        if not self.args.no_check:
            sp = AuthenticatingServerProxy(uri,
                                           auth_backend=MemoryAuthBackend([
                                               (username, userless_uri, token)
                                           ]))
            try:
                token_user = sp.system.whoami()
            except xmlrpclib.ProtocolError as ex:
                if ex.errcode == 401:
                    raise LavaCommandError(
                        "Token rejected by server for user %s." % username)
                else:
                    raise
            except xmlrpclib.Fault as ex:
                raise LavaCommandError(
                    "Server reported error during check: %s." % ex)
            if token_user != username:
                raise LavaCommandError(
                    "whoami() returned %s rather than expected %s -- this is "
                    "a bug." % (token_user, username))

        self.auth_backend.add_token(username, userless_uri, token)

        print 'Token added successfully for user %s.' % username
 def test_token_file_and_in_url_conflict(self):
     auth_backend = MemoryAuthBackend([])
     cmd = self.make_command(auth_backend,
                             HOST='http://*****:*****@example.com',
                             no_check=True,
                             token_file='some-file-name')
     self.assertRaises(LavaCommandError, cmd.invoke)
Exemple #8
0
def _get_scheduler_rpc():
    """Returns the scheduler xmlrpc AuthicatingServerProxy object.
    """
    username = '******'  # We assume this user exists always.
    user = User.objects.get(username=username)
    rpc2_url = Worker.get_rpc2_url()

    try:
        token = AuthToken.objects.filter(user=user)[0]
    except IndexError:
        token = AuthToken.objects.create(user=user)
        token.save()

    parsed_server = urlparse.urlparse(rpc2_url)
    server = '{0}://{1}:{2}@{3}'.format(parsed_server.scheme, username,
                                        token.secret, parsed_server.hostname)
    if parsed_server.port:
        server += ':' + str(parsed_server.port)
    server += parsed_server.path

    auth_backend = MemoryAuthBackend([(username, rpc2_url, token.secret)])
    server = AuthenticatingServerProxy(server, auth_backend=auth_backend)
    server = server.scheduler

    return server
 def test_non_existent_token_reported(self):
     auth_backend = MemoryAuthBackend([])
     cmd = self.make_command(auth_backend,
                             HOST='http://*****:*****@example.com',
                             no_check=True,
                             token_file='does-not-exist')
     self.assertRaises(LavaCommandError, cmd.invoke)
Exemple #10
0
 def test_port_included(self):
     auth_headers = self.auth_headers_for_method_call_on(
         'http://user@localhost:1234/RPC2/',
         MemoryAuthBackend([('user', 'http://localhost:1234/RPC2/', 'TOKEN')
                            ]))
     self.assertEqual(('user', 'TOKEN'),
                      self.user_and_password_from_auth_data(auth_headers))
 def test_check_fails_token_not_recorded(self):
     mocked_AuthenticatingServerProxy = self.mocker.replace(
         'lava_tool.authtoken.AuthenticatingServerProxy', passthrough=False)
     mocked_sp = mocked_AuthenticatingServerProxy(ARGS, KWARGS)
     self.mocker.nospec()
     mocked_sp.system.whoami()
     self.mocker.throw(xmlrpclib.ProtocolError('', 401, '', []))
     self.mocker.replay()
     auth_backend = MemoryAuthBackend([])
     cmd = self.make_command(auth_backend,
                             HOST='http://*****:*****@example.com',
                             no_check=False)
     self.assertRaises(LavaCommandError, cmd.invoke)
     self.assertEqual(
         None,
         auth_backend.get_token_for_endpoint('user',
                                             'http://example.com/RPC2/'))
 def test_check_made(self):
     mocked_AuthenticatingServerProxy = self.mocker.replace(
         'lava_tool.authtoken.AuthenticatingServerProxy', passthrough=False)
     mocked_sp = mocked_AuthenticatingServerProxy(ARGS, KWARGS)
     # nospec() is required because of
     # https://bugs.launchpad.net/mocker/+bug/794351
     self.mocker.nospec()
     mocked_sp.system.whoami()
     self.mocker.result('user')
     self.mocker.replay()
     auth_backend = MemoryAuthBackend([])
     cmd = self.make_command(auth_backend,
                             HOST='http://*****:*****@example.com',
                             no_check=False)
     cmd.invoke()
     self.assertEqual(
         'TOKEN',
         auth_backend.get_token_for_endpoint('user',
                                             'http://example.com/RPC2/'))
 def test_user_taken_from_getuser(self):
     mocked_getuser = self.mocker.replace('getpass.getuser',
                                          passthrough=False)
     mocked_getuser()
     self.mocker.result("user")
     self.mocker.replay()
     auth_backend = MemoryAuthBackend([])
     token_file = tempfile.NamedTemporaryFile('w')
     token_file.write("TOKEN")
     token_file.flush()
     cmd = self.make_command(auth_backend,
                             HOST='http://example.com',
                             no_check=True,
                             token_file=token_file.name)
     cmd.invoke()
     self.assertEqual(
         'TOKEN',
         auth_backend.get_token_for_endpoint('user',
                                             'http://example.com/RPC2/'))
 def test_fault_reported(self):
     mocked_AuthenticatingServerProxy = self.mocker.replace(
         'lava_tool.authtoken.AuthenticatingServerProxy', passthrough=False)
     mocked_sp = mocked_AuthenticatingServerProxy(ARGS, KWARGS)
     # nospec() is required because of
     # https://bugs.launchpad.net/mocker/+bug/794351
     self.mocker.nospec()
     mocked_sp.system.whoami()
     self.mocker.throw(xmlrpclib.Fault(100, 'faultString'))
     self.mocker.replay()
     auth_backend = MemoryAuthBackend([])
     cmd = self.make_command(auth_backend,
                             HOST='http://*****:*****@example.com',
                             no_check=False)
     self.assertRaises(LavaCommandError, cmd.invoke)
Exemple #15
0
 def test_no_user_no_auth(self):
     auth_headers = self.auth_headers_for_method_call_on(
         'http://localhost/RPC2/', MemoryAuthBackend([]))
     self.assertEqual([], auth_headers)
Exemple #16
0
 def test_token_used_for_auth_https(self):
     auth_headers = self.auth_headers_for_method_call_on(
         'https://user@localhost/RPC2/',
         MemoryAuthBackend([('user', 'https://localhost/RPC2/', 'TOKEN')]))
     self.assertEqual(('user', 'TOKEN'),
                      self.user_and_password_from_auth_data(auth_headers))
Exemple #17
0
 def test_error_when_user_but_no_token(self):
     self.assertRaises(LavaCommandError,
                       self.auth_headers_for_method_call_on,
                       'http://user@localhost/RPC2/', MemoryAuthBackend([]))