def _EnsureSSHKeyExistsForUser(self, fetcher, user): """Ensure the user's public SSH key is known by the Account Service.""" public_key = self.keys.GetPublicKey().ToEntry(include_comment=True) should_upload = True try: user_info = fetcher.LookupUser(user) except user_client.UserException: owner_email = gaia.GetAuthenticatedGaiaEmail(self.http) fetcher.CreateUser(user, owner_email) user_info = fetcher.LookupUser(user) for remote_public_key in user_info.publicKeys: if remote_public_key.key.rstrip() == public_key: expiration_time = remote_public_key.expirationTimestamp if expiration_time and time_util.IsExpired(expiration_time): # If a key is expired we remove and reupload fetcher.RemovePublicKey(user_info.name, remote_public_key.fingerprint) else: should_upload = False break if should_upload: fetcher.UploadPublicKey(user, public_key) return True
def _UpdateWindowsKeysValue(self, existing_metadata): """Returns a string appropriate for the metadata. Values are removed if they have expired and non-expired keys are removed from the head of the list only if the total key size is greater than MAX_METADATA_VALUE_SIZE_IN_BYTES. Args: existing_metadata: The existing metadata for the instance to be updated. Returns: A new-line-joined string of Windows keys. """ # Get existing keys from metadata. windows_keys = [] self.old_metadata_keys = [] for item in existing_metadata.items: if item.key == METADATA_KEY: windows_keys = [key.strip() for key in item.value.split('\n') if key] if item.key in OLD_METADATA_KEYS: self.old_metadata_keys.append(item.key) # Append new key. windows_keys.append(self.windows_key_entry) # Remove expired and excess key entries. keys = [] bytes_consumed = 0 for key in reversed(windows_keys): # Keys should be removed in FIFO order. num_bytes = len(key + '\n') key_expired = False # Try to determine if key is expired. Ignore any errors. try: key_data = json.loads(key) if time_util.IsExpired(key_data['expireOn']): key_expired = True # Errors should come in two forms: Invalid JSON (ValueError) or missing # 'expireOn' key (KeyError). except (ValueError, KeyError): pass if key_expired: log.debug('The following Windows key has expired and will be removed ' 'from your project: {0}'.format(key)) elif (bytes_consumed + num_bytes > constants.MAX_METADATA_VALUE_SIZE_IN_BYTES): log.debug('The following Windows key will be removed from your project ' 'because your windows keys metadata value has reached its ' 'maximum allowed size of {0} bytes: {1}' .format(constants.MAX_METADATA_VALUE_SIZE_IN_BYTES, key)) else: keys.append(key) bytes_consumed += num_bytes log.debug('Number of Windows Keys: {0}'.format(len(keys))) keys.reverse() return '\n'.join(keys)