szaszm commented on code in PR #2225:
URL: https://github.com/apache/nifi-minifi-cpp/pull/2225#discussion_r4083161748


##########
minifi_rust/extensions/minifi_pgp/src/processors/encrypt_content.rs:
##########
@@ -0,0 +1,392 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use minifi_native::{
+    FlowFileStreamTransform, GetAttribute, GetControllerService, GetId, 
GetProperty, InputStream,
+    Logger, MinifiError, OutputStream, ProcessError, RouteErrorExt, Schedule,
+    TransformStreamResult,
+};
+use pgp::composed::{ArmorOptions, MessageBuilder, SignedPublicKey};
+use pgp::types::{Password, StringToKey};
+
+use proc_def::*;
+
+use minifi_native::macros::{ComponentIdentifier, PropertyType};
+use strum_macros::{Display, EnumString, IntoStaticStr, VariantNames};
+
+#[derive(
+    Debug, Clone, Copy, PartialEq, Display, EnumString, VariantNames, 
IntoStaticStr, PropertyType,
+)]
+#[strum(serialize_all = "UPPERCASE", const_into_str)]
+enum FileEncoding {
+    Ascii,
+    Binary,
+}
+
+#[derive(Debug, ComponentIdentifier)]
+pub(crate) struct EncryptContentPGP {
+    file_encoding: FileEncoding,
+    symmetric_password: Option<Password>,
+}
+
+#[cfg(not(test))]
+fn string_to_key() -> StringToKey {
+    StringToKey::new_argon2(rand::thread_rng(), 3, 4, 16) // 64 MiB with 
rpgp's recommended parameter choice
+}
+
+#[cfg(test)]
+fn string_to_key() -> StringToKey {
+    StringToKey::new_argon2(rand::thread_rng(), 1, 1, 10) // fast for unit 
tests
+}
+
+impl EncryptContentPGP {
+    fn encrypt_bytes(
+        &self,
+        input_stream: &mut dyn InputStream,
+        output_stream: &mut dyn OutputStream,
+        pub_key: Option<&SignedPublicKey>,
+        file_name: String,
+    ) -> Result<(), MinifiError> {
+        if pub_key.is_none() && self.symmetric_password.is_none() {
+            return Err(MinifiError::custom(
+                "No password or public key to encrypt with",
+            ));
+        }
+
+        let mut builder = MessageBuilder::from_reader(file_name, 
input_stream).seipd_v1(
+            rand::thread_rng(),
+            pgp::crypto::sym::SymmetricKeyAlgorithm::AES256,
+        );
+
+        if let Some(pub_key) = pub_key {
+            builder
+                .encrypt_to_key(rand::thread_rng(), pub_key)
+                .map_err(MinifiError::other)?;
+        }
+
+        if let Some(password) = &self.symmetric_password {
+            builder
+                .encrypt_with_password(string_to_key(), password)
+                .map_err(MinifiError::other)?;
+        }
+
+        match self.file_encoding {
+            FileEncoding::Ascii => builder
+                .to_armored_writer(rand::thread_rng(), 
ArmorOptions::default(), output_stream)
+                .map_err(MinifiError::other),
+            FileEncoding::Binary => builder
+                .to_writer(rand::thread_rng(), output_stream)
+                .map_err(MinifiError::other),
+        }
+    }
+}
+
+impl Schedule for EncryptContentPGP {
+    fn schedule<P: GetProperty + GetControllerService, L: Logger>(
+        context: &P,
+        _logger: &L,
+    ) -> Result<Self, MinifiError>
+    where
+        Self: Sized,
+    {
+        let file_encoding = context.get_property(&FILE_ENCODING)?;
+        let symmetric_password = context.get_property(&SYMMETRIC_PASSPHRASE)?;
+
+        let public_key_service = 
context.get_controller_service(&PUBLIC_KEY_SERVICE)?;
+        let public_key_search = context.get_raw_property(&PUBLIC_KEY_SEARCH)?;

Review Comment:
   I forgot how get_raw_property differs from get_property or 
get_controller_service. Could you add a comment for get_raw_property? Does it 
skip validation, EL eval, or both?
   If it doesn't evaluate EL, then it looks good to me. If it does, then it can 
result in an empty expansion where the expression depends on flow file 
attributes, resulting in an error even when the configuration is correct.



##########
minifi_rust/extensions/minifi_pgp/src/controller_services/private_key_service.rs:
##########
@@ -0,0 +1,249 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#[cfg(test)]
+use crate::controller_services::key_lookup::key_matches;
+use minifi_native::macros::ComponentIdentifier;
+use minifi_native::{EnableControllerService, GetProperty, Logger, MinifiError};
+use pgp::composed::{SignedSecretKey, TheRing};
+#[cfg(test)]
+use pgp::types::KeyDetails;
+use service_def::*;
+
+#[derive(Debug, ComponentIdentifier)]
+pub(crate) struct PGPPrivateKeyService {
+    private_keys: Vec<SignedSecretKey>,
+    passphrase: pgp::types::Password,
+}
+
+impl EnableControllerService for PGPPrivateKeyService {
+    fn enable<P: GetProperty, L: Logger>(context: &P, _logger: &L) -> 
Result<Self, MinifiError>
+    where
+        Self: Sized,
+    {
+        let mut private_keys = 
context.get_property(&KEY_FILE)?.unwrap_or_default();
+        private_keys.extend(context.get_property(&KEY)?.unwrap_or_default());
+
+        let passphrase = 
context.get_property(&KEY_PASSWORD)?.unwrap_or_default();
+
+        if private_keys.is_empty() {
+            return Err(MinifiError::validation("Could not load any valid 
keys"));
+        }
+        Ok(Self {
+            private_keys,
+            passphrase,
+        })
+    }
+}
+
+impl PGPPrivateKeyService {
+    pub fn get_the_ring(&'_ self) -> TheRing<'_> {
+        TheRing {
+            secret_keys: self.private_keys.iter().collect(),
+            key_passwords: vec![&self.passphrase],
+            message_password: vec![],
+            session_keys: vec![],
+            decrypt_options: Default::default(),
+        }
+    }
+
+    #[cfg(test)]
+    pub fn get_secret_key(&self, target_id: &str) -> Option<&SignedSecretKey> {
+        self.private_keys.iter().find(|private_key| {
+            key_matches(
+                &private_key.primary_key.legacy_key_id(),
+                &private_key.details,
+                target_id,
+            )
+        })
+    }
+}
+
+mod service_def {
+    use crate::controller_services::key_file_property::SecretKeyFile;
+    use crate::controller_services::key_property::SecretKey;
+    use crate::controller_services::private_key_service::PGPPrivateKeyService;
+    use crate::utils;
+    use minifi_native::{
+        ControllerServiceDefinition, Property, PropertyDefinition, 
ProvidedInterface,
+        property_definitions,
+    };
+
+    pub(super) const KEY_FILE: Property<Option<SecretKeyFile>> = Property::new(
+        "Key File",
+        "File path to PGP Secret Key encoded in binary or ASCII Armor",
+    )
+    .supports_expression_language();
+
+    pub(super) const KEY: Property<Option<SecretKey>> =
+        Property::new("Key", "Secret Key encoded in ASCII Armor").sensitive();

Review Comment:
   Is this identical to the Keyring property in the NiFi equivalent? If so, I'd 
rename this one too, and Key file to Keyring file.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to