class Validator: from voluptuous import Schema, Required, Optional, Range, All, Or, And SENSOR_SCHEMA = Schema({ Required("entity"): str, Required("op"): And(str, Op.from_str), Required("value"): Or(float, int) }) SCHEMA = Schema( { Optional("for", default="5m"): utils.parse_duration_literal, # Lights on for x seconds Required("lights"): Or([str], lambda v: [v] if isinstance(v, str) else []), Required("motion"): Or([str], lambda v: [v] if isinstance(v, str) else []), Optional("sensor", default=[]): Or([SENSOR_SCHEMA], lambda v: [Validator.SENSOR_SCHEMA(v)]) }, extra=True) @classmethod def validate(cls, dct): return cls.SCHEMA(dct)
from .objects.errors import ObjectFormatError from .objects.meta import Meta from .objects.stage import stage as ostage from .objects.transfer import transfer as otransfer from .scheme import Schemes from .utils import relpath from .utils.fs import path_isin if TYPE_CHECKING: from .objects.db.base import ObjectDB logger = logging.getLogger(__name__) CHECKSUM_SCHEMA = Any( None, And(str, Length(max=0), SetTo(None)), And(Any(str, And(int, Coerce(str))), Length(min=3), Lower), ) CASE_SENSITIVE_CHECKSUM_SCHEMA = Any( None, And(str, Length(max=0), SetTo(None)), And(Any(str, And(int, Coerce(str))), Length(min=3)), ) # NOTE: currently there are only 3 possible checksum names: # # 1) md5 (LOCAL, SSH); # 2) etag (S3, GS, OSS, AZURE, HTTP); # 3) checksum (HDFS); #
class DIDDoc(dict): """DIDDoc class for creating and verifying DID Docs.""" # DIDDoc specification is very flexible: https://w3c-ccg.github.io # This particular schema covers Ed25519 keys. All key types here: # https://w3c-ccg.github.io/ld-cryptosuite-registry/ EXPECTED_SERVICE_TYPE = 'IndyAgent' EXPECTED_SERVICE_SUFFIX = 'indy' PUBLIC_KEY_VALIDATOR = Schema({ "id": str, "type": "Ed25519VerificationKey2018", "controller": str, "publicKeyBase58": str }) VALIDATOR = Schema({ "@context": "https://w3id.org/did/v1", "id": str, "publicKey": [PUBLIC_KEY_VALIDATOR], # This is not fully correct; see: # https://w3c.github.io/did-core/#authentication Optional("authentication"): [ { "type": "Ed25519SignatureAuthentication2018", "publicKey": str }, PUBLIC_KEY_VALIDATOR, str ], "service": And( # Service contains at least one agent service AtLeastOne( { 'id': Match('.*;{}$'.format(EXPECTED_SERVICE_SUFFIX)), 'type': EXPECTED_SERVICE_TYPE, 'priority': int, 'recipientKeys': [str], Optional('routingKeys'): [str], 'serviceEndpoint': str }, msg='DID Communication service missing' ), # And all services match DID Spec [ { "id": str, "type": str, "serviceEndpoint": str, Extra: object # Allow extra values } ], ) }) def validate(self): """Validate this DIDDoc.""" self.update(DIDDoc.VALIDATOR(self)) @classmethod def make(cls, my_did, my_vk, endpoint): """Make a DIDDoc dictionary.""" return cls({ "@context": "https://w3id.org/did/v1", "id": my_did, "publicKey": [{ "id": my_did + "#keys-1", "type": "Ed25519VerificationKey2018", "controller": my_did, "publicKeyBase58": my_vk }], "service": [{ "id": my_did + ";indy", "type": "IndyAgent", "recipientKeys": [my_vk], "routingKeys": [], "serviceEndpoint": endpoint, }], }) @classmethod def parse_key_reference(cls, key: str): """Parse out a key reference if present; return the key otherwise.""" parts = key.split("#") return parts[1] if len(parts) > 1 else parts[0] def key_for_reference(self, key: str) -> Optional(str): """Find key matching reference.""" key = self.parse_key_reference(key) found_key = next(( public_key['publicKeyBase58'] for public_key in self.get('publicKey', []) if key in (public_key['id'], public_key['publicKeyBase58']) ), None) if not found_key: raise KeyReferenceError( 'No key found for reference {}'.format(key) ) return found_key def get_connection_info(self): """Extract connection information from DID Doc.""" service = next(filter( lambda service: service['type'] == DIDDoc.EXPECTED_SERVICE_TYPE, self['service'] ), None) if not service: raise NoSuitableService( 'No Service with type {} found in DID Document' .format(DIDDoc.EXPECTED_SERVICE_TYPE) ) return TheirInfo( # self['publicKey'][0]['controller'], # did service['serviceEndpoint'], # endpoint list(map( self.key_for_reference, service.get('recipientKeys', []) )), list(map( self.key_for_reference, service.get('routingKeys', []) )), )
from voluptuous import Or, Schema, Email, Optional, ALLOW_EXTRA, Length, And job_schema = Schema( { "id": Or(str, int), "email": Email(), Optional("name"): str }, required=True, extra=ALLOW_EXTRA, ) job_request_schema = Schema( { "jobs": And([job_schema], Length(min=1)), "template": str, "subject": str }, required=True, ) settings_schema = Schema({ "auth": { "user": str, "password": str }, "email_from": { "name": str, "email": Email() }, "headers": dict,
def empty_ok(x): return Or(x, And('', lambda y: type(x)()))
class EntityTypeHandler(Handler): def __init__(self): self.session = Session() def get(self, ident=None): if ident is None: return [ entity_type.to_dict() for entity_type in get_all(self.session, EntityType) ] else: return get_one(self.session, EntityType, id=ident).to_dict() @requires_validation( Schema({ Required('name'): non_empty_string, Required('tags'): And([non_empty_string], Unique()), Required('meta'): And([non_empty_string], Unique()), Required('series'): And([non_empty_string], Unique()), })) def post(self): data = self.request.data entity_type = EntityType(name=data['name']) self.session.add(entity_type) # add tags, meta and series for tag in data['tags']: self.session.add(TagAttribute( entity_type=entity_type, name=tag, )) for meta in data['meta']: self.session.add( MetaAttribute( entity_type=entity_type, name=meta, )) for series in data['series']: self.session.add( SeriesAttribute( entity_type=entity_type, name=series, )) self.session.commit() update_last_data_modification_ts(self.session) return { 'success': True, 'ID': entity_type.id, } @requires_validation(_assert_objects_were_not_created, with_route_params=True) @requires_validation( Schema({ 'name': non_empty_string, 'tags': And([non_empty_string], Unique()), 'meta': And([non_empty_string], Unique()), 'series': And([non_empty_string], Unique()), })) def put(self, ident): data = self.request.data entity_type = get_one(self.session, EntityType, id=ident) if 'name' in data: entity_type.name = data['name'] # add tags, meta and series if 'tags' in data: for tag in data['tags']: self.session.add( TagAttribute( entity_type=entity_type, name=tag, )) if 'meta' in data: for meta in data['meta']: self.session.add( MetaAttribute( entity_type=entity_type, name=meta, )) if 'series' in data: for series in data['series']: self.session.add( SeriesAttribute( entity_type=entity_type, name=series, )) self.session.commit() update_last_data_modification_ts(self.session) return { 'success': True, 'ID': entity_type.id, } def delete(self, ident): entity_type = get_one(self.session, EntityType, id=ident) now = time.time() entity_type.delete_ts = now for tag in entity_type.tags: tag.delete_ts = now for series in entity_type.series: series.delete_ts = now for alert in series.alerts: alert.delete_ts = now for meta in entity_type.meta: meta.delete_ts = now for entity in entity_type.nodes: entity.delete_ts = now for tag in entity.tags: tag.delete_ts = now for meta in entity.meta: meta.delete_ts = now for child in entity.children: child.parent = entity.parent self.session.commit() update_last_data_modification_ts(self.session) return {'success': True}