接著我們寫一個單元測試來測試一下功能是否正確

先準備一個 test.zip,其中 test.zip 包含以下檔案: 

1. 一個文字檔名稱叫做 testfile.txt 文字檔 (內容不重要)

2. 一個資料夾名稱叫做 folder,這個 folder 放置一個檔案 infolderfile.txt 文字檔 (內容不重要)

Java - 解壓縮 (unzip),並寫一個單元測試進行測

並將這個準備好的測試檔案放到Spring Boot 專案 src/test/resources 的路徑下

如果沒有 resources 自己建一個 Directory,接著在 resources 在建立一個 test_unZip 的目錄

把 test.zip 放到 test_unZip 目錄下

Java - 解壓縮 (unzip),並寫一個單元測試進行測

接著就可以進行下面的測試程式撰寫

因為測試過程中會將 test.zip 進行解壓縮,並將解壓縮出來的檔案放置 unZip_result 目錄下

所以我們在測試完的最後,我們要把這個資料夾的內容刪除,這部分做在 teardown

另外補充一下,這邊可以看到我們並沒有預先建立 unZip_result 目錄,但程式還是能正常跑

這是因為 Path.resolve() 方法會根據給定的路徑解析出一個新的路徑。如果該路徑不存在,則在解析時會自動創建相應的目錄結構

 

ref: https://www.baeldung.com/java-compress-and-uncompress#unzip

 

------後續補充------

上述的程式寫法雖然程式可以work,但在做sonarqube的弱掃掃描的時候會出現安全性問題

Java - 解壓縮 (unzip),並寫一個單元測試進行測

Java - 解壓縮 (unzip),並寫一個單元測試進行測

在 zis.getNextEntrty()的時候,會有一個警告提醒「Make sure that expanding this archive file is safe here」

這是因為在解壓縮的時候並沒針對解出來的檔案做一些安全性檢查,隱藏著一些安全性問題

根據sonarqube的建議如下:

1. Define and control the ratio between compressed and uncompressed data, in general the data compression ratio for most of the legit archives is 1 to 3.

(定義並控制壓縮和解壓縮數據之間的比例,在一般情況下,大多數合法存檔的數據壓縮比為 1:3)

2. Define and control the threshold for maximum total size of the uncompressed data.

(定義並控制解壓縮後的數據的最大總大小閾值) 

3. Count the number of file entries extracted from the archive and abort the extraction if their number is greater than a predefined threshold

(計算從存檔中提取的文件條目的數量,如果它們的數量超過了預定的閾值,則中止提取)

 

最後,另外sonarqube有另外一個提醒:

Do not rely on getsize to retrieve the size of an uncompressed entry because this method returns what is defined in the archive headers which can be forged by attackers, instead calculate the actual entry size when unzipping it

(不要依賴 getsize 方法來檢索未壓縮條目的大小,因為該方法返回存檔標頭中定義的大小,這可能會被攻擊者偽造。相反,應在解壓縮時計算實際條目的大小)

 

因此根據以上建議,調整程式如下:

這樣調整完後,讓sonarqube在掃一次就沒問題了

 

arrow
arrow

    Mark Zhang 發表在 痞客邦 留言(0) 人氣()