Ejemplo n.º 1
0
def test_bearer_validate_failed():
    with pytest.raises(ValueError) as err:
        BearerTokenAuthenticator(None)
    assert str(err.value) == 'The bearer token shouldn\'t be None.'
    authenticator = BearerTokenAuthenticator('my_bearer_token')
    with pytest.raises(ValueError) as err:
        authenticator.set_bearer_token(None)
    assert str(err.value) == 'The bearer token shouldn\'t be None.'
def run_module():

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=False)

    # New resource required arguments checks
    missing_args = []
    for arg, _ in REQUIRED_PARAMETERS:
        if module.params[arg] is None:
            missing_args.append(arg)
    if missing_args:
        module.fail_json(msg=("missing required arguments: " +
                              ", ".join(missing_args)))

    # authenticate using api-key
    if module.params["ibmcloud_api_key"]:
        authenticator = IAMAuthenticator(module.params["ibmcloud_api_key"])
    elif module.params["bearer_token"]:
        authenticator = BearerTokenAuthenticator(module.params["bearer_token"])
    else:
        authenticator = BearerTokenAuthenticator(
            module.params["env_bearer_token"])

    service = VpcV1('2020-06-02', authenticator=authenticator)

    # Stop Instance
    #print("Stop Instance")
    try:
        stopIns = service.create_instance_action(
            instance_id=module.params["instance_id"],
            type=module.params["action_type"])
    except ApiException as e:
        module.fail_json(msg=("Failed to get expected response"))
        print("stop instances failed with status code " + str(e.code) + ": " +
              e.message)

    #print(stopIns)

    if stopIns.get_status_code() != 201:
        module.fail_json(msg=("Failed to get expected response"))
    module.exit_json(**stopIns.get_result())
Ejemplo n.º 3
0
def choose_auth(args: Namespace) -> Authenticator:
    """
    Choose the authenticator type

    :param args:
    :return:
    """
    if args.auth_type == 'iam':
        return IAMAuthenticator(args.iam_apikey)
    elif args.auth_type == 'bearer':
        return BearerTokenAuthenticator(args.iam_apikey)
    else:
        raise ValueError(f'Unknown auth type: "{args.auth_type}"')
Ejemplo n.º 4
0
def change_card(account_id, token, endpoint, note):
    try:
        findingsAPI = FindingsApiV1(
            authenticator=BearerTokenAuthenticator(token))
        findingsAPI.set_service_url(endpoint)
        response = findingsAPI.update_note(account_id=account_id,
                                           note_id=note['id']**note)
        if response.get_status_code() == 200:
            logger.info("card updated: %s" % note['id'])
        else:
            logger.error("card not updated: %s" % note['id'])
    except:
        logger.exception(
            "an unexpected error was encountered while updating note")
def test_bearer_authenticator():
    authenticator = BearerTokenAuthenticator('my_bearer_token')
    assert authenticator is not None
    assert authenticator.authentication_type(
    ) == Authenticator.AUTHTYPE_BEARERTOKEN
    assert authenticator.bearer_token == 'my_bearer_token'

    authenticator.set_bearer_token('james bond')
    assert authenticator.bearer_token == 'james bond'

    request = {'headers': {}}
    authenticator.authenticate(request)
    assert request['headers']['Authorization'] == 'Bearer james bond'
Ejemplo n.º 6
0
def choose_authenticator(config: ConfigParser) -> Authenticator:
    creds = config['CREDENTIALS']
    apikey = get_required(creds, 'api_key')

    if apikey is None:
        raise RequiredConfigMissingError('api_key')

    if creds.get('auth_method', 'iam') == 'bearer':
        LOG.warning('Using bearer token authentication')
        return BearerTokenAuthenticator(apikey)
    else:
        LOG.warning('Using IAM authentication')
        return IAMAuthenticator(
            apikey
        )
Ejemplo n.º 7
0
def createOccurences(account_id, token, endpoint, occurrencesJson):
    try:
        findingsAPI = FindingsApiV1(
            authenticator=BearerTokenAuthenticator(token))
        findingsAPI.set_service_url(endpoint)
        for occurrence in occurrencesJson:
            response = findingsAPI.create_occurrence(account_id=account_id,
                                                     **occurrence)
            if response.get_status_code() == 200:
                logger.info("created occurrence: %s" % occurrence['id'])
            else:
                logger.error("unable to create occurrence: %s" %
                             occurrence['id'])
    except requests.exceptions.HTTPError as err:
        logger.exception(
            "an unexpected error was encountered while creating occurrence: " +
            str(err))
Ejemplo n.º 8
0
def create_note(account_id, token, endpoint):
    try:
        findingsAPI = FindingsApiV1(
            authenticator=BearerTokenAuthenticator(token))
        findingsAPI.set_service_url(endpoint)
        for note in vulnerablity_notes_definition["notes"]:
            response = findingsAPI.create_note(account_id=account_id, **note)
            if response.get_status_code() == 200:
                logger.info("created note: %s" % note['id'])
            elif response.get_status_code() == 409 and note['kind'] == "CARD":
                logger.info("card already present... attempting to update")
                change_card(account_id, token, endpoint, note)
            else:
                logger.error("unable to create note: %s" % note['id'])
    except:
        logger.exception(
            "an unexpected error was encountered while creating note")
Ejemplo n.º 9
0
 def test_analyze(self):
     authenticator = BearerTokenAuthenticator('<bearer_token>')
     discovery_cpd = ibm_watson.DiscoveryV2(
         version='2020-08-12',
         authenticator=authenticator
     )
     discovery_cpd.service_url = "<url>"
     discovery_cpd.set_disable_ssl_verification(True)
     test_file = abspath('resources/problem.json')
     with open(test_file, 'rb') as file:
         result = discovery_cpd.analyze_document(
             project_id="<project_id>",
             collection_id="<collection_id>",
             file=file,
             file_content_type="application/json"
         ).get_result()
         assert result is not None
Ejemplo n.º 10
0
def delete_notes(account_id, token, endpoint, notes):
    try:
        findingsAPI = FindingsApiV1(
            authenticator=BearerTokenAuthenticator(token))
        findingsAPI.set_service_url(endpoint)
        for note in notes:
            response = findingsAPI.delete_note(account_id=account_id,
                                               note_id=note['id'],
                                               **note)
            if response.get_status_code() == 200:
                logger.info("deleted note: %s" % note['id'])
            else:
                logger.error("unable to delete note: %s" % note['id'])
    except:
        logger.exception(
            "an unexpected error was encountered while deleting the note: " +
            str(err))
    time.sleep(1)
Ejemplo n.º 11
0
def get_notes(account_id, token, endpoint, url):
    notes = []
    try:
        findingsAPI = FindingsApiV1(
            authenticator=BearerTokenAuthenticator(token))
        findingsAPI.set_service_url(endpoint)
        for provider in providers:
            response = findingsAPI.list_notes(account_id=account_id,
                                              provider_id=provider)
            if response.get_status_code() == 200:
                logger.info("got notes by provider: %s" % provider)
                for note in response.get_result()['notes']:
                    notes.append(note)
            else:
                logger.error("unable to get notes by provider: %s" % provider)
        return notes
    except requests.exceptions.HTTPError as err:
        logger.exception(
            "an unexpected error was encountered while getting the note: " +
            str(err))
        return False
Ejemplo n.º 12
0
def delete_workspaces(iam_apikey, url, version, workspace_ids, auth_type):
    """ Delete workspaces
    """
    if auth_type == 'iam':
        authenticator = IAMAuthenticator(iam_apikey)
    elif auth_type == 'bearer':
        authenticator = BearerTokenAuthenticator(iam_apikey)
    else:
        raise ValueError(f'Unknown auth_type "{auth_type}"')

    for workspace_id in workspace_ids:
        if 'natural-language-classifier' in url:
            c = NaturalLanguageClassifierV1(authenticator=authenticator)
            c.set_service_url(url)
            c.delete_classifier(classifier_id=workspace_id)
        else:
            c = AssistantV1(version=version, authenticator=authenticator)
            c.set_service_url(url)
            c.delete_workspace(workspace_id=workspace_id)

    print('Cleaned up workspaces')
import os
from ibm_watson import DiscoveryV2
from ibm_watson.discovery_v2 import TrainingExample
from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator, BearerTokenAuthenticator

## Important: Discovery v2 is only available on Cloud Pak for Data. ##

## Authentication ##
## Option 1: username/password
authenticator = CloudPakForDataAuthenticator('<your username>',
                                             '<your password>',
                                             '<url for authentication>',
                                             disable_ssl_verification=True)

## Option 2: bearer token
authenticator = BearerTokenAuthenticator('your bearer token')

## Initialize discovery instance ##
discovery = DiscoveryV2(version='2019-11-22', authenticator=authenticator)
discovery.set_service_url('<service url>')
discovery.set_disable_ssl_verification(True)

PROJECT_ID = 'your project id'
## List Collections ##
collections = discovery.list_collections(project_id=PROJECT_ID).get_result()
print(json.dumps(collections, indent=2))

## Component settings ##
settings_result = discovery.get_component_settings(
    project_id=PROJECT_ID).get_result()
print(json.dumps(settings_result, indent=2))
from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions, CategoriesOptions, ConceptsOptions, EmotionOptions, RelationsOptions, SemanticRolesOptions, SentimentOptions

authenticator = IAMAuthenticator(
    'mKzR3k6BF2W3tMUmoX3_Xvxze4LL0-f_q8FM5QMsFIFY')
natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2019-07-12', authenticator=authenticator)
from ibm_watson import IAMTokenManager

iam_token_manager = IAMTokenManager(
    apikey='mKzR3k6BF2W3tMUmoX3_Xvxze4LL0-f_q8FM5QMsFIFY')
token = iam_token_manager.get_token()

from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator

# in the constructor, assuming control of managing the token
authenticator1 = BearerTokenAuthenticator(token)
natural_language_understanding1 = NaturalLanguageUnderstandingV1(
    version='2019-07-12', authenticator=authenticator1)
f_name = input("enter file in csv format")
x = 0
intext = []
with open("C:\\Users\\HP\\Desktop\\" + f_name + ".csv") as file:
    data = list(csv.reader(file))
#print(type(data[0]))
strin = " ".join(str(x) for x in data)
#print(type(strin))
#print(file)
natural_language_understanding.set_service_url(
    'https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/c70c1850-5873-495c-b449-d84d30415f06'
)
natural_language_understanding.set_disable_ssl_verification(True)
Ejemplo n.º 15
0
def run_module():

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=False)

    # New resource required arguments checks
    missing_args = []
    for arg, _ in REQUIRED_PARAMETERS:
        if module.params[arg] is None:
            missing_args.append(arg)
    if missing_args:
        module.fail_json(msg=("missing required arguments: " +
                              ", ".join(missing_args)))

    if not module.params["instance_ip"] and not module.params["instance_id"]:
        module.fail_json(msg=(
            "missing required arguments: pass instance_ip or instance_id"))

    # authenticate using api-key
    if module.params["ibmcloud_api_key"]:
        authenticator = IAMAuthenticator(module.params["ibmcloud_api_key"])
    elif module.params["bearer_token"]:
        authenticator = BearerTokenAuthenticator(module.params["bearer_token"])
    else:
        authenticator = BearerTokenAuthenticator(
            module.params["env_bearer_token"])

    service = VpcV1('2020-06-02', authenticator=authenticator)

    instanceId = module.params["instance_id"]
    if module.params["instance_ip"]:
        try:
            floatingIps = service.list_floating_ips().get_result(
            )['floating_ips']
            instances = service.list_instances().get_result()['instances']
        except ApiException as e:
            print("List instances/floatingIp failed with status code " +
                  str(e.code) + ": " + e.message)
        target = ""
        for floatingIp in floatingIps:
            if floatingIp["address"] == module.params["instance_ip"]:
                target = floatingIp["target"]["id"]
        for instance in instances:
            if target == "":
                if instance["primary_network_interface"][
                        "primary_ipv4_address"] == module.params[
                            "instance_ip"]:
                    instanceId = instance["id"]
                    # print(instance['id'], "\t",  instance['name'])
            elif instance["primary_network_interface"]["id"] == target:
                instanceId = instance["id"]
                # print(instance['id'], "\t",  instance['name'])
        if instanceId == "":
            module.fail_json(msg=("instance not found"))

    try:
        stopIns = service.create_instance_action(
            instance_id=instanceId, type=module.params["action_type"])
    except ApiException as e:
        module.fail_json(msg=("Failed to get expected response"))
        print("stop instances failed with status code " + str(e.code) + ": " +
              e.message)

    #print(stopIns)

    if stopIns.get_status_code() != 201:
        module.fail_json(msg=("Failed to get expected response"))
    module.exit_json(**stopIns.get_result())