Skip to content

Conversation

pflynn-virtru
Copy link
Member

Proposed Changes

This pull request improves the robustness of the ECPrivateKeyFromPem function in ec_key_pair.go by adding support for parsing EC private keys in both PKCS8 and traditional EC formats. If parsing as PKCS8 fails, the function now attempts to parse the key as an EC private key before returning an error.

Key improvement to private key parsing:

  • Enhanced ECPrivateKeyFromPem to try parsing the input as a traditional EC private key if PKCS8 parsing fails, improving compatibility with different PEM-encoded EC key formats.

Checklist

  • I have added or updated unit tests
  • I have added or updated integration tests (if appropriate)
  • I have added or updated documentation

Testing Instructions

@pflynn-virtru pflynn-virtru requested a review from a team as a code owner September 23, 2025 18:04
Copy link
Contributor

Summary of Changes

Hello @pflynn-virtru, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the ECPrivateKeyFromPem function's ability to handle various PEM-encoded EC private key formats. By implementing a fallback mechanism, the system becomes more resilient to different key encodings, ensuring broader compatibility and reducing potential parsing failures when dealing with elliptic curve private keys.

Highlights

  • EC Private Key Parsing Robustness: The ECPrivateKeyFromPem function now attempts to parse EC private keys using the traditional EC format if parsing as PKCS8 fails, enhancing compatibility with various PEM-encoded key types.
  • Improved Error Handling: Error messages are more informative, providing details if parsing fails for both PKCS8 and traditional EC formats, aiding in debugging.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.


Key in PEM's embrace, PKCS8 first, then EC, Robust parse, secure.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request enhances EC private key parsing by adding a fallback to the traditional EC format if PKCS8 parsing fails. This is a good improvement for robustness. My review focuses on two main areas: error handling and testing. The error returned when both parsing methods fail can be improved to make both underlying errors programmatically inspectable. More critically, this change lacks unit tests to verify the new fallback logic and its failure modes. Adding comprehensive tests is essential to ensure the correctness of this cryptographic functionality and prevent future regressions.

Comment on lines 353 to 360
if err != nil {
return nil, fmt.Errorf("ec x509.ParsePKCS8PrivateKey failed: %w", err)
// If PKCS8 fails, try EC private key format
ecKey, ecErr := x509.ParseECPrivateKey(block.Bytes)
if ecErr != nil {
return nil, fmt.Errorf("failed to parse private key as PKCS8 or EC format: PKCS8 error: %w, EC error: %v", err, ecErr)
}
return ConvertToECDHPrivateKey(ecKey)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This change introduces new logic for parsing EC keys, but there are no corresponding unit tests as indicated by the unchecked item in the PR checklist. It's crucial to add unit tests to cover the new fallback behavior.

Please add tests for at least the following scenarios:

  • A key that is successfully parsed as a PKCS8 key.
  • A key that fails PKCS8 parsing but is successfully parsed as a traditional EC key (the new code path).
  • A key that fails both parsing methods.
  • Invalid input that fails pem.Decode.

Without tests, it's difficult to be confident in the correctness of this new logic and protect against future regressions.

// If PKCS8 fails, try EC private key format
ecKey, ecErr := x509.ParseECPrivateKey(block.Bytes)
if ecErr != nil {
return nil, fmt.Errorf("failed to parse private key as PKCS8 or EC format: PKCS8 error: %w, EC error: %v", err, ecErr)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current error message wraps the PKCS8 error (err) but only includes the EC error (ecErr) as a string. This prevents callers from programmatically inspecting ecErr using errors.Is or errors.As.

Since the project appears to use Go 1.20+ (indicated by the crypto/ecdh package), you can use errors.Join to wrap both errors. This makes the error handling more robust and idiomatic, allowing callers to inspect both underlying causes of failure.

Suggested change
return nil, fmt.Errorf("failed to parse private key as PKCS8 or EC format: PKCS8 error: %w, EC error: %v", err, ecErr)
return nil, errors.Join(fmt.Errorf("PKCS8: %w", err), fmt.Errorf("EC: %w", ecErr))

Copy link
Contributor

Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 185.639664ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 94.930089ms

Standard Benchmark Metrics Skipped or Failed

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 347.553739ms
Throughput 287.73 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 36.872086693s
Average Latency 366.947238ms
Throughput 135.60 requests/second

NANOTDF Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 25.800826369s
Average Latency 256.525756ms
Throughput 193.79 requests/second

priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("ec x509.ParsePKCS8PrivateKey failed: %w", err)
// If PKCS8 fails, try EC private key format
Copy link
Contributor

@b-long b-long Sep 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm somewhat surprised there's no logger in this file, but maybe that was a performance choice?

In any case, I was thinking a warning message might be useful just above the comment on line 354.

Printing to STDOUT here just as an example... I'll defer to others about the logger usage.

Suggested change
// If PKCS8 fails, try EC private key format
// Log warning about PKCS8 parsing failure
fmt.Printf("WARNING: ec x509.ParsePKCS8PrivateKey failed: %v\n", err)
// If PKCS8 fails, try EC private key format

@nibsbin
Copy link

nibsbin commented Sep 26, 2025

The bug persists.

Reproduce with my codespace on this branch: https://symmetrical-funicular-gv6xqxx76r3v5rx.github.dev/
Run ./linux_startup to reset the platform and run hello_world.js to test the encrypt() function.

Update: Codespaces might be unshareable. Use this script in a codespace based on this branch to reproduce on a standardized environment:

cp opentdf-dev.yaml opentdf.yaml

./.github/scripts/init-temp-keys.sh
sudo cp ./keys/localhost.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates

# Kill existing containers and start fresh
docker ps -aq | xargs -r docker rm -f
docker compose up -d

sleep 5
read -p "Are the docker containers ready? Press Enter to continue..."

go run ./service provision keycloak
go run ./service provision fixtures
go run ./service start &

sleep 5
read -p "Is the go service ready? Press Enter to continue..."

git clone https://github.com/nibsbin/opentdf-basekey-bug.git
cd opentdf-basekey-bug
npm run dev

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants