Esempio n. 1
0
def test_payload_expired():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    # expire_after must be greater than 0 or None.
    with pytest.raises(bitjws.jws.InvalidPayload):
        bitjws.sign_serialize(key, expire_after=0)

    ser = bitjws.sign_serialize(key, expire_after=0.01)
    time.sleep(0.02)
    with pytest.raises(bitjws.jws.InvalidPayload):
        # payload expired.
        bitjws.validate_deserialize(ser)

    # But the signature can still be verified and the msg decoded
    # if expiration checks are disabled.
    h, p = bitjws.validate_deserialize(ser, check_expiration=False)
    assert h and p

    # Check with multisig.
    ser = bitjws.multisig_sign_serialize([key], expire_after=0.01)
    time.sleep(0.02)
    with pytest.raises(bitjws.jws.InvalidPayload):
        # payload expired.
        bitjws.multisig_validate_deserialize(ser)
Esempio n. 2
0
def test_dummy_algo():
    key = bitjws.PrivateKey()

    # Setup a new algorithm for signing/verifying.
    # The sign function always take two parameters and return bytes.
    # The verify function always take three parameters and return a boolean.
    # The pubkey_serialize function take a pubkey object and return text.
    newalgo = bitjws.Algorithm(
        'dummy',
        sign=lambda privkey, signdata: signdata.encode('utf8'),
        verify=lambda sig, data, pubkey: True,
        pubkey_serialize=lambda x: "hello")
    bitjws.ALGORITHM_AVAILABLE[newalgo.name] = newalgo

    ser = bitjws.sign_serialize(key)
    with pytest.raises(bitjws.InvalidMessage):
        # Algorithm mismatch.
        bitjws.validate_deserialize(ser, algorithm_name='dummy')

    ser = bitjws.sign_serialize(key, algorithm_name='dummy')
    with pytest.raises(bitjws.InvalidMessage):
        # Algorithm mismatch.
        bitjws.validate_deserialize(ser)

    result = bitjws.validate_deserialize(ser, algorithm_name='dummy')
    assert result[0] and result[1]
Esempio n. 3
0
def test_payload_expired():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    # expire_after must be greater than 0 or None.
    with pytest.raises(bitjws.jws.InvalidPayload):
        bitjws.sign_serialize(key, expire_after=0)

    ser = bitjws.sign_serialize(key, expire_after=0.01)
    time.sleep(0.02)
    with pytest.raises(bitjws.jws.InvalidPayload):
        # payload expired.
        bitjws.validate_deserialize(ser)

    # But the signature can still be verified and the msg decoded
    # if expiration checks are disabled.
    h, p = bitjws.validate_deserialize(ser, check_expiration=False)
    assert h and p

    # Check with multisig.
    ser = bitjws.multisig_sign_serialize([key], expire_after=0.01)
    time.sleep(0.02)
    with pytest.raises(bitjws.jws.InvalidPayload):
        # payload expired.
        bitjws.multisig_validate_deserialize(ser)
Esempio n. 4
0
def test_dummy_algo():
    key = bitjws.PrivateKey()

    # Setup a new algorithm for signing/verifying.
    # The sign function always take two parameters and return bytes.
    # The verify function always take three parameters and return a boolean.
    # The pubkey_serialize function take a pubkey object and return text.
    newalgo = bitjws.Algorithm('dummy',
        sign=lambda privkey, signdata: signdata.encode('utf8'),
        verify=lambda sig, data, pubkey: True,
        pubkey_serialize=lambda x: "hello")
    bitjws.ALGORITHM_AVAILABLE[newalgo.name] = newalgo

    ser = bitjws.sign_serialize(key)
    with pytest.raises(bitjws.InvalidMessage):
        # Algorithm mismatch.
        bitjws.validate_deserialize(ser, algorithm_name='dummy')

    ser = bitjws.sign_serialize(key, algorithm_name='dummy')
    with pytest.raises(bitjws.InvalidMessage):
        # Algorithm mismatch.
        bitjws.validate_deserialize(ser)

    result = bitjws.validate_deserialize(ser, algorithm_name='dummy')
    assert result[0] and result[1]
Esempio n. 5
0
def test_invalid_audience():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    ser = bitjws.sign_serialize(key, requrl='https://example.com/api/login')

    with pytest.raises(bitjws.jws.InvalidPayload):
        # audience not specified.
        bitjws.validate_deserialize(ser)
    with pytest.raises(bitjws.jws.InvalidPayload):
        # audience does not match.
        bitjws.validate_deserialize(ser, requrl='https://example.com/api')
Esempio n. 6
0
def test_invalid_audience():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    ser = bitjws.sign_serialize(key, requrl='https://example.com/api/login')

    with pytest.raises(bitjws.jws.InvalidPayload):
        # audience not specified.
        bitjws.validate_deserialize(ser)
    with pytest.raises(bitjws.jws.InvalidPayload):
        # audience does not match.
        bitjws.validate_deserialize(ser, requrl='https://example.com/api')
Esempio n. 7
0
def test_encode_decode():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key)
    header, payload = bitjws.validate_deserialize(ser)

    rawheader, rawpayload = ser.rsplit('.', 1)[0].split('.')
    origheader = bitjws.base64url_decode(rawheader.encode('utf8'))
    origpayload = bitjws.base64url_decode(rawpayload.encode('utf8'))

    assert header['typ'] == 'JWT'
    assert header['alg'] == 'CUSTOM-BITCOIN-SIGN'
    assert header['kid'] == bitjws.pubkey_to_addr(key.pubkey.serialize())
    assert len(header) == 3
    assert header == json.loads(origheader.decode('utf8'))

    assert isinstance(payload.get('exp', ''), (float, int))
    assert payload['aud'] is None
    assert len(payload) == 2
    assert payload == json.loads(origpayload.decode('utf8'))

    # Assumption: it takes mores than 0 seconds to perform the above
    # instructions but less than 1 second. 3600 is the default
    # expiration time.
    diff = 3600 - (payload['exp'] - time.time())
    assert diff > 0 and diff < 1
Esempio n. 8
0
def test_no_expire():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key, expire_after=None)
    header, payload = bitjws.validate_deserialize(ser)
    assert header is not None
    assert payload['exp'] >= 2 ** 31
 def listener_allowed(self, instance, data):
     """Incomplete/Naive bitjws auth (being developed)"""
     self._log.info("allowed: %s" % data)
     try:
         payload_data = bitjws.validate_deserialize(data)[1]['data']
     except Exception as e:
         print e
         try:
             headers, payload_data = bitjws.multisig_validate_deserialize(data)
         except Exception as e:
             print e
             self._log.info("allowed auth err %s" % e)
             return False
     if payload_data['model'] not in self.schemas:
         return False
     elif 'id' in payload_data:
         if not 'GET' in self.schemas[payload_data['model']]['routes']['/:id']:
             return False
         permissions = self.schemas[payload_data['model']]['routes']['/:id']['GET']
     else:
         if not 'GET' in self.schemas[payload_data['model']]['routes']['/']:
             return False
         permissions = self.schemas[payload_data['model']]['routes']['/']['GET']
     self._log.info("allowed permissions: %s" % permissions)
     if 'pubhash' in permissions:
         if 'pubhash' not in payload_data:
             return False
     return True
    def on_message(self, unused_channel, basic_deliver, properties, body):
        """
        Invoked by pika when a message is delivered from RabbitMQ. The
        channel is passed for your convenience. The basic_deliver object that
        is passed in carries the exchange, routing key, delivery tag and
        a redelivered flag for the message. The properties passed in is an
        instance of BasicProperties with the message properties and the body
        is the message that was sent.

        The message is delivered according to the settings per listener.

        :param pika.channel.Channel unused_channel: The channel object
        :param pika.Spec.Basic.Deliver: basic_deliver method
        :param pika.Spec.BasicProperties: properties
        :param str|unicode body: The message body
        """
        if basic_deliver and properties:
            self._log.debug('Received message # %s: %s' % (
                basic_deliver.delivery_tag, repr(body)))
            self.acknowledge_message(basic_deliver.delivery_tag)
        else:
            self._log.debug('Received direct message: %r' % body)

        try:
            payload_data = bitjws.validate_deserialize(body)[1]['data']
        except Exception, e:
            self._log.exception(e)
            return
Esempio n. 11
0
def test_invalid_algorithm():
    key1 = bitjws.PrivateKey()

    # Invalid algorithm name for signing.
    with pytest.raises(AssertionError):
        bitjws.sign_serialize(key1, algorithm_name='test')
    with pytest.raises(AssertionError):
        bitjws.multisig_sign_serialize([key1], algorithm_name='test')

    # Invalid algorithm name for verifying.
    ser = bitjws.sign_serialize(key1)
    with pytest.raises(AssertionError):
        bitjws.validate_deserialize(ser, algorithm_name='test')
    ser = bitjws.multisig_sign_serialize([key1])
    with pytest.raises(AssertionError):
        bitjws.multisig_validate_deserialize(ser, algorithm_name='test')
Esempio n. 12
0
def test_no_expire():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key, expire_after=None)
    header, payload = bitjws.validate_deserialize(ser)
    assert header is not None
    assert payload['exp'] >= 2 ** 31
Esempio n. 13
0
def test_encode_decode():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key)
    header, payload = bitjws.validate_deserialize(ser)

    rawheader, rawpayload = ser.rsplit('.', 1)[0].split('.')
    origheader = bitjws.base64url_decode(rawheader.encode('utf8'))
    origpayload = bitjws.base64url_decode(rawpayload.encode('utf8'))

    assert header['typ'] == 'JWT'
    assert header['alg'] == 'CUSTOM-BITCOIN-SIGN'
    assert header['kid'] == bitjws.pubkey_to_addr(key.pubkey.serialize())
    assert len(header) == 3
    assert header == json.loads(origheader.decode('utf8'))

    assert isinstance(payload.get('exp', ''), (float, int))
    assert payload['aud'] is None
    assert len(payload) == 2
    assert payload == json.loads(origpayload.decode('utf8'))

    # Assumption: it takes mores than 0 seconds to perform the above
    # instructions but less than 1 second. 3600 is the default
    # expiration time.
    diff = 3600 - (payload['exp'] - time.time())
    assert diff > 0 and diff < 1
Esempio n. 14
0
def test_invalid_algorithm():
    key1 = bitjws.PrivateKey()

    # Invalid algorithm name for signing.
    with pytest.raises(AssertionError):
        bitjws.sign_serialize(key1, algorithm_name='test')
    with pytest.raises(AssertionError):
        bitjws.multisig_sign_serialize([key1], algorithm_name='test')

    # Invalid algorithm name for verifying.
    ser = bitjws.sign_serialize(key1)
    with pytest.raises(AssertionError):
        bitjws.validate_deserialize(ser, algorithm_name='test')
    ser = bitjws.multisig_sign_serialize([key1])
    with pytest.raises(AssertionError):
        bitjws.multisig_validate_deserialize(ser, algorithm_name='test')
Esempio n. 15
0
def test_vectors():
    tests = json.load(open(os.path.join(HERE, 'vectors.json')))
    for entry in tests:
        header, payload = bitjws.validate_deserialize(
            entry['jwsdata'], requrl=entry['aud'], check_expiration=False)
        assert header and payload
        assert header['kid'] == entry['kid']
        assert payload['aud'] == entry['aud']
Esempio n. 16
0
def test_audience():
    key = bitjws.PrivateKey()

    audience = 'https://example.com/api/login'
    ser = bitjws.sign_serialize(key, requrl=audience)
    header, payload = bitjws.validate_deserialize(ser, requrl=audience)
    assert header is not None
    assert payload is not None
    assert payload['aud'] == audience
Esempio n. 17
0
def test_audience():
    key = bitjws.PrivateKey()

    audience = 'https://example.com/api/login'
    ser = bitjws.sign_serialize(key, requrl=audience)
    header, payload = bitjws.validate_deserialize(ser, requrl=audience)
    assert header is not None
    assert payload is not None
    assert payload['aud'] == audience
Esempio n. 18
0
def test_too_big():
    key = bitjws.PrivateKey(rawkey)

    try:
        ser = bitjws.sign_serialize(key, test='a' * 4294967295)
        h, p = bitjws.validate_deserialize(ser)
        assert h and p
    except MemoryError:
        pytest.skip('Not enough memory to run this test')
        return
Esempio n. 19
0
def test_none_algo():
    # Register an algorithm named None.
    newalgo = bitjws.Algorithm(None,
                               sign=lambda a, b: b.encode('utf8'),
                               verify=lambda a, b, c: True,
                               pubkey_serialize=lambda x: "hello")
    bitjws.ALGORITHM_AVAILABLE[None] = newalgo

    key = bitjws.PrivateKey()
    ser = bitjws.sign_serialize(key, algorithm_name=None)

    with pytest.raises(bitjws.InvalidMessage):
        # Although it "signs" a message, decoding does complete
        # due to its name (None).
        bitjws.validate_deserialize(ser, algorithm_name=None)
    with pytest.raises(bitjws.InvalidMessage):
        # The algorithm name (None) is defined in the header, so it
        # fails to decode here too.
        bitjws.validate_deserialize(ser)
Esempio n. 20
0
def test_none_algo():
    # Register an algorithm named None.
    newalgo = bitjws.Algorithm(None,
        sign=lambda a, b: b.encode('utf8'),
        verify=lambda a, b, c: True,
        pubkey_serialize=lambda x: "hello")
    bitjws.ALGORITHM_AVAILABLE[None] = newalgo

    key = bitjws.PrivateKey()
    ser = bitjws.sign_serialize(key, algorithm_name=None)

    with pytest.raises(bitjws.InvalidMessage):
        # Although it "signs" a message, decoding does complete
        # due to its name (None).
        bitjws.validate_deserialize(ser, algorithm_name=None)
    with pytest.raises(bitjws.InvalidMessage):
        # The algorithm name (None) is defined in the header, so it
        # fails to decode here too.
        bitjws.validate_deserialize(ser)
Esempio n. 21
0
def test_get_bitjws_header_payload():
    app = server.app.test_client()
    coins = app.get('/coin')
    h, p = bitjws.validate_deserialize(coins.get_data().decode('utf8'), requrl='/response')
    assert 'alg' in h
    assert h['alg'] == 'CUSTOM-BITCOIN-SIGN'
    assert 'typ' in h
    assert 'kid' in h
    assert 'data' in p
    assert isinstance(p['data'], list)
    assert 'metal' in p['data'][0] and 'mint' in p['data'][0]
Esempio n. 22
0
def load_user_from_request(request):
    header, payload = bitjws.validate_deserialize(request.data.decode('utf8'))
    if header is None:
        # Validation failed.
        return None

    # Store the decoded payload so it can be used for processing the request.
    flask.g.payload = payload

    # In this example, Users are not loaded from a database or similar
    # and are always assumed to exist.
    return User(header['kid'])
Esempio n. 23
0
def load_user_from_request(request):
    header, payload = bitjws.validate_deserialize(request.data.decode('utf8'))
    if header is None:
        # Validation failed.
        return None

    # Store the decoded payload so it can be used for processing the request.
    flask.g.payload = payload

    # In this example, Users are not loaded from a database or similar
    # and are always assumed to exist.
    return User(header['kid'])
Esempio n. 24
0
def test_bad_signature():
    wif = 'L2Ai1TBwKfyPshmqosKRBvJ47qUCDKesfZXh2zLoYoB7NHgdPS6d'
    key = bitjws.PrivateKey(bitjws.wif_to_privkey(wif))
    assert bitjws.privkey_to_wif(key.private_key) == wif

    ser = bitjws.sign_serialize(key)
    # Drop the last byte from the signature.
    ser = ser[:-1]
    with pytest.raises(bitjws.jws.InvalidMessage):
        # It will fail to decode as base64 due to padding.
        bitjws.validate_deserialize(ser)
    # Drop another byte.
    ser = ser[:-1]
    with pytest.raises(bitjws.jws.InvalidMessage):
        # Although it can be decoded now, the length is incorrect.
        bitjws.validate_deserialize(ser)

    # Replace the signature by something that has the correct
    # length before decoding but becomes invalid after it.
    dummy = bitjws.base64url_encode(b'a' * 88)
    ser = ser[:ser.rfind('.')] + '.' + dummy.decode('utf8')
    with pytest.raises(bitjws.jws.InvalidMessage):
        # Now it fails because the dummy signature above produces
        # 66 bytes (instead of 65) after being decoded.
        bitjws.validate_deserialize(ser)
Esempio n. 25
0
def test_bad_signature():
    wif = 'L2Ai1TBwKfyPshmqosKRBvJ47qUCDKesfZXh2zLoYoB7NHgdPS6d'
    key = bitjws.PrivateKey(bitjws.wif_to_privkey(wif))
    assert bitjws.privkey_to_wif(key.private_key) == wif

    ser = bitjws.sign_serialize(key)
    # Drop the last byte from the signature.
    ser = ser[:-1]
    with pytest.raises(bitjws.jws.InvalidMessage):
        # It will fail to decode as base64 due to padding.
        bitjws.validate_deserialize(ser)
    # Drop another byte.
    ser = ser[:-1]
    with pytest.raises(bitjws.jws.InvalidMessage):
        # Although it can be decoded now, the length is incorrect.
        bitjws.validate_deserialize(ser)

    # Replace the signature by something that has the correct
    # length before decoding but becomes invalid after it.
    dummy = bitjws.base64url_encode(b'a' * 88)
    ser = ser[:ser.rfind('.')] + '.' + dummy.decode('utf8')
    with pytest.raises(bitjws.jws.InvalidMessage):
        # Now it fails because the dummy signature above produces
        # 66 bytes (instead of 65) after being decoded.
        bitjws.validate_deserialize(ser)
Esempio n. 26
0
def test_bad_response():
    app = server.app.test_client()
    privkey = bitjws.PrivateKey()
    echo_msg = {'hello': 'server'}
    data = bitjws.sign_serialize(privkey, echo=echo_msg, iat=time.time(), requrl="/echo")
    data2 = bitjws.sign_serialize(privkey, echo='not%s' % echo_msg)
    da = data.split('.')
    da2 = data2.split('.')
    baddata = "%s.%s.%s" % (da[0], da2[1], da[2])
    echo = app.post('/echo', data=data, headers={'Content-Type': 'application/jose'})
    echo.data = baddata
    h, p = bitjws.validate_deserialize(echo.get_data().decode('utf8'), requrl='/response')
    assert h is None
Esempio n. 27
0
def test_payload_nojson():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key)
    header64 = ser.split('.')[0]

    # Sign a new payload, 'test'
    new_payload = bitjws.base64url_encode(b'test').decode('utf8')
    signdata = '{}.{}'.format(header64, new_payload)
    sig = bitjws.ALGORITHM_AVAILABLE['CUSTOM-BITCOIN-SIGN'].sign(
        key, signdata)
    sig64 = bitjws.base64url_encode(sig).decode('utf8')

    new = '{}.{}'.format(signdata, sig64)
    with pytest.raises(bitjws.InvalidMessage):
        # The new payload was not JSON encoded, so it cannot be
        # decoded as that.
        bitjws.validate_deserialize(new)
    # But we can get its raw value.
    header, payload = bitjws.validate_deserialize(new, decode_payload=False)

    assert header is not None
    assert payload == b'test'
Esempio n. 28
0
def jws_preprocessor(request, status=400):
    """Deserialize the JWS received in the request."""
    url = request.base_url
    data = request.data.encode('utf8')

    try:
        header, payload = bitjws.validate_deserialize(data, requrl=url)
    except Exception:
        logging.exception("Failed to validate and deserialize message")
        return current_app.encode_error(Errors.InvalidMessage, status)

    if header is None or payload is None:
        logging.error("Signature validation failed")
        return current_app.encode_error(Errors.InvalidSignature, status)

    return {'header': header, 'data': payload}
Esempio n. 29
0
 def json(self, **kwargs):
     jso = {}
     if 'content-type' in self._delegate.headers and \
             'application/jose' in self._delegate.headers['content-type']:
         rawtext = self.text.decode('utf8')
         headers, jwtpayload = \
                 bitjws.validate_deserialize(rawtext, requrl='/response')
         if headers is None:
             raise bitjws.jws.InvalidPayload("Response failed validation")
         if 'data' in jwtpayload:
             jso = jwtpayload['data']
         else:
             jso = jwtpayload
     else:
         jso = self._delegate.json(**kwargs)
     return jso
Esempio n. 30
0
def test_echo_request():
    privkey = bitjws.PrivateKey()
    pubkey = bitjws.pubkey_to_addr(privkey.pubkey.serialize())
    echo_msg = {'hello': 'server'}
    data = bitjws.sign_serialize(privkey, data=echo_msg, iat=time.time(), requrl="/echo")
    fbj = FlaskBitjws(server.app)
    app = server.app.test_client()
    udata = json.dumps({'username': pubkey[0:8], 'kid': pubkey})
    user = app.post('/user', data=udata)
    echo = app.post('/echo', data=data, headers={'Content-Type': 'application/jose'})
    h, p = bitjws.validate_deserialize(echo.get_data().decode('utf8'), requrl='/response')
    assert 'alg' in h
    assert h['alg'] == 'CUSTOM-BITCOIN-SIGN'
    assert 'typ' in h
    assert 'kid' in h
    assert 'data' in p
    assert p['data'] == echo_msg
Esempio n. 31
0
def test_apply_auth_json():
    url = 'http://0.0.0.0:8002/path/to/api'
    bjauth = BitJWSAuthenticator('0.0.0.0', privkey=wif)
    rawdata = {'message': 'goes here for sure'}
    data = json.dumps(rawdata)
    headers = {'content-type': 'application/json'}
    params = {'mess': 'couldgohere'}
    request = requests.Request(method='GET', url=url, headers=headers,
                               data=data, params=params)
    req = bjauth.apply(request)
    assert len(req.params) == 0
    assert req.headers['content-type'] == 'application/jose'

    path = urlparse.urlsplit(req.url).path
    h, p = bitjws.validate_deserialize(req.data, requrl=path)
    assert 'message' in p['data']
    assert p['data']['message'] == rawdata['message']
Esempio n. 32
0
def test_invalid_header():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    ser = bitjws.sign_serialize(key)
    # Decode header.
    rawheader = ser.split('.')[0]
    origheader = bitjws.base64url_decode(rawheader.encode('utf8'))
    header = json.loads(origheader.decode('utf8'))

    # Modify the algorithm specified (by removing it).
    algorithm = header.pop('alg')

    # Encode header and try to deserialize.
    ser = _encode_header(header, ser)
    with pytest.raises(bitjws.jws.InvalidMessage):
        # Unknown algorithm.
        bitjws.validate_deserialize(ser)

    # Set some other algorithm.
    header['alg'] = 'SHA256'
    ser = _encode_header(header, ser)
    with pytest.raises(bitjws.jws.InvalidMessage):
        # Unknown algorithm.
        bitjws.validate_deserialize(ser)

    # Drop the key used to sign.
    header['alg'] = algorithm
    kid = header.pop('kid')
    ser = _encode_header(header, ser)
    with pytest.raises(bitjws.jws.InvalidMessage):
        # No address specified.
        bitjws.validate_deserialize(ser)

    # Try to decode the original one.
    ser = rawheader + '.' + ser.split('.', 1)[1]
    header, payload = bitjws.validate_deserialize(ser)
    assert header is not None
    assert payload is not None
    h, p = bitjws.validate_deserialize(ser, check_expiration=False)
    assert h == header
    assert p == payload
Esempio n. 33
0
def test_invalid_signature_key():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    ser = bitjws.sign_serialize(key)
    # Decode header.
    rawheader = ser.rsplit('.')[0]
    origheader = bitjws.base64url_decode(rawheader.encode('utf8'))
    header = json.loads(origheader.decode('utf8'))

    # Modify the key declared to be used in the signature.
    header['kid'] = '123'
    ser = _encode_header(header, ser)
    header, payload = bitjws.validate_deserialize(ser)
    # If both header or payload are None then it failed to validate
    # the signature (as expected).
    assert header is None
    assert payload is None
Esempio n. 34
0
def test_invalid_signature_key():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    ser = bitjws.sign_serialize(key)
    # Decode header.
    rawheader = ser.rsplit('.')[0]
    origheader = bitjws.base64url_decode(rawheader.encode('utf8'))
    header = json.loads(origheader.decode('utf8'))

    # Modify the key declared to be used in the signature.
    header['kid'] = '123'
    ser = _encode_header(header, ser)
    header, payload = bitjws.validate_deserialize(ser)
    # If both header or payload are None then it failed to validate
    # the signature (as expected).
    assert header is None
    assert payload is None
Esempio n. 35
0
def test_invalid_header():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    ser = bitjws.sign_serialize(key)
    # Decode header.
    rawheader = ser.split('.')[0]
    origheader = bitjws.base64url_decode(rawheader.encode('utf8'))
    header = json.loads(origheader.decode('utf8'))

    # Modify the algorithm specified (by removing it).
    algorithm = header.pop('alg')

    # Encode header and try to deserialize.
    ser = _encode_header(header, ser)
    with pytest.raises(bitjws.jws.InvalidMessage):
        # Unknown algorithm.
        bitjws.validate_deserialize(ser)

    # Set some other algorithm.
    header['alg'] = 'SHA256'
    ser = _encode_header(header, ser)
    with pytest.raises(bitjws.jws.InvalidMessage):
        # Unknown algorithm.
        bitjws.validate_deserialize(ser)

    # Drop the key used to sign.
    header['alg'] = algorithm
    kid = header.pop('kid')
    ser = _encode_header(header, ser)
    with pytest.raises(bitjws.jws.InvalidMessage):
        # No address specified.
        bitjws.validate_deserialize(ser)

    # Try to decode the original one.
    ser = rawheader + '.' + ser.split('.', 1)[1]
    header, payload = bitjws.validate_deserialize(ser)
    assert header is not None
    assert payload is not None
    h, p = bitjws.validate_deserialize(ser, check_expiration=False)
    assert h == header
    assert p == payload
Esempio n. 36
0
def load_jws_from_request(req):
    """
    This function performs almost entirely bitjws authentication tasks.
    If valid bitjws message and signature headers are found,
    then the request will be assigned 'jws_header' and 'jws_payload' attributes.

    :param req: The flask request to load the jwt claim set from.
    """
    current_app.logger.info("loading request with headers: %s" % req.headers)
    if (("content-type" in req.headers and
         "application/jose" in req.headers['content-type']) or
        ("Content-Type" in req.headers and
         "application/jose" in req.headers['Content-Type'])):
        path = urlparse.urlsplit(req.url).path
        for rule in current_app.url_map.iter_rules():
            if path == rule.rule and req.method in rule.methods:
                dedata = req.get_data().decode('utf8')
                bp = current_app.bitjws.basepath
                req.jws_header, req.jws_payload = \
                    bitjws.validate_deserialize(dedata, requrl=bp + rule.rule)
                break
Esempio n. 37
0
def client_wait_for(client, method, model=None, n=20):
    # Assume one of the next n messages will be the
    # one with the desired type on it.
    # print method
    # print model
    while n:
        n -= 1
        msg = client.recv()
        try:
            payload = bitjws.validate_deserialize(msg)[1]
            data = payload['data']
        except Exception:
            try:
                data = json.loads(msg)
            except Exception:
                return
        if 'method' in data and data['method'] == method:
            if model is None:
                return data
            elif 'model' in data and data['model'] == model:
                return payload
    def on_message(self, msg):
        if len(str(msg)) > 1024:
            self.logger.info('rejected message from %s (%s): too large' % (
                self.ip, self))
            self.send(ERR_INVALID_DATA)
            return

        received_at = '%.6f' % time.time()

        self.logger.info('%s @ %s' % (str(msg), received_at))
        # Check if the message received has at least the required fields.
        try:
            payload_data = bitjws.validate_deserialize(msg)[1]['data']
            if 'method' not in payload_data:
                self.logger.info("method not in payload data")
                self.send(ERR_UNKNOWN_MSG)  # method is required
                return
        except Exception, e:
            self.logger.exception(e)
            self.send(ERR_INVALID_DATA)
            return
Esempio n. 39
0
def test_malformed():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    ser = bitjws.sign_serialize(key)
    # Drop one of the segments.
    ser = ser.split('.', 1)[1]
    with pytest.raises(bitjws.jws.InvalidMessage):
        bitjws.validate_deserialize(ser)

    # Add an empty segment.
    ser = '.' + ser
    with pytest.raises(bitjws.jws.InvalidMessage):
        bitjws.validate_deserialize(ser)

    # Add an invalid segment.
    ser = ' ' + ser
    with pytest.raises(bitjws.jws.InvalidMessage):
        # This will fail while trying to parse it as JSON.
        bitjws.validate_deserialize(ser)
Esempio n. 40
0
def test_malformed():
    key = bitjws.PrivateKey()
    print(bitjws.privkey_to_wif(key.private_key))

    ser = bitjws.sign_serialize(key)
    # Drop one of the segments.
    ser = ser.split('.', 1)[1]
    with pytest.raises(bitjws.jws.InvalidMessage):
        bitjws.validate_deserialize(ser)

    # Add an empty segment.
    ser = '.' + ser
    with pytest.raises(bitjws.jws.InvalidMessage):
        bitjws.validate_deserialize(ser)

    # Add an invalid segment.
    ser = ' ' + ser
    with pytest.raises(bitjws.jws.InvalidMessage):
        # This will fail while trying to parse it as JSON.
        bitjws.validate_deserialize(ser)
Esempio n. 41
0
import bitjws

# Load existing private key. In this example the server always
# create a new private key while the client loads an existing one.
wif = "KxZUqanyzZEGptbauar66cQo8bfGHwDauHogkxCaqTeMGY1stH6E"
priv = bitjws.wif_to_privkey(wif)
privkey = bitjws.PrivateKey(priv)
assert wif == bitjws.privkey_to_wif(privkey.private_key)
# The resulting bitcoin address can be derived for debugging
# purposes.
my_pubkey = privkey.pubkey.serialize()
my_address = bitjws.pubkey_to_addr(my_pubkey)
assert my_address == "1G9sChbyDSmuAXNVpjuRwakTmcHdxKGqpp"
print("My WIF key: {}".format(wif))
print("My key address: {}".format(my_address))

# Prepare a request to be sent. This one uses a single custom
# parameter named 'echo'.
echo_msg = 'hello'
data = bitjws.sign_serialize(privkey, echo=echo_msg)
# Send and receive signed requests.
resp = requests.post('http://localhost:8001/', data=data)
headers, payload = bitjws.validate_deserialize(resp.content.decode('utf8'))
print(headers)  # headers['kid'] contains the key used by the server.
print(payload)

# In this example the server returns a response containing the
# echo parameter specified earlier and also a param named 'address'.
assert payload['echo'] == echo_msg
assert payload['address'] == my_address
Esempio n. 42
0
def test_slightly_big():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key, test='a' * 254)
    h, p = bitjws.validate_deserialize(ser)
    assert h and p
Esempio n. 43
0
def test_big():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key, test='a' * 65536)
    h, p = bitjws.validate_deserialize(ser)
    assert h and p
Esempio n. 44
0
from bravado_bitjws.client import BitJWSSwaggerClient

host = "swagxample.deginner.com"
url = "http://swagxample.deginner.com/"
specurl = "%sstatic/swagger.json" % url
username = str(my_address)[0:8]

client = BitJWSSwaggerClient.from_url(specurl, privkey=privkey)

luser = client.get_model('User')(username=username)
user = client.user.addUser(user=luser).result()

print "registered as user\n%s" % user

##### Example of creating a coin with the more common requests package
import requests
import time

rawcoin = {'metal': 'I_approve_CTF1_game_for_1_BTC',
           'mint': '1AVV83Xa8E4yQGKrE4bZgi9rB2fDAEmySE'}
jwsdata = bitjws.sign_serialize(privkey, requrl="/coin",
                                iat=time.time(), data=rawcoin)
resp = requests.post("http://swagxample.deginner.com/coin", data=jwsdata,
                     headers={'content-type': 'application/jose'})
rawresp = resp.content.decode('utf8')
print "raw response\n%s" % rawresp
headers, payload = bitjws.validate_deserialize(rawresp, requrl="/response")
print "bitjws response body\n%s" % payload
print "bitjws response headers\n%s" % headers

Esempio n. 45
0
def test_slightly_big():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key, test='a' * 254)
    h, p = bitjws.validate_deserialize(ser)
    assert h and p
Esempio n. 46
0
def test_big():
    key = bitjws.PrivateKey()

    ser = bitjws.sign_serialize(key, test='a' * 65536)
    h, p = bitjws.validate_deserialize(ser)
    assert h and p
Esempio n. 47
0
import bitjws

# Load existing private key. In this example the server always
# create a new private key while the client loads an existing one.
wif = "KxZUqanyzZEGptbauar66cQo8bfGHwDauHogkxCaqTeMGY1stH6E"
priv = bitjws.wif_to_privkey(wif)
privkey = bitjws.PrivateKey(priv)
assert wif == bitjws.privkey_to_wif(privkey.private_key)
# The resulting bitcoin address can be derived for debugging
# purposes.
my_pubkey = privkey.pubkey.serialize()
my_address = bitjws.pubkey_to_addr(my_pubkey)
assert my_address == "1G9sChbyDSmuAXNVpjuRwakTmcHdxKGqpp"
print("My WIF key: {}".format(wif))
print("My key address: {}".format(my_address))

# Prepare a request to be sent. This one uses a single custom
# parameter named 'echo'.
echo_msg = "hello"
data = bitjws.sign_serialize(privkey, echo=echo_msg)
# Send and receive signed requests.
resp = requests.post("http://localhost:8001/", data=data)
headers, payload = bitjws.validate_deserialize(resp.content.decode("utf8"))
print(headers)  # headers['kid'] contains the key used by the server.
print(payload)

# In this example the server returns a response containing the
# echo parameter specified earlier and also a param named 'address'.
assert payload["echo"] == echo_msg
assert payload["address"] == my_address