Skip to content

Implement MySQL Encode()/Decode() function by AES - #17568

Merged
mergify[bot] merged 8 commits into
matrixorigin:mainfrom
charleschile:feature/aes-encode-decode
Jul 29, 2024
Merged

mergify[bot] merged 8 commits into
matrixorigin:mainfrom
charleschile:feature/aes-encode-decode

Conversation

@charleschile

@charleschile charleschile commented Jul 16, 2024 •

Copy link
Copy Markdown
Contributor

User description

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #15027

What this PR does / why we need it:

Implement Encode() and Decode() functions by AES


PR Type

Feature, Tests


Description

  • Implemented AES-based Encode and Decode functions in func_unary.go.
  • Added helper functions for SHA256 key generation and initialization vector creation.
  • Registered the new functions in list_builtIn.go with appropriate overloads.
  • Added unit tests for the new functions in func_unary_test.go.
  • Included BVT test cases and results for the new functions.

Changes walkthrough 📝

Relevant files
Feature
func_unary.go
Implement AES-based Encode and Decode Functions                   

pkg/sql/plan/function/func_unary.go

  • Added AES-based encode and decode functions.
  • Introduced helper functions for key and IV generation.
  • Implemented Encode and Decode functions for AES encryption and
    decryption.
  • +81/-0   
    list_builtIn.go
    Register AES Encode and Decode Functions                                 

    pkg/sql/plan/function/list_builtIn.go

  • Registered new encode and decode functions.
  • Defined overloads for the new functions.
  • +42/-0   
    Tests
    func_unary_test.go
    Add Unit Tests for AES Encode and Decode Functions             

    pkg/sql/plan/function/func_unary_test.go

  • Added unit tests for AES encode and decode functions.
  • Initialized test cases for encode and decode functions.
  • +161/-0 
    func_decode_encode.result
    Add BVT Test Results for AES Encode and Decode                     

    test/distributed/cases/function/func_decode_encode.result

    • Added BVT test results for AES encode and decode functions.
    +39/-0   
    func_decode_encode.sql
    Add BVT Test Cases for AES Encode and Decode                         

    test/distributed/cases/function/func_decode_encode.sql

    • Added BVT test cases for AES encode and decode functions.
    +13/-0   

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    @mergify mergify Bot added the kind/feature label Jul 16, 2024
    @matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Jul 16, 2024
    @qodo-code-review

    Copy link
    Copy Markdown

    PR-Agent was enabled for this repository. To continue using it, please link your git user with your CodiumAI identity here.

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 PR contains tests
    🔒 Security concerns

    Predictable IV:
    The method generateInitializationVector generates an IV that could be predictable if the same encryption key and plaintext length are used repeatedly. This can compromise the security of the encryption scheme by making it easier for an attacker to derive the IV and potentially decrypt the data.

    ⚡ Key issues to review

    Security Concern
    The implementation of AES encryption uses a static IV generation method based on the key and plaintext length. This could lead to predictable IVs if the same key and similar plaintext lengths are used repeatedly, which is not recommended for secure encryption practices.

    Error Handling
    The function encodeByAES and decodeByAES do not handle errors that might occur during the encryption or decryption process other than those thrown by aes.NewCipher. Consider adding error handling for other potential issues, such as problems during the stream processing.

    @qodo-code-review

    Copy link
    Copy Markdown

    PR-Agent was enabled for this repository. To continue using it, please link your git user with your CodiumAI identity here.

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Security
    Improve the security and unpredictability of the initialization vector

    Instead of appending a single byte to the key data for generating the initialization
    vector, consider using a more robust method such as HMAC or a secure random
    generator to ensure the IV's uniqueness and unpredictability.

    pkg/sql/plan/function/func_unary.go [1067-1070]

    -data := append(key, byte(length))
    -hash := sha256.Sum256(data)
    -return hash[:aes.BlockSize]
    +iv := make([]byte, aes.BlockSize)
    +if _, err := rand.Read(iv); err != nil {
    +    return nil, err
    +}
    +return iv
     
    • Apply this suggestion
    Suggestion importance[1-10]: 10

    Why: Using a secure random generator for the initialization vector instead of appending a single byte to the key data ensures the IV's uniqueness and unpredictability, which is essential for maintaining the security of the encryption process.

    10
    Enhance security by using a secure key derivation function

    Replace the use of sha256.Sum256 directly with a more secure key derivation function
    like bcrypt or scrypt for generating the encryption key. This will enhance the
    security by providing a key derivation function that includes a salt and is
    resistant to brute force attacks.

    pkg/sql/plan/function/func_unary.go [1061-1064]

    -hash := sha256.Sum256(key)
    -return hash[:]
    +// Example using bcrypt
    +salt := []byte("your-random-salt")
    +derivedKey, err := bcrypt.GenerateFromPassword(key, bcrypt.DefaultCost)
    +if err != nil {
    +    return nil, err
    +}
    +return derivedKey[:32]
     
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: The suggestion to replace sha256.Sum256 with a more secure key derivation function like bcrypt or scrypt significantly enhances security by making the key derivation process resistant to brute force attacks. This is a crucial improvement for cryptographic functions.

    9
    Error handling
    Add detailed error handling for cipher block creation failures

    Add error handling for the aes.NewCipher function to handle potential failures in
    cipher block creation, which can occur if the key size is not supported.

    pkg/sql/plan/function/func_unary.go [1078-1080]

     block, err := aes.NewCipher(fixedKey)
     if err != nil {
    -    return err
    +    return fmt.Errorf("failed to create cipher block: %w", err)
     }
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Adding detailed error handling for aes.NewCipher improves the robustness of the code by providing more informative error messages, which can help in debugging and maintaining the code.

    7

    @fengttt fengttt left a comment

    Copy link
    Copy Markdown
    Contributor

    Choose a reason for hiding this comment

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

    lgtm, thank you.

    @charleschile

    Copy link
    Copy Markdown
    Contributor Author

    @heni02 @m-schen @aressu1985 To be review.

    @mergify
    mergify Bot merged commit 5a98c53 into matrixorigin:main Jul 29, 2024
    triump2020 added a commit to triump2020/matrixone that referenced this pull request Aug 1, 2024
    * support restore pitr phase2 (matrixorigin#17772)
    
    support restore pitr phase2
    
    Approved by: @iamlinjunhong, @daviszhen
    
    * split merge receivers from join operators  (matrixorigin#17759)
    
    从channel里收数据的任务应该只由merge算子来完成,join算子只负责call子节点,而不是直接访问channel
    
    Approved by: @aunjgr, @m-schen
    
    * fix unnecessary pipeline broken (matrixorigin#17777)
    
    以前的pipeline会在阻塞算子处断开。现在不需要这个逻辑了。避免pipeline在不必要的地方断开。
    
    Approved by: @ouyuanning, @XuPeng-SH
    
    * fix unnecessary merge scope in broadcast join (matrixorigin#17778)
    
    减少broadcast join中不必要的merge scope,减少pipeline的打断
    
    Approved by: @ouyuanning
    
    * [bug] stats: fix nil pointer (matrixorigin#17767)
    
    fix nil pointer in Merge function of stats info
    
    Approved by: @zhangxu19830126
    
    * Implement MySQL Encode()/Decode() function by AES (matrixorigin#17568)
    
    Implement Encode() and Decode() functions by AES
    
    Approved by: @fengttt, @heni02, @m-schen
    
    * Revert "fix unnecessary merge scope in broadcast join (matrixorigin#17778)" (matrixorigin#17787)
    
    先revert引入问题的pr,再继续调查
    
    Approved by: @ouyuanning
    
    * container/types: make empty Packer valid for use (matrixorigin#17780)
    
    Some packers may be used after Close. Make them work.
    
    Approved by: @XuPeng-SH
    
    * add sql length metric (matrixorigin#17792)
    
    增加sql 长度监控项。用于定位问题。
    
    Approved by: @qingxinhome
    
    * reduce flush&merge memory usage (matrixorigin#17768)
    
    1. reduce `TransferDestPos` size from 12B to 8B, which can reduce ~25%(16B -> 12B) memory usage for transfer map.
    2. During a merge commit, avoid creating a map with rowid as values to save memory. Only generate the corresponding rowid when needed for transfer, using the TransferMap produced by the merge and createObjs.
    
    Result:
    Before:
    ![tmp k3FnO9DlPr](https://github.com/user-attachments/assets/b40ba6f0-f6d5-4d2c-9aad-191ae47f2280)
    
    
    After:
    ![tmp sbw8STJdBx](https://github.com/user-attachments/assets/29abd2a3-0346-409e-858b-664bfa8d0033)
    
    Diff:
    ![image](https://github.com/user-attachments/assets/cf16f961-1df4-4b24-bb75-686a1b16753d)
    
    Approved by: @LeftHandCold, @zhangxu19830126, @XuPeng-SH
    
    * refactor the three tables (matrixorigin#17721)
    
    * Revert "Small reader update (#75)"
    
    This reverts commit f39edde.
    
    * Revert "Revert "Small reader update (#75)""
    
    This reverts commit a414863.
    
    * support restore cluster by pitr (matrixorigin#17796)
    
    support restore cluster by pitr
    
    Approved by: @iamlinjunhong, @daviszhen
    
    * fix bug: panic when get vector (type.Oid is T_any) from pool (matrixorigin#17801)
    
    fix bug: panic when get vector (type.Oid is T_any) from pool
    
    Approved by: @m-schen, @XuPeng-SH, @aunjgr
    
    * remove unnecessary merge scope in broadcast join (matrixorigin#17808)
    
    在某些场景下,broadcast join的probe端会merge不止一次。 这个pr的目标是保证一定只merge一次。
    之前测试场景覆盖不够充分,现在已经重新跑了多个测试场景。
    
    Approved by: @m-schen, @ouyuanning, @aunjgr
    
    * refactor message framework (matrixorigin#17786)
    
    该pr本身没有实质性逻辑改动,将message从process包中独立出来,并修改message的api接口,为后续重构做准备
    
    Approved by: @qingxinhome, @triump2020, @m-schen, @ouyuanning, @fengttt, @aunjgr, @XuPeng-SH
    
    * Handle data race when get table def (matrixorigin#17774)
    
    * Session disable agg stmt (matrixorigin#17802)
    
    change
    1. support session variable `disable_agg_statement`
    - default: off
    - if set on, this session will do NO statement aggregation.
    2. base on `disable_agg_statement`, fix 2 bvt case
    - case: result_count.sql
    - case: statement_query_type_1.sql
    
    Approved by: @heni02, @daviszhen
    
    * fileservice: add active reader metrics to object storage (matrixorigin#17799)
    
    more metrics for active object storage readers.
    
    Approved by: @zhangxu19830126, @fengttt
    
    * More constant fold for expression executor (matrixorigin#17779)
    
    More constant fold for expression executor
    
    Approved by: @m-schen, @heni02
    
    * Mo inspect checkpoint command (matrixorigin#17795)
    
    Support for online commands of Checkpoint analysis tools
    
    Approved by: @aptend, @LeftHandCold, @XuPeng-SH
    
    * merge main
    
    * make pb
    
    ---------
    
    Co-authored-by: YANGGMM <[email protected]>
    Co-authored-by: nitao <[email protected]>
    Co-authored-by: LiuBo <[email protected]>
    Co-authored-by: Charles Chi Le <[email protected]>
    Co-authored-by: reusee <[email protected]>
    Co-authored-by: davis zhen <[email protected]>
    Co-authored-by: Wei Ziran <[email protected]>
    Co-authored-by: aptend <[email protected]>
    Co-authored-by: ou yuanning <[email protected]>
    Co-authored-by: qingxinhome <[email protected]>
    Co-authored-by: Jackson <[email protected]>
    Co-authored-by: Wenbin <[email protected]>
    fengttt pushed a commit to fengttt/matrixone that referenced this pull request May 7, 2026
    Implement Encode() and Decode() functions by AES
    
    Approved by: @fengttt, @heni02, @m-schen
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Labels

    kind/feature Review effort [1-5]: 3 size/M Denotes a PR that changes [100,499] lines Tests

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    4 participants