예제 #1
0
def test_extra_headers(
    request_mock: Mock,
    client: GGClient,
    session_headers: Any,
    extra_headers: Optional[Dict[str, str]],
    expected_headers: Dict[str, str],
):
    """
    GIVEN client's session headers
    WHEN calling any client method with additional headers
    THEN session/method headers should be merged with priority on method headers
    """
    client.session.headers = session_headers

    mock_response = Mock(spec=Response)
    mock_response.headers = {"content-type": "text"}
    mock_response.text = "some error"
    mock_response.status_code = 400
    request_mock.return_value = mock_response

    client.multi_content_scan(
        [{
            "filename": FILENAME,
            "document": DOCUMENT
        }],
        extra_headers=extra_headers,
    )
    assert request_mock.called
    _, kwargs = request_mock.call_args
    assert expected_headers == kwargs["headers"]

    client.content_scan("some_string", extra_headers=extra_headers)
    assert request_mock.called
    _, kwargs = request_mock.call_args
    assert expected_headers == kwargs["headers"]
예제 #2
0
def test_content_not_ok():
    req = {"document": "valid", "filename": "valid"}
    client = GGClient(base_uri=base_uri, api_key="invalid")

    obj = client.content_scan(**req)

    assert obj.status_code == 401
    assert isinstance(obj, Detail)
    assert obj.detail == "Invalid API key."
예제 #3
0
    async def content_scan(self, api_key, content, file_id):
        client = GGClient(api_key=api_key)  
        
        if file_id and content:
            raise Exception("Can not use file_id & content at once, Please use either one of them.")     
        
        if file_id:
            text = file_id['data']
            try:
                scan_result = client.content_scan(document=text)
                return scan_result.to_json()
            except Exception as e:
                return f"Exception occured: {e}"

        if content:
            try:
                scan_result = client.content_scan(document=content)
                return scan_result.to_json()
            except Exception as e:
                return f"Exception occured: {e}"
예제 #4
0
def test_content_scan(
    client: GGClient,
    name: str,
    to_scan: Dict[str, str],
    has_secrets: bool,
    has_policy_breaks: bool,
    policy_break_count: int,
):
    with my_vcr.use_cassette(name + ".yaml"):
        scan_result = client.content_scan(**to_scan)
        assert type(repr(scan_result)) == str
        assert type(str(scan_result)) == str
        assert scan_result.status_code == 200
        if isinstance(scan_result, ScanResult):
            assert scan_result.has_secrets == has_secrets
            assert scan_result.has_policy_breaks == has_policy_breaks
            assert scan_result.policy_break_count == policy_break_count
        else:
            pytest.fail("returned should be a ScanResult")

        assert type(scan_result.to_dict()) == dict
        scan_result_json = scan_result.to_json()
        assert type(scan_result_json) == str
        assert type(json.loads(scan_result_json)) == dict
예제 #5
0
def test_content_scan_exceptions(client: GGClient, to_scan: str,
                                 exception: Type[Exception], regex: str):
    with pytest.raises(exception, match=regex):
        client.content_scan(to_scan)
예제 #6
0
from requests import codes

from pygitguardian import GGClient

API_KEY = os.getenv("GG_API_KEY")
FILENAME = ".env"
DOCUMENT = """
    import urllib.request
    url = 'http://*****:*****@cake.gitguardian.com/isreal.json'
    response = urllib.request.urlopen(url)
    consume(response.read())"
"""

client = GGClient(api_key=API_KEY)

# Check the health of the API and the API key used.
health_obj = client.health_check()

if health_obj.status_code == codes[r"\o/"]:  # this is 200 but cooler
    try:
        scan_result = client.content_scan(filename=FILENAME, document=DOCUMENT)
    except Exception as exc:
        # Handle exceptions such as schema validation
        traceback.print_exc(2, file=sys.stderr)
        print(str(exc))

    print("Scan results:", scan_result.has_secrets, "-",
          scan_result.policy_break_count)
else:
    print("Invalid API Key")