Beispiel #1
0
def test_api_token_auth_with_v2_url():
    token = GalaxyToken(token=u"my_token")
    api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=token)
    actual = {}
    # Add v3 to random part of URL but response should only see the v2 as the full URI path segment.
    api._add_auth_token(actual, "https://galaxy.ansible.com/api/v2/resourcev3/name", required=True)
    assert actual == {'Authorization': 'Token my_token'}
Beispiel #2
0
    def __init__(self, galaxy):

        self.galaxy = galaxy
        self.token = GalaxyToken()
        self._api_server = C.GALAXY_SERVER
        self._validate_certs = C.GALAXY_IGNORE_CERTS

        # set validate_certs
        if galaxy.options.validate_certs == False:
            self._validate_certs = False
        display.vvv('Check for valid certs: %s' % self._validate_certs)

        # set the API server
        if galaxy.options.api_server != C.GALAXY_SERVER:
            self._api_server = galaxy.options.api_server
        display.vvv("Connecting to galaxy_server: %s" % self._api_server)

        server_version = self.get_server_api_version()
       
        if server_version in self.SUPPORTED_VERSIONS:
            self.baseurl = '%s/api/%s' % (self._api_server, server_version)
            self.version = server_version # for future use
            display.vvv("Base API: %s" % self.baseurl)
        else:
            raise AnsibleError("Unsupported Galaxy server API version: %s" % server_version)
Beispiel #3
0
def test_initialise_galaxy_with_auth(monkeypatch):
    mock_open = MagicMock()
    mock_open.side_effect = [
        StringIO(u'{"available_versions":{"v1":"v1/"}}'),
        StringIO(u'{"token":"my token"}'),
    ]
    monkeypatch.setattr(galaxy_api, 'open_url', mock_open)

    api = GalaxyAPI(None,
                    "test",
                    "https://galaxy.ansible.com/api/",
                    token=GalaxyToken(token='my_token'))
    actual = api.authenticate("github_token")

    assert len(api.available_api_versions) == 2
    assert api.available_api_versions['v1'] == u'v1/'
    assert api.available_api_versions['v2'] == u'v2/'
    assert actual == {u'token': u'my token'}
    assert mock_open.call_count == 2
    assert mock_open.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api/'
    assert 'ansible-galaxy' in mock_open.mock_calls[0][2]['http_agent']
    assert mock_open.mock_calls[1][1][
        0] == 'https://galaxy.ansible.com/api/v1/tokens/'
    assert 'ansible-galaxy' in mock_open.mock_calls[1][2]['http_agent']
    assert mock_open.mock_calls[1][2]['data'] == 'github_token=github_token'
Beispiel #4
0
def test_api_token_auth_with_v3_url():
    token = GalaxyToken(token=u"my_token")
    api = GalaxyAPI(None, "test", "https://galaxy.ansible.com", token=token)
    actual = {}
    api._add_auth_token(actual,
                        "https://galaxy.ansible.com/api/v3/resource/name")
    assert actual == {'Authorization': 'Bearer my_token'}
Beispiel #5
0
def test_initialise_automation_hub(monkeypatch):
    mock_open = MagicMock()
    mock_open.side_effect = [
        urllib_error.HTTPError('https://galaxy.ansible.com/api', 401, 'msg',
                               {}, StringIO()),
        # AH won't return v1 but we do for authenticate() to work.
        StringIO(u'{"available_versions":{"v1":"/api/v1","v3":"/api/v3"}}'),
        StringIO(u'{"token":"my token"}'),
    ]
    monkeypatch.setattr(galaxy_api, 'open_url', mock_open)

    api = GalaxyAPI(None,
                    "test",
                    "https://galaxy.ansible.com",
                    token=GalaxyToken(token='my_token'))
    actual = api.authenticate("github_token")

    assert len(api.available_api_versions) == 2
    assert api.available_api_versions['v1'] == u'/api/v1'
    assert api.available_api_versions['v3'] == u'/api/v3'
    assert actual == {u'token': u'my token'}
    assert mock_open.call_count == 3
    assert mock_open.mock_calls[0][1][0] == 'https://galaxy.ansible.com/api'
    assert mock_open.mock_calls[0][2]['headers'] == {
        'Authorization': 'Token my_token'
    }
    assert mock_open.mock_calls[1][1][0] == 'https://galaxy.ansible.com/api'
    assert mock_open.mock_calls[1][2]['headers'] == {
        'Authorization': 'Bearer my_token'
    }
    assert mock_open.mock_calls[2][1][
        0] == 'https://galaxy.ansible.com/api/v1/tokens/'
    assert mock_open.mock_calls[2][2]['data'] == 'github_token=github_token'
Beispiel #6
0
    def execute_login(self):
        """
        verify user's identify via Github and retrieve an auth token from Ansible Galaxy.
        """
        # Authenticate with github and retrieve a token
        if self.options.token is None:
            if C.GALAXY_TOKEN:
                github_token = C.GALAXY_TOKEN
            else:
                login = GalaxyLogin(self.galaxy)
                github_token = login.create_github_token()
        else:
            github_token = self.options.token

        galaxy_response = self.api.authenticate(github_token)

        if self.options.token is None and C.GALAXY_TOKEN is None:
            # Remove the token we created
            login.remove_github_token()

        # Store the Galaxy token
        token = GalaxyToken()
        token.set(galaxy_response['token'])

        display.display("Successfully logged into Galaxy as %s" %
                        galaxy_response['username'])
        return 0
Beispiel #7
0
def get_test_galaxy_api(url, version, token_ins=None, token_value=None):
    token_value = token_value or "my token"
    token_ins = token_ins or GalaxyToken(token_value)
    api = GalaxyAPI(None, "test", url)
    api._available_api_versions = {version: '/api/%s' % version}
    api.token = token_ins

    return api
Beispiel #8
0
def test_api_token_auth():
    token = GalaxyToken(token=u"my_token")
    api = GalaxyAPI(None,
                    "test",
                    "https://galaxy.ansible.com/api/",
                    token=token)
    actual = {}
    api._add_auth_token(actual, "", required=True)
    assert actual == {'Authorization': 'Token my_token'}
Beispiel #9
0
def get_test_galaxy_api(url, version, token_ins=None, token_value=None):
    token_value = token_value or "my token"
    token_ins = token_ins or GalaxyToken(token_value)
    api = GalaxyAPI(None, "test", url)
    # Warning, this doesn't test g_connect() because _availabe_api_versions is set here.  That means
    # that urls for v2 servers have to append '/api/' themselves in the input data.
    api._available_api_versions = {version: '%s' % version}
    api.token = token_ins

    return api
Beispiel #10
0
    def execute_publish(self):
        """
        Publish a collection into Ansible Galaxy.
        """
        api_key = context.CLIARGS['api_key'] or GalaxyToken().get()
        api_server = context.CLIARGS['api_server']
        collection_path = GalaxyCLI._resolve_path(context.CLIARGS['args'])
        ignore_certs = context.CLIARGS['ignore_certs']
        wait = context.CLIARGS['wait']

        publish_collection(collection_path, api_server, api_key, ignore_certs, wait)
Beispiel #11
0
    def __init__(self, galaxy):
        self.galaxy = galaxy
        self.token = GalaxyToken()
        self._api_server = C.GALAXY_SERVER
        self._validate_certs = not galaxy.options.ignore_certs
        self.baseurl = None
        self.version = None
        self.initialized = False

        display.debug('Validate TLS certificates: %s' % self._validate_certs)

        # set the API server
        if galaxy.options.api_server != C.GALAXY_SERVER:
            self._api_server = galaxy.options.api_server
Beispiel #12
0
def test_initialise_unknown(monkeypatch):
    mock_open = MagicMock()
    mock_open.side_effect = [
        urllib_error.HTTPError('https://galaxy.ansible.com/api/', 500, 'msg', {}, StringIO(u'{"msg":"raw error"}')),
        urllib_error.HTTPError('https://galaxy.ansible.com/api/api/', 500, 'msg', {}, StringIO(u'{"msg":"raw error"}')),
    ]
    monkeypatch.setattr(galaxy_api, 'open_url', mock_open)

    api = GalaxyAPI(None, "test", "https://galaxy.ansible.com/api/", token=GalaxyToken(token='my_token'))

    expected = "Error when finding available api versions from test (%s) (HTTP Code: 500, Message: msg)" \
        % api.api_server
    with pytest.raises(AnsibleError, match=re.escape(expected)):
        api.authenticate("github_token")
Beispiel #13
0
    def __init__(self, galaxy):
        self.galaxy = galaxy
        self.token = GalaxyToken()
        self._api_server = C.GALAXY_SERVER
        self._validate_certs = not context.CLIARGS['ignore_certs']
        self.baseurl = None
        self.version = None
        self.initialized = False

        display.debug('Validate TLS certificates: %s' % self._validate_certs)

        # set the API server
        if context.CLIARGS['api_server'] != C.GALAXY_SERVER:
            self._api_server = context.CLIARGS['api_server']
Beispiel #14
0
def get_test_galaxy_api(url, version):
    api = GalaxyAPI(None, "test", url)
    api._available_api_versions = {version: '/api/%s' % version}
    api.token = GalaxyToken(token="my token")

    return api
Beispiel #15
0
    expected_url = '%s/api/%s/%s' % (api.api_server, api_version,
                                     collection_url)

    mock_open = MagicMock()
    mock_open.side_effect = urllib_error.HTTPError(
        expected_url, 500, 'msg', {}, StringIO(to_text(json.dumps(response))))
    monkeypatch.setattr(galaxy_api, 'open_url', mock_open)

    with pytest.raises(GalaxyError,
                       match=re.escape(to_native(expected % api.api_server))):
        api.publish_collection(collection_artifact)


@pytest.mark.parametrize('api_version, token_type, token_ins', [
    ('v2', 'Token', GalaxyToken('my token')),
    ('v3', 'Bearer', KeycloakToken(auth_url='https://api.test/')),
])
def test_wait_import_task(api_version, token_type, token_ins, monkeypatch):
    api = get_test_galaxy_api('https://galaxy.server.com',
                              api_version,
                              token_ins=token_ins)
    import_uri = 'https://galaxy.server.com/api/%s/task/1234' % api_version

    if token_ins:
        mock_token_get = MagicMock()
        mock_token_get.return_value = 'my token'
        monkeypatch.setattr(token_ins, 'get', mock_token_get)

    mock_open = MagicMock()
    mock_open.return_value = StringIO(
Beispiel #16
0
def test_api_token_auth_with_token_type():
    token = GalaxyToken(token=u"my_token")
    api = GalaxyAPI(None, "test", "https://galaxy.ansible.com", token=token)
    actual = {}
    api._add_auth_token(actual, "", token_type="Bearer")
    assert actual == {'Authorization': 'Bearer my_token'}
Beispiel #17
0
    mock_open = MagicMock()
    mock_open.side_effect = urllib_error.HTTPError(
        expected_url, 500, 'msg', {}, StringIO(to_text(json.dumps(response))))
    monkeypatch.setattr(galaxy_api, 'open_url', mock_open)

    with pytest.raises(GalaxyError,
                       match=re.escape(to_native(expected % api.api_server))):
        api.publish_collection(collection_artifact)


@pytest.mark.parametrize(
    'server_url, api_version, token_type, token_ins, import_uri, full_import_uri',
    [
        ('https://galaxy.server.com/api', 'v2', 'Token',
         GalaxyToken('my token'), '1234',
         'https://galaxy.server.com/api/v2/collection-imports/1234/'),
        ('https://galaxy.server.com/api/automation-hub/', 'v3', 'Bearer',
         KeycloakToken(auth_url='https://api.test/'), '1234',
         'https://galaxy.server.com/api/automation-hub/v3/imports/collections/1234/'
         ),
    ])
def test_wait_import_task(server_url, api_version, token_type, token_ins,
                          import_uri, full_import_uri, monkeypatch):
    api = get_test_galaxy_api(server_url, api_version, token_ins=token_ins)

    if token_ins:
        mock_token_get = MagicMock()
        mock_token_get.return_value = 'my token'
        monkeypatch.setattr(token_ins, 'get', mock_token_get)
Beispiel #18
0
def test_publish_failure(api_version, collection_url, response, expected, collection_artifact, monkeypatch):
    api = get_test_galaxy_api('https://galaxy.server.com/api/', api_version)

    expected_url = '%s/api/%s/%s' % (api.api_server, api_version, collection_url)

    mock_open = MagicMock()
    mock_open.side_effect = urllib_error.HTTPError(expected_url, 500, 'msg', {},
                                                   StringIO(to_text(json.dumps(response))))
    monkeypatch.setattr(galaxy_api, 'open_url', mock_open)

    with pytest.raises(GalaxyError, match=re.escape(to_native(expected % api.api_server))):
        api.publish_collection(collection_artifact)


@pytest.mark.parametrize('server_url, api_version, token_type, token_ins, import_uri, full_import_uri', [
    ('https://galaxy.server.com/api', 'v2', 'Token', GalaxyToken('my token'),
     '1234',
     'https://galaxy.server.com/api/v2/collection-imports/1234'),
    ('https://galaxy.server.com/api/automation-hub/', 'v3', 'Bearer', KeycloakToken(auth_url='https://api.test/'),
     '1234',
     'https://galaxy.server.com/api/automation-hub/v3/imports/collections/1234/'),
])
def test_wait_import_task(server_url, api_version, token_type, token_ins, import_uri, full_import_uri, monkeypatch):
    api = get_test_galaxy_api(server_url, api_version, token_ins=token_ins)

    if token_ins:
        mock_token_get = MagicMock()
        mock_token_get.return_value = 'my token'
        monkeypatch.setattr(token_ins, 'get', mock_token_get)

    mock_open = MagicMock()
def test_token_none(b_token_file):
    assert GalaxyToken(token=NoTokenSentinel).get() is None
def test_token_from_file_missing(b_token_file):
    assert GalaxyToken().get() is None
def test_token_from_file(b_token_file):
    assert GalaxyToken().get() == "file"
def test_token_explicit_override_file(b_token_file):
    assert GalaxyToken(token="explicit").get() == "explicit"
Beispiel #23
0
def test_api_token_auth():
    token = GalaxyToken(token=u"my_token")
    api = GalaxyAPI(None, "test", "https://galaxy.ansible.com", token=token)
    actual = api._auth_header()
    assert actual == {'Authorization': 'Token my_token'}