def AddCreateGatewayArgsToRequest(ref, args, req): """Python hook for yaml create command to process gateway flags.""" del ref gateway = args.device_type auth_method = args.auth_method # Don't set gateway config if no flags provided if not (gateway or auth_method): return req messages = devices.GetMessagesModule() req.device.gatewayConfig = messages.GatewayConfig() if auth_method: if not gateway or gateway == 'non-gateway': raise InvalidAuthMethodError( 'auth_method can only be set on gateway devices.') auth_enum = flags.GATEWAY_AUTH_METHOD_ENUM_MAPPER.GetEnumForChoice( auth_method) req.device.gatewayConfig.gatewayAuthMethod = auth_enum if gateway: gateway_enum = flags.CREATE_GATEWAY_ENUM_MAPPER.GetEnumForChoice( gateway) req.device.gatewayConfig.gatewayType = gateway_enum return req
def SetUp(self): self.messages = devices.GetMessagesModule( devices.GetClientInstance(no_http=True)) temp_dir = files.TemporaryDirectory() self.temp_path = temp_dir.path self.addCleanup(temp_dir.Close)
def ParseRegistryCredential(path, messages=None): messages = messages or devices.GetMessagesModule() contents = _ReadKeyFileFromPath(path) format_enum = messages.PublicKeyCertificate.FormatValueValuesEnum return messages.RegistryCredential( publicKeyCertificate=messages.PublicKeyCertificate( certificate=contents, format=format_enum.X509_CERTIFICATE_PEM))
def SetUp(self): self.messages = devices.GetMessagesModule( devices.GetClientInstance(no_http=True)) self.format_enum = self.messages.PublicKeyCertificate.FormatValueValuesEnum temp_dir = files.TemporaryDirectory() self.temp_path = temp_dir.path self.addCleanup(temp_dir.Close)
def ParseCredential(path, type_str, expiration_time=None, messages=None): messages = messages or devices.GetMessagesModule() type_ = _ConvertStringToFormatEnum(type_str, messages) contents = _ReadKeyFileFromPath(path) if expiration_time: expiration_time = times.FormatDateTime(expiration_time) return messages.DeviceCredential(expirationTime=expiration_time, publicKey=messages.PublicKeyCredential( format=type_, key=contents))
def RegistriesDevicesListRequestHook(ref, args, req): """Add Api field query string mappings to list requests.""" del ref del args msg = devices.GetMessagesModule() updated_requests_type = ( msg.CloudiotProjectsLocationsRegistriesDevicesListRequest) for req_field, mapped_param in _CUSTOM_JSON_FIELD_MAPPINGS.items(): encoding.AddCustomJsonFieldMapping(updated_requests_type, req_field, mapped_param) return req
def AddUnBindArgsToRequest(ref, args, req): """Python hook for yaml gateways unbind command to process resource_args.""" del ref messages = devices.GetMessagesModule() gateway_ref = args.CONCEPTS.gateway.Parse() device_ref = args.CONCEPTS.device.Parse() registry_ref = gateway_ref.Parent() unbind_request = messages.UnbindDeviceFromGatewayRequest( deviceId=device_ref.Name(), gatewayId=gateway_ref.Name()) req.unbindDeviceFromGatewayRequest = unbind_request req.parent = registry_ref.RelativeName() return req
def ParseCredentials(public_keys, messages=None): """Parse a DeviceCredential from user-supplied arguments. Returns a list of DeviceCredential with the appropriate type, expiration time (if provided), and contents of the file for each public key. Args: public_keys: list of dict (maximum 3) representing public key credentials. The dict should have the following keys: - 'type': Required. The key type. One of [es256, rs256] - 'path': Required. Path to a valid key file on disk. - 'expiration-time': Optional. datetime, the expiration time for the credential. messages: module or None, the apitools messages module for Cloud IoT (uses a default module if not provided). Returns: List of DeviceCredential (possibly empty). Raises: TypeError: if an invalid public_key specification is given in public_keys ValueError: if an invalid public key type is given (that is, neither es256 nor rs256) InvalidPublicKeySpecificationError: if a public_key specification is missing a required part, or too many public keys are provided. InvalidKeyFileError: if a valid combination of flags is given, but the specified key file is not valid or not readable. """ messages = messages or devices.GetMessagesModule() if not public_keys: return [] if len(public_keys) > MAX_PUBLIC_KEY_NUM: raise InvalidPublicKeySpecificationError( ('Too many public keys specified: ' '[{}] given, but maximum [{}] allowed.').format( len(public_keys), MAX_PUBLIC_KEY_NUM)) credentials = [] for key in public_keys: _ValidatePublicKeyDict(key) credentials.append( ParseCredential(key.get('path'), key.get('type'), key.get('expiration-time'), messages=messages)) return credentials
def ParseMetadata(metadata, metadata_from_file, messages=None): """Parse and create metadata object from the parsed arguments. Args: metadata: dict, key-value pairs passed in from the --metadata flag. metadata_from_file: dict, key-path pairs passed in from the --metadata-from-file flag. messages: module or None, the apitools messages module for Cloud IoT (uses a default module if not provided). Returns: MetadataValue or None, the populated metadata message for a Device. Raises: InvalidMetadataError: if there was any issue parsing the metadata. """ if not metadata and not metadata_from_file: return None metadata = metadata or dict() metadata_from_file = metadata_from_file or dict() if len(metadata) + len(metadata_from_file) > MAX_METADATA_PAIRS: raise InvalidMetadataError( 'Maximum number of metadata key-value pairs ' 'is {}.'.format(MAX_METADATA_PAIRS)) if set(metadata.keys()) & set(metadata_from_file.keys()): raise InvalidMetadataError('Cannot specify the same key in both ' '--metadata and --metadata-from-file.') total_size = 0 messages = messages or devices.GetMessagesModule() additional_properties = [] for key, value in six.iteritems(metadata): total_size += len(key) + len(value) additional_properties.append( _ValidateAndCreateAdditionalProperty(messages, key, value)) for key, path in metadata_from_file.items(): value = _ReadMetadataValueFromFile(path) total_size += len(key) + len(value) additional_properties.append( _ValidateAndCreateAdditionalProperty(messages, key, value)) if total_size > MAX_METADATA_SIZE: raise InvalidMetadataError('Maximum size of metadata key-value pairs ' 'is 256KB.') return messages.Device.MetadataValue( additionalProperties=additional_properties)
def SetUp(self): self.messages = devices.GetMessagesModule( devices.GetClientInstance(no_http=True)) self.StartObjectPatch(times, 'LOCAL', tz.tzutc()) self.format_enum = self.messages.PublicKeyCredential.FormatValueValuesEnum temp_dir = files.TemporaryDirectory() self.temp_path = temp_dir.path self.addCleanup(temp_dir.Close) self.rsa_key_path = self.Touch(self.temp_path, 'id_rsa.pub', contents=_DUMMY_RSA_FILE_CONTENTS) self.ecdsa_key_path = self.Touch(self.temp_path, 'id_ecdsa.pub', contents=_DUMMY_ECDSA_FILE_CONTENTS) self.bad_key_path = os.path.join(self.temp_path, 'bad.pub')