Esempio n. 1
0
    def test_valid(self):
        bar_builder = GroupBuilder('my_bar',
                                   attributes={'data_type': 'Bar', 'attr1': text('a string attribute')},
                                   datasets=[DatasetBuilder('data', 100, attributes={'attr2': 10})])

        foo_builder = GroupBuilder('my_foo',
                                   attributes={'data_type': 'Foo', 'foo_attr': text('example Foo object')},
                                   groups=[bar_builder])

        results = self.vmap.validate(foo_builder)
        self.assertEqual(len(results), 0)
Esempio n. 2
0
    def getSpecs(self):
        bar = GroupSpec('A test group specification with a data type',
                        data_type_def='Bar',
                        datasets=[
                            DatasetSpec('an example dataset',
                                        'int',
                                        name='data',
                                        attributes=[
                                            AttributeSpec(
                                                'attr2',
                                                'an example integer attribute',
                                                'int')
                                        ])
                        ],
                        attributes=[
                            AttributeSpec('attr1',
                                          text('an example string attribute'),
                                          'text')
                        ])
        foo = GroupSpec('A test group that contains a data type',
                        data_type_def='Foo',
                        groups=[
                            GroupSpec('A Bar group for Foos',
                                      name='my_bar',
                                      data_type_inc='Bar')
                        ],
                        attributes=[
                            AttributeSpec(
                                'foo_attr',
                                'a string attribute specified as text',
                                'text',
                                required=False)
                        ])

        return (bar, foo)
Esempio n. 3
0
 def test_valid(self):
     builder = GroupBuilder('my_bar',
                            attributes={'data_type': 'Bar', 'attr1': text('a string attribute')},
                            datasets=[DatasetBuilder('data', 100, attributes={'attr2': 10})])
     validator = self.vmap.get_validator('Bar')
     result = validator.validate(builder)
     self.assertEqual(len(result), 0)
Esempio n. 4
0
 def test_invalid_missing_req_type(self):
     foo_builder = GroupBuilder('my_foo', attributes={'data_type': 'Foo',
                                                      'foo_attr': text('example Foo object')})
     results = self.vmap.validate(foo_builder)
     self.assertIsInstance(results[0], MissingDataType)  # noqa: F405
     self.assertEqual(results[0].name, 'Foo')
     self.assertEqual(results[0].reason, 'missing data type Bar')
Esempio n. 5
0
    def test_invalid_wrong_name_req_type(self):
        bar_builder = GroupBuilder('bad_bar_name',
                                   attributes={'data_type': 'Bar', 'attr1': 'a string attribute'},
                                   datasets=[DatasetBuilder('data', 100, attributes={'attr2': 10})])

        foo_builder = GroupBuilder('my_foo',
                                   attributes={'data_type': 'Foo', 'foo_attr': text('example Foo object')},
                                   groups=[bar_builder])

        results = self.vmap.validate(foo_builder)
        self.assertEqual(len(results), 1)
        self.assertIsInstance(results[0], MissingDataType)  # noqa: F405
        self.assertEqual(results[0].data_type, 'Bar')
Esempio n. 6
0
    def WampSessionProcMapper(funcname):
        wampfuncname = text('.'.join((ID, funcname)))

        def catcher_func(*args, **kwargs):
            if _WampSession is not None:
                try:
                    return threads.blockingCallFromThread(
                        reactor, _WampSession.call, wampfuncname,
                        *args, **kwargs)
                except TransportLost:
                    confnodesroot.logger.write_error(_("Connection lost!\n"))
                    confnodesroot._SetConnector(None)
                except Exception:
                    errmess = traceback.format_exc()
                    confnodesroot.logger.write_error(errmess+"\n")
                    print(errmess)
                    # confnodesroot._SetConnector(None)
            return PLCObjDefaults.get(funcname)
        return catcher_func
Esempio n. 7
0
    def onJoin(self, details):
        global _WampSession
        _WampSession = self
        ID = self.config.extra["ID"]

        for name, kwargs in ExposedCalls:
            try:
                registerOptions = types.RegisterOptions(**kwargs)
            except TypeError as e:
                registerOptions = None
                print(_("TypeError register option: {}".format(e)))

            self.register(GetCallee(name), u'.'.join((ID, name)), registerOptions)

        for name in SubscribedEvents:
            self.subscribe(GetCallee(name), text(name))

        for func in DoOnJoin:
            func(self)

        print(_('WAMP session joined (%s) by:' % time.ctime()), ID)
Esempio n. 8
0
    def RegisterWampClient():

        # start logging to console
        # log.startLogging(sys.stdout)

        # create a WAMP application session factory
        component_config = types.ComponentConfig(
            realm=text(realm),
            extra={"ID": ID})
        session_factory = wamp.ApplicationSessionFactory(
            config=component_config)
        session_factory.session = cls

        # create a WAMP-over-WebSocket transport client factory
        transport_factory = WampWebSocketClientFactory(
            session_factory,
            url=url,
            serializers=[MsgPackSerializer()])

        # start the client from a Twisted endpoint
        conn = connectWS(transport_factory)
        confnodesroot.logger.write(_("WAMP connecting to URL : %s\n") % url)
        return conn
Esempio n. 9
0
def get_md5hash(self):
    c = text(self.msgid) + text(self.msgstr) + text(self.msgctxt)
    return md5(c.encode("utf8")).hexdigest()
Esempio n. 10
0
 def __getitem__(self, key):
     return text(getattr(self, key))
Esempio n. 11
0
def create(options):
    key = ec.generate_private_key(ec.SECP256R1(), default_backend())
    options.key_output.write(
        key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()))
    # Various details about who we are. For a self-signed certificate the
    # subject and issuer are always the same.
    subjectList = []
    try:
        if options.country:
            subjectList += [
                x509.NameAttribute(x509.oid.NameOID.COUNTRY_NAME,
                                   text(options.country))
            ]
        if options.state:
            subjectList += [
                x509.NameAttribute(x509.oid.NameOID.STATE_OR_PROVINCE_NAME,
                                   text(options.state))
            ]
        if options.locality:
            subjectList += [
                x509.NameAttribute(x509.oid.NameOID.LOCALITY_NAME,
                                   text(options.locality))
            ]
        if options.organization:
            subjectList += [
                x509.NameAttribute(x509.oid.NameOID.ORGANIZATION_NAME,
                                   text(options.organization))
            ]
        if options.common_name:
            subjectList += [
                x509.NameAttribute(x509.oid.NameOID.COMMON_NAME,
                                   text(options.common_name))
            ]
        if len(subjectList) == 0:
            subjectList += [
                x509.NameAttribute(x509.oid.NameOID.COMMON_NAME,
                                   text('localhost'))
            ]
        subject = issuer = x509.Name(subjectList)
    except ValueError as e:
        LOG.critical('Error creating certificate: {}'.format(e.message))
        fname = options.output_file.name
        options.output_file.close()
        os.remove(fname)
        return 1

    subjectKey = key.public_key().public_bytes(
        serialization.Encoding.DER,
        serialization.PublicFormat.SubjectPublicKeyInfo)
    subjectKeyIdentifier = utils.sha_hash(
        subjectKey)[:160 // 8]  # Use RFC7093, Method 1

    try:
        cert = x509.CertificateBuilder().subject_name(subject).issuer_name(
            issuer).public_key(key.public_key(
            )).serial_number(x509.random_serial_number()).not_valid_before(
                datetime.datetime.utcnow()).not_valid_after(
                    datetime.datetime.utcnow() +
                    datetime.timedelta(days=options.valid_time)).add_extension(
                        x509.KeyUsage(digital_signature=True,
                                      content_commitment=False,
                                      key_encipherment=False,
                                      data_encipherment=False,
                                      key_agreement=False,
                                      key_cert_sign=False,
                                      crl_sign=False,
                                      encipher_only=False,
                                      decipher_only=False),
                        critical=False).add_extension(
                            x509.SubjectAlternativeName(
                                [x509.DNSName(u"localhost")]),
                            critical=False,
                        ).add_extension(
                            x509.ExtendedKeyUsage(
                                [x509.oid.ExtendedKeyUsageOID.CODE_SIGNING]),
                            critical=False,
                        ).add_extension(
                            x509.SubjectKeyIdentifier(subjectKeyIdentifier),
                            critical=False,
                            # Sign our certificate with our private key
                        ).sign(key, hashes.SHA256(), default_backend())
    except ValueError as e:
        LOG.critical('Error creating certificate: {}'.format(e.message))
        fname = options.output_file.name
        options.output_file.close()
        os.remove(fname)
        return 1
    # Write our certificate out to disk.
    options.output_file.write(cert.public_bytes(serialization.Encoding.DER))
    options.output_file.close()
    print(
        '[\033[1;93mWARNING\033[1;0m]: Certificates generated with this tool are self-signed and for testing only',
        file=sys.stderr)
    if options.valid_time < 10 * 365.25:
        print(
            '[\033[1;93mWARNING\033[1;0m]: This certificate is valid for {} days. For production,'
            'use certificates with at least 10 years validity.'.format(
                options.valid_time),
            file=sys.stderr)

    return 0
Esempio n. 12
0
def PublishEventWithOwnID(eventID, value):
    if getWampStatus() == "Attached":
        _WampSession.publishWithOwnID(text(eventID), value)
Esempio n. 13
0
 def publishWithOwnID(self, eventID, value):
     ID = self.config.extra["ID"]
     self.publish(text(ID+'.'+eventID), value)