def test_can_add_new_strategies():
    a = AuthHandler({'https://example.com': ('foo', 'bar')})
    a.add_strategy('https://api.github.com', ('fiz', 'baz'))
    assert isinstance(
        a.get_strategy_for('https://api.github.com'),
        HTTPBasicAuth
        )
示例#2
0
def test_prepares_auth_correctly():
    # Set up our Session and AuthHandler
    auth = AuthHandler({
        'https://api.example.com': ('bar', 'baz'),
        'https://httpbin.org': ('biz', 'fiz'),
    })
    s = requests.Session()
    s.auth = auth
    # Set up a valid GET request to https://api.example.com/users
    r1 = requests.Request('GET', 'https://api.example.com/users')
    p1 = s.prepare_request(r1)
    assert p1.headers['Authorization'] == 'Basic YmFyOmJheg=='

    # Set up a valid POST request to https://httpbin.org/post
    r2 = requests.Request('POST', 'https://httpbin.org/post', data='foo')
    p2 = s.prepare_request(r2)
    assert p2.headers['Authorization'] == 'Basic Yml6OmZpeg=='

    # Set up an *invalid* OPTIONS request to http://api.example.com
    # NOTE(sigmavirus24): This is not because of the verb but instead because
    # it is the wrong URI scheme.
    r3 = requests.Request('OPTIONS', 'http://api.example.com/projects')
    p3 = s.prepare_request(r3)
    assert p3.headers.get('Authorization') is None
示例#3
0
def test_turns_tuples_into_basic_auth():
    a = AuthHandler({'http://example.com': ('foo', 'bar')})
    strategy = a.get_strategy_for('http://example.com')
    assert not isinstance(strategy, NullAuthStrategy)
    assert isinstance(strategy, HTTPBasicAuth)
示例#4
0
def test_can_add_new_strategies():
    a = AuthHandler({'https://example.com': ('foo', 'bar')})
    a.add_strategy('https://api.github.com', ('fiz', 'baz'))
    assert isinstance(a.get_strategy_for('https://api.github.com'),
                      HTTPBasicAuth)
示例#5
0
def test_normalizes_domain_keys():
    a = AuthHandler({'https://API.github.COM': ('foo', 'bar')})
    assert 'https://api.github.com' in a.strategies
    assert 'https://API.github.COM' not in a.strategies
示例#6
0
def test_uses_null_strategy_for_non_matching_domains():
    a = AuthHandler({'http://api.example.com': ('foo', 'bar')})
    strategy = a.get_strategy_for('http://example.com')
    assert isinstance(strategy, NullAuthStrategy)
示例#7
0
def main() -> None:
    # Demo content for our target file.
    content = b"Hello, World!\n"
    content_hash = hashlib.sha256(content).hexdigest()

    # Create a request signer instance.
    request_signer = AwsRequestSigner(AWS_REGION, AWS_ACCESS_KEY_ID,
                                      AWS_SECRET_ACCESS_KEY, "s3")

    #
    # Use AWS request signer to generate authentication headers.
    #

    # The headers we'll provide and want to sign.
    headers = {
        "Content-Type": "text/plain",
        "Content-Length": str(len(content))
    }

    # Add the authentication headers.
    headers.update(
        request_signer.sign_with_headers("PUT", URL, headers, content_hash))

    # Make the request.
    r = requests.put(URL, headers=headers, data=content)
    r.raise_for_status()

    #
    # Use AWS request signer to generate a pre-signed URL.
    #

    # The headers we'll provide and want to sign.
    headers = {
        "Content-Type": "text/plain",
        "Content-Length": str(len(content))
    }

    # Generate the pre-signed URL that includes the authentication
    # parameters. Allow the client to determine the contents by
    # settings the content_has to UNSIGNED-PAYLOAD.
    presigned_url = request_signer.presign_url("PUT", URL, headers,
                                               UNSIGNED_PAYLOAD)

    # Perform the request.
    r = requests.put(presigned_url, headers=headers, data=content)
    r.raise_for_status()

    #
    # Use AWS request signer for requests helper to perform requests.
    #

    # Create a requests session and assign auth handler.
    session = requests.Session()
    session.auth = AuthHandler({
        "http://127.0.0.1:9000":
        AwsAuth(AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, "s3")
    })

    # Perform the request.
    r = session.put(URL, data=content)
    r.raise_for_status()

    #
    # Use AWS request signer to sign an S3 POST policy request.
    #

    # Create a policy, only restricting bucket and expiration.
    expiration = datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
    policy = {
        "expiration": expiration.strftime("%Y-%m-%dT%H:%M:%SZ"),
        "conditions": [{
            "bucket": "demo"
        }],
    }

    # Get the required form fields to use the policy.
    fields = request_signer.sign_s3_post_policy(policy)

    # Post the form data to the bucket endpoint.
    # Set key (filename) to hello_world.txt.
    r = requests.post(
        URL.rsplit("/", 1)[0],
        data={
            "key": "hello_world.txt",
            "Content-Type": "text/plain",
            **fields
        },
        files={"file": content},
    )
    r.raise_for_status()
def test_turns_tuples_into_basic_auth():
    a = AuthHandler({'http://example.com': ('foo', 'bar')})
    strategy = a.get_strategy_for('http://example.com')
    assert not isinstance(strategy, NullAuthStrategy)
    assert isinstance(strategy, HTTPBasicAuth)
def test_uses_null_strategy_for_non_matching_domains():
    a = AuthHandler({'http://api.example.com': ('foo', 'bar')})
    strategy = a.get_strategy_for('http://example.com')
    assert isinstance(strategy, NullAuthStrategy)