Skip to content

tls setup err handling #24

Description

@ybrs

⚠️ Potential issue

setup_tls may panic when no private key is found

pkcs8_private_keys(...).collect::<Vec<_>>()?.remove(0) assumes at least one key.
If the file is empty or contains unsupported key formats, remove(0) triggers an index-out-of-bounds panic at runtime, converting a recoverable IO/parse failure into a hard crash.

-    let key = pkcs8_private_keys(&mut BufReader::new(File::open(key_path)?))
-        .map(|key| key.map(PrivateKeyDer::from))
-        .collect::<Result<Vec<PrivateKeyDer>, IOError>>()?
-        .remove(0);
+    let mut keys = pkcs8_private_keys(&mut BufReader::new(File::open(key_path)?))
+        .map(|k| k.map(PrivateKeyDer::from))
+        .collect::<Result<Vec<PrivateKeyDer>, IOError>>()?;
+
+    let key = keys
+        .pop()
+        .ok_or_else(|| IOError::new(ErrorKind::InvalidData, "no private key found in PEM file"))?;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

fn setup_tls(cert_path: &str, key_path: &str) -> Result<Arc<TlsAcceptor>, IOError> {
    let cert = certs(&mut BufReader::new(File::open(cert_path)?))
        .collect::<Result<Vec<CertificateDer>, IOError>>()?;

    let mut keys = pkcs8_private_keys(&mut BufReader::new(File::open(key_path)?))
        .map(|k| k.map(PrivateKeyDer::from))
        .collect::<Result<Vec<PrivateKeyDer>, IOError>>()?;

    let key = keys
        .pop()
        .ok_or_else(|| IOError::new(ErrorKind::InvalidData, "no private key found in PEM file"))?;

    let mut config = ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(cert, key)
        .map_err(|err| IOError::new(ErrorKind::InvalidInput, err))?;

    config.alpn_protocols = vec![b"postgresql".to_vec()];

    Ok(Arc::new(TlsAcceptor::from(Arc::new(config))))
}
🤖 Prompt for AI Agents
In src/lib.rs around lines 726 to 743, the setup_tls function calls remove(0) on
the vector of private keys without checking if the vector is empty, which can
cause a panic if no keys are found. To fix this, check if the collected private
keys vector is empty before calling remove(0); if it is empty, return an
appropriate error instead of panicking. This ensures the function handles
missing or unsupported keys gracefully by returning a recoverable error.

Originally posted by @coderabbitai[bot] in #23 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions