

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 外掛程式 API 參考
<a name="sbomgen-plugin-api-reference"></a>

 完成 inspector-sbomgen Lua 外掛程式的 API 參考。如需撰寫外掛程式的指南，請參閱 [外掛程式開發人員指南](sbomgen-plugin-developer-guide.md)。如需測試，請參閱 [外掛程式測試指南](sbomgen-plugin-testing-guide.md)。

## 概觀
<a name="sbomgen-plugin-api-reference-overview"></a>

 所有執行時間提供的函數都可以透過全域`sbomgen`資料表 （檔案 I/O、regex、記錄、常數等） 存取。此外，每個外掛程式都會定義一組最上層全域函數 (`discover`、`subscribe_to_event`、、 等）， sbomgen `collect` `get_scanner_name`會在外掛程式生命週期中定義的點呼叫。這些會記錄在 中[外掛程式生命週期全域](#sbomgen-plugin-api-reference-plugin-lifecycle-globals)。

 在`*_test.lua`檔案內，sbomgen 還會公開`testing`全域，讓測試作者驅動 探索→集合管道並進行宣告。請參閱 [測試 API](#sbomgen-plugin-api-reference-testing-api)。

### 沙盒限制
<a name="sbomgen-plugin-api-reference-sandbox-restrictions"></a>

 外掛程式會在沙盒化 Lua VM 中執行，並限制標準程式庫存取。下列 Lua 標準程式庫模組**可供使用**：


| **模組** | **備註** | 
| --- | --- | 
| base | 核心函數 (print、type、tostring、tonumberpairs、、ipairs、pcallerror、selectunpack、、rawget、rawset、 等）。dofile、 loadfile和 loadstring會移除。 | 
| string | 完整字串操作 (string.match、string.findstring.format、、 string.gsub等） | 
| table | 完整資料表處理 table.remove(table.insert、table.sort、、 table.concat等） | 
| math | 完整數學程式庫 (math.floor、math.min、 math.max等） | 
| package | require() 可供使用，但僅限於外掛程式本身目錄樹狀目錄中的模組。父目錄周遊 (require("../shared")) 已封鎖。 package.cpath和 package.path已清除。 | 

 基於安全性和穩定性，**明確不允許**下列標準程式庫模組：


| **模組** | **原因** | 
| --- | --- | 
| io | 直接檔案系統存取已封鎖。所有檔案操作都必須經過 sbomgen.\*函數，這些函數會透過成品界面路由，跨成品類型 （目錄、容器、磁碟區等） 實現一致的行為。 | 
| os | 系統會封鎖系統層級操作 os.remove(os.execute、os.rename、os.getenv、 等），以防止外掛程式修改主機系統。 | 
| debug | 偵錯程式庫會遭到封鎖，以防止 Lua VM 內部的檢查或修改。 | 
| coroutine | 不會載入 Coroutine。 | 

 這些模組不在 VM 的允許清單中，且無法由外掛程式存取。

**注意**  
**重要：**所有檔案 I/O 必須通過 `sbomgen.*`函數 `sbomgen.read_file`（例如 、`sbomgen.open_file`、`sbomgen.get_file_list`)。使用 `io.open`或任何直接檔案系統存取都會引發執行時間錯誤。`sbomgen` API 可確保外掛程式與成品抽象層互動，無論掃描目錄、容器映像、封存或磁碟區，都能提供一致的行為。

## 外掛程式生命週期全域
<a name="sbomgen-plugin-api-reference-plugin-lifecycle-globals"></a>

 外掛程式是名為 的 Lua 檔案`init.lua`，可定義特定最上層全域函數。這些全域**不在**`sbomgen`資料表中 — 這些是外掛程式為 sbomgen 定義的函數。探索外掛程式和集合外掛程式之間的有效全域集不同。對於以下每個函數，如果外掛程式省略它，則會使用資料表中顯示的預設值。

### 探索外掛程式
<a name="sbomgen-plugin-api-reference-discovery-plugins"></a>


| **函數** | **Arity** | **必要** | **預設 （省略時）** | **Description** | 
| --- | --- | --- | --- | --- | 
| discover() | 0 | 是 | — | 傳回此外掛程式找到的檔案。傳回路徑字串的循序資料表 （單一事件模式） 或由事件名稱字串鍵入的資料表，其值為路徑資料表 （多事件模式）。 | 
| get\_event\_name() | 0 | 否 | "lua:{platform}/{category}/{ecosystem}" | 傳回發佈檔案的事件名稱。在所有探索外掛程式中必須是唯一的。 | 
| get\_scanner\_name() | 0 | 否 | 生態系統目錄名稱 | 傳回掃描器的顯示名稱。在所有探索外掛程式中必須是唯一的。 | 
| get\_scanner\_description() | 0 | 否 | "Lua discovery plugin: {ecosystem}" | 傳回人類可讀的描述。 | 
| get\_scanner\_groups() | 0 | 否 | 衍生自類別目錄 （請參閱開發人員指南） | 傳回掃描器群組字串的資料表。使用sbomgen.groups.\*常數。 | 
| get\_localhost\_scan\_paths() | 0 | 否 | — | 傳回掃描 localhost 成品時要包含的檔案/目錄路徑資料表。僅諮詢localhost掃描。 | 

### 集合外掛程式
<a name="sbomgen-plugin-api-reference-collection-plugins"></a>


| **函數** | **Arity** | **必要** | **預設 （省略時）** | **Description** | 
| --- | --- | --- | --- | --- | 
| collect(file\_path) | 1 | 是 | — | 每個發佈至訂閱事件的檔案呼叫一次。透過 剖析檔案並發出問題清單sbomgen.push\_package()。不傳回任何內容。 | 
| subscribe\_to\_event() | 0 | 否 | "lua:{platform}/{category}/{ecosystem}" | 傳回此收集器訂閱的事件名稱。應該符合對應的探索外掛程式 get\_event\_name()。 | 
| get\_collector\_name() | 0 | 否 | 生態系統目錄名稱 | 傳回收集器的顯示名稱。在所有集合外掛程式中必須是唯一的。 | 
| get\_collector\_description() | 0 | 否 | "" （空白） | 傳回人類可讀的描述。 | 

## 檔案 I/O
<a name="sbomgen-plugin-api-reference-file-i-o"></a>

 所有檔案操作都必須通過 `sbomgen.*` API。透過 Lua 程式`io`庫的直接檔案系統存取不可用 （請參閱 [沙盒限制](#sbomgen-plugin-api-reference-sandbox-restrictions))。`sbomgen` 檔案 I/O 函數會透過成品界面路由，確保無論在磁碟上掃描目錄、容器映像、壓縮封存或掛載磁碟區，您的外掛程式都能正常運作。

### `sbomgen.get_file_list()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-file-list"></a>

 以字串資料表的形式傳回成品中的所有檔案路徑。
+ **傳回：** `{string, ...}` — 絕對檔案路徑字串的資料表
+ **效能：**此函數會將成品中的每個檔案路徑複製到 Lua VM 中，做為 Lua 字串。在大型成品 （例如具有 300K\+ 檔案的 localhost 掃描） 上，這只需要幾秒鐘的時間。使用 在 Lua 中反覆運算傳回的資料表`string.match()`會增加額外額外負荷，完整掃描可能需要 15 秒以上。**成品中的檔案越多，外掛程式的速度就越慢。**

**注意**  
**盡可能偏好這些目標替代方案：**  


| **函數** | **使用時機...** | 
| --- | --- | 
| sbomgen.find\_files\_by\_name() | 您知道要比對的確切檔案名稱 （例如 "requirements.txt"、) "curl" | 
| sbomgen.find\_files\_by\_name\_icase() | 與上述相同，但不區分大小寫 | 
| sbomgen.find\_files\_by\_suffix() | 您需要比對路徑尾碼 （例如 "/pom.properties"、 "curlver.h") | 
| sbomgen.find\_files\_by\_path\_regex() | 您需要全路徑 regex 比對 | 
| sbomgen.glob\_find\_files() | 您需要 glob 樣式的 basename 比對 | 
這些函數會在 Lua VM 之外執行比對，並僅傳回比對的路徑，即使在 300K-file成品上也在 1 毫秒內完成。`get_file_list()` 只有當您的相符邏輯無法以上述任何項目表示時使用 。

```
-- AVOID in discovery plugins when possible:
local files = sbomgen.get_file_list()
for _, f in ipairs(files) do
    if string.match(f, "pattern$") then ... end
end

-- PREFER:
local matches = sbomgen.find_files_by_name({"target-file.txt"})
```

### `sbomgen.read_file(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-read-file-path"></a>

 讀取檔案的完整內容，並將其傳回為字串。
+ **傳回：** `string, err`
+ 失敗時： `nil, error_string`

```
local content, err = sbomgen.read_file("/app/package.json")
if err then
    sbomgen.log_error("read failed: " .. err)
    return
end
```

### `sbomgen.open_file(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-open-file-path"></a>

 開啟檔案以進行串流讀取。傳回 FileHandle 物件。將此用於大型檔案，其中將整個內容載入記憶體並不切實際。
+ **傳回：** `FileHandle, err`

```
local fh, err = sbomgen.open_file(path)
if err then return end
local line = fh:read_line()
while line do
    -- process line
    line = fh:read_line()
end
fh:close()
```

### `sbomgen.glob_find_files(pattern)`
<a name="sbomgen-plugin-api-reference-sbomgen-glob-find-files-pattern"></a>

 傳回符合 Go `filepath.Match` glob 模式的檔案。模式會與基本檔案名稱相符。
+ **傳回：** `{string, ...}, err`

```
local files, err = sbomgen.glob_find_files("*.txt")
```

 使用 `sbomgen.get_file_list()`搭配 `string.match`進行完整路徑模式比對。

### `sbomgen.find_files_by_name(names)`
<a name="sbomgen-plugin-api-reference-sbomgen-find-files-by-name-names"></a>

 傳回基底名稱 （最後一個路徑元件） 完全符合其中一個指定名稱的檔案。Go 中會發生反覆運算和比較，這比在 Lua `sbomgen.get_file_list()`中反覆運算明顯更快。
+ **參數：** `names` — 字串資料表 （要比對的基底名稱）
+ **傳回：**`{string, ...}`— 相符的檔案路徑 （無錯誤元組）

```
local curl_bins = sbomgen.find_files_by_name({"curl", "curl.exe"})
local headers = sbomgen.find_files_by_name({"curlver.h"})
```

### `sbomgen.find_files_by_name_icase(names)`
<a name="sbomgen-plugin-api-reference-sbomgen-find-files-by-name-icase-names"></a>

 傳回基底名稱符合其中一個指定名稱的檔案，忽略大小寫。例如， `"version"`符合 `VERSION`、 `Version`和 `version`。與 類似`find_files_by_name`，比對發生在 Lua VM 之外。
+ **參數：** `names` — 字串資料表 （要比對的基底名稱，不區分大小寫）
+ **傳回：**`{string, ...}`— 相符的檔案路徑 （無錯誤元組）

```
local version_files = sbomgen.find_files_by_name_icase({"version"})
local war_files = sbomgen.find_files_by_name_icase({"jenkins.war"})
```

### `sbomgen.find_files_by_suffix(suffixes)`
<a name="sbomgen-plugin-api-reference-sbomgen-find-files-by-suffix-suffixes"></a>

 傳回完整 forward-slash-normalized) 路徑以其中一個指定尾碼結尾的檔案。與 類似`find_files_by_name`，比對發生在 Lua VM 之外。
+ **參數：** `suffixes` — 字串資料表 （路徑尾碼要比對）
+ **傳回：**`{string, ...}`— 相符的檔案路徑 （無錯誤元組）

```
local pom_files = sbomgen.find_files_by_suffix({"/pom.properties"})
local release_headers = sbomgen.find_files_by_suffix({"ap_release.h", "opensslv.h"})
```

### `sbomgen.find_files_by_path_regex(patterns)`
<a name="sbomgen-plugin-api-reference-sbomgen-find-files-by-path-regex-patterns"></a>

 傳回其forward-slash-normalized路徑符合任何指定 Go (RE2) regex 模式的檔案。比對發生在 Lua VM 之外，這使得大型檔案清單更有效率。
+ **參數：** `patterns` — Go regex 字串的資料表
+ **傳回：**`{string, ...}`— 相符的檔案路徑 （無錯誤元組）
+ **引發：**如果任何模式無法編譯，Lua 錯誤

```
local configs = sbomgen.find_files_by_path_regex({"/etc/.*\\.conf$", "/opt/.*/config\\.json$"})
```

### 效能： `find_files_by_*` vs `get_file_list`
<a name="sbomgen-plugin-api-reference-performance-find-files-by-vs-get-file-list"></a>

 對於探索外掛程式，偏好 `find_files_by_name`、 `find_files_by_suffix`或 ，`find_files_by_path_regex`而不是在 Lua `get_file_list()`中反覆運算。在具有 300K 檔案的 localhost 掃描上，使用 在 Lua 中重複檔案清單`string.match()`大約需要 15 秒，而在 1 毫秒內`find_files_by_name`完成。差別在於， 會將每個檔案路徑`get_file_list()`複製到 Lua VM 做為字串，然後 Lua 會解譯每個路徑的迴圈和模式比對。`find_files_by_*` 函數會在 Lua VM 之外執行相符項目，並僅傳回相符路徑，避免複製和每個路徑的解釋額外負荷。

 `get_file_list()` 只有當您需要無法以 basename、尾碼或 regex 比對表示的自訂比對邏輯時，才使用 。

### `sbomgen.read_dir(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-read-dir-path"></a>

 列出目錄中的項目。
+ **傳回：** `{{name, is_dir}, ...}, err`

```
local entries, err = sbomgen.read_dir("/app/node_modules")
if err then return end
for _, e in ipairs(entries) do
    if e.is_dir then
        sbomgen.log_debug("directory: " .. e.name)
    end
end
```

### `sbomgen.file_stat(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-file-stat-path"></a>

 傳回檔案的中繼資料。
+ **傳回：** `{is_regular, is_dir, size}, err`

```
local info, err = sbomgen.file_stat(path)
if err then return end
if info.is_regular and info.size > 0 then
    -- process file
end
```

### `sbomgen.read_zip_entry(path, entry_path)`
<a name="sbomgen-plugin-api-reference-sbomgen-read-zip-entry-path-entry-path"></a>

 從 ZIP、JAR 或 WAR 封存檔讀取單一項目。
+ **傳回：** `string, err`

```
local manifest, err = sbomgen.read_zip_entry(
    "/app/lib/example.jar",
    "META-INF/MANIFEST.MF"
)
```

### `sbomgen.search_binary(path, regex)`
<a name="sbomgen-plugin-api-reference-sbomgen-search-binary-path-regex"></a>

 將檔案剖析為 ELF、PE 或 Mach-O 二進位檔，並搜尋預設常數/變數區段以取得 Go regex 比對。
+ **傳回：**`string|nil, err`— 相符的字串，如果不相符則為 nil

```
local version, err = sbomgen.search_binary(path, "Version:\\s+([\\d.]+)")
if version then
    sbomgen.log_info("found version: " .. version)
end
```

### `sbomgen.search_binary_all(path, regex [, n])`
<a name="sbomgen-plugin-api-reference-sbomgen-search-binary-all-path-regex-n"></a>

 將檔案剖析為 ELF、PE 或 Mach-O 二進位檔，並從預設常數/變數區段傳回所有唯一的第一個擷取群組比對。傳遞 `n` 以限制結果。
+ **傳回：**`{string, ...}|nil, err`— 相符字串的資料表，如果沒有相符項目，則為 nil

```
local versions, err = sbomgen.search_binary_all(path, "version[= ]+([\\d.]+)", 5)
if versions then
    for _, v in ipairs(versions) do
        sbomgen.log_info("found: " .. v)
    end
end
```

### `sbomgen.search_binary_raw(path, regex)`
<a name="sbomgen-plugin-api-reference-sbomgen-search-binary-raw-path-regex"></a>

 搜尋整個二進位檔案以進行第一個 regex 比對，不限於特定區段。當區段型搜尋 (`search_binary`) 不足時使用 - 例如，當版本字串位於非標準區段時。
+ **傳回：**`string|nil, err`— 相符的字串，如果不相符則為 nil

```
local version, err = sbomgen.search_binary_raw(path, "ProductVersion[\\x00\\s]+([\\d.]+)")
```

## FileHandle 方法
<a name="sbomgen-plugin-api-reference-filehandle-methods"></a>

 FileHandle 物件由 傳回`sbomgen.open_file()`。

### `fh:read_line()`
<a name="sbomgen-plugin-api-reference-fh-read-line"></a>

 讀取下一行 （不含換行字元）。在 EOF `nil`傳回 。
+ **傳回：** `string|nil, err`

### `fh:read(n)`
<a name="sbomgen-plugin-api-reference-fh-read-n"></a>

 最多可讀取 個`n`位元組。在 EOF `nil`傳回 。
+ **傳回：** `string|nil, err`

### `fh:close()`
<a name="sbomgen-plugin-api-reference-fh-close"></a>

 關閉檔案控制代碼。完成後一律關閉控點。

## 二進位公用程式
<a name="sbomgen-plugin-api-reference-binary-utilities"></a>

### `sbomgen.sha256(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-sha256-path"></a>

 傳回檔案內容的十六進位編碼 SHA-256 雜湊。
+ **傳回：** `string, err`

```
local hash, err = sbomgen.sha256("/app/bin/server")
if hash then
    sbomgen.log_info("SHA-256: " .. hash)
end
```

### `sbomgen.contains_bytes(path, patterns)`
<a name="sbomgen-plugin-api-reference-sbomgen-contains-bytes-path-patterns"></a>

 檢查檔案是否包含每個指定的位元組模式。以與輸入模式相同的順序傳回布林值資料表。
+ **傳回：** `{bool, ...}, err`

```
local results, err = sbomgen.contains_bytes(path, {
    "\xff Go buildinf:",   -- Go build identifier
    "/rustc/",             -- Rust build identifier
})
if results then
    local is_go = results[1]
    local is_rust = results[2]
end
```

### `sbomgen.get_pe_version_info(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-get-pe-version-info-path"></a>

 從二進位檔案剖析 Windows PE 版本資源。如果檔案不是 PE 二進位檔或沒有版本資源，`nil, err`則傳回具有版本欄位的資料表。
+ **傳回：** `{product_version, file_version, string_table}, err`

 `product_version` 和 `file_version` 欄位來自 PE `FixedFileInfo`結構，格式為 `"major.minor.build.revision"`。`string_table` 欄位是以**地區設定代碼** （例如`"040904B0"`，美國英文 Unicode) 為索引鍵的巢狀資料表。每個地區設定都會映射到從 PE `StringFileInfo`(`ProductVersion`、`FileDescription`、 `ProductName`等） 繪製的名稱/值對資料表。PE 二進位檔可能會公開一或多個地區設定。

```
local info, err = sbomgen.get_pe_version_info(file_path)
if err then return end

-- Fixed version fields (always flat)
local product_ver = info.product_version  -- e.g. "25.1.0.0"
local file_ver    = info.file_version     -- e.g. "25.1.0.0"

-- String table — iterate locales, or address a known locale by key
for locale, fields in pairs(info.string_table or {}) do
    sbomgen.log_info(string.format("%s ProductName=%s", locale, fields.ProductName or ""))
end

-- US English Unicode is the most common locale for PE files
local us = (info.string_table or {})["040904B0"]
if us then
    local display_ver = us.ProductVersion  -- e.g. "25.01"
    local name        = us.ProductName     -- e.g. "7-Zip"
end
```

### `sbomgen.parse_product_version(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-parse-product-version-path"></a>

 便利包裝函式，只傳回來自 PE 二進位的 FixedFileInfo 的產品版本字串。等同於呼叫`get_pe_version_info(path)`和讀取 `product_version`。
+ **傳回：** `string, err`

```
local version, err = sbomgen.parse_product_version(file_path)
if version then
    sbomgen.log_info("product version: " .. version)
end
```

### `sbomgen.parse_file_version(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-parse-file-version-path"></a>

 方便的包裝函式，只傳回來自 PE 二進位的 FixedFileInfo 的檔案版本字串。等同於呼叫`get_pe_version_info(path)`和讀取 `file_version`。
+ **傳回：** `string, err`

```
local version, err = sbomgen.parse_file_version(file_path)
if version then
    sbomgen.log_info("file version: " .. version)
end
```

## 套件輸出
<a name="sbomgen-plugin-api-reference-package-output"></a>

### `sbomgen.push_package(pkg)`
<a name="sbomgen-plugin-api-reference-sbomgen-push-package-pkg"></a>

 將套件問題清單推送至 SBOM。僅適用於集合外掛程式。

 `pkg` 資料表支援下列欄位：


| **欄位** | **類型** | **必要** | **Description** | 
| --- | --- | --- | --- | 
| name | string | 是 | 套件名稱 | 
| version | string | 否 | 已解析的版本字串 | 
| namespace | string | 否 | PURL 命名空間 （例如 "curl"、"wordpress/plugin") | 
| purl\_type | string | 是 | PURL 類型 "pypi" "npm"（例如 、、"cargo"、"deb"、"generic") | 
| component\_type | string | 是 | CycloneDX 元件類型；使用sbomgen.component\_types.\*常數 （例如 sbomgen.component\_types.LIBRARY) | 
| qualifiers | 資料表 | 否 | 做為鍵值對的 PURL 限定詞 （出現在套件 URL 中） | 
| properties | 資料表 | 否 | CycloneDX 元件屬性作為鍵值對 （請參閱 [CycloneDX 屬性](#sbomgen-plugin-api-reference-cyclonedx-properties)) | 
| children | 資料表 | 否 | 巢狀子套件，每個套件的形狀都與 相同 pkg（必要欄位會以遞迴方式驗證） | 

```
sbomgen.push_package({
    name = "requests",
    version = "2.28.1",
    purl_type = "pypi",
    component_type = sbomgen.component_types.LIBRARY,
    qualifiers = { example_qualifier = "example_qualifier_value" },
    properties = {
        -- Use your own namespace; amazon:inspector:* is reserved for Amazon Inspector.
        ["acme:example:extra_field"] = "example_value",
    },
})
```

## CycloneDX 屬性
<a name="sbomgen-plugin-api-reference-cyclonedx-properties"></a>

 CycloneDX 屬性是連接到 SBOM 中元件的鍵值中繼資料。它們與 PURL 限定詞不同：
+ **`qualifiers`** — PURL 限定詞。這些會成為套件 URL 字串 （例如 `pkg:deb/debian/curl@7.88.1?arch=amd64`) 的一部分。有些 PURL 限定詞對 Amazon Inspector 具有語意意義，並影響漏洞識別。請參閱[什麼是套件 URL？](https://docs.aws.amazon.com/inspector/latest/user/sbom-generator-purl-sbom.html) 適用於 Inspector 的每種類型慣例。
+ **`properties`** — CycloneDX 元件屬性。這些會出現在 SBOM 的`components[].properties`陣列中，不會變更元件的識別方式。

### 預留命名空間
<a name="sbomgen-plugin-api-reference-reserved-namespaces"></a>

 CycloneDX 屬性命名空間`amazon:inspector:*`系列保留給 Amazon Inspector：
+ `amazon:inspector:sbom_generator:*` — 供 sbomgen 及其內建掃描器使用。
+ `amazon:inspector:sbom_scanner:*` — 由 Amazon Inspector Scan API 使用。

 **外掛程式定義的屬性不得使用這些命名空間。**寫入預留命名空間可能會與 Inspector 依賴的值陰影或衝突，而產生的 SBOM 可能會在漏洞識別期間被錯誤解譯。如需預留金鑰的完整清單，請參閱[搭配 Amazon Inspector 使用 CycloneDX 命名空間](https://docs.aws.amazon.com/inspector/latest/user/cyclonedx-namespace.html)。

### 金鑰命名規則
<a name="sbomgen-plugin-api-reference-key-naming-rules"></a>

 傳遞給 `sbomgen.push_package()` 的屬性金鑰處理方式如下：


| **輸入金鑰** | **SBOM 中產生的金鑰** | **建議用於自訂外掛程式？** | 
| --- | --- | --- | 
| 包含 :（例如 acme:my\_plugin:field) | 逐字使用 | 是 — 將每個外掛程式定義的屬性放在您自己的命名空間中 | 
| 否 :（例如 field) | 自動字首為 amazon:inspector:sbom\_generator:field | 否 — 這會寫入預留命名空間 | 

 一律在您定義的屬性索引鍵中包含至少一個冒號。使用組織或外掛程式獨有的命名空間 （例如 `acme:python-pip:*`)：

```
properties = {
    -- Custom namespace — safe to use (recommended)
    ["acme:python-pip:manifest_path"] = file_path,
    ["acme:python-pip:pinned"]        = "true",

    -- Fully-qualified key outside amazon:inspector:* — also fine
    ["my:custom:namespace:key"] = "value",

    -- No colon: avoid — ends up as "amazon:inspector:sbom_generator:custom_field"
    -- custom_field = "value",
}
```

### sbomgen 設定的屬性
<a name="sbomgen-plugin-api-reference-properties-set-by-sbomgen"></a>

 Sbomgen 可以將自己的屬性連接到其發出的每個元件。這些值來自預留`amazon:inspector:sbom_generator:*`命名空間，不應由外掛程式產生。觀察到的執行時間行為：
+ `source_path` 一律由 sbomgen 新增。
+ `source_file_scanner` 啟用 時`source_package_collector`，會新增 `--enable-debug-props` 和 。

 Amazon Inspector 使用者指南中會維護預留金鑰的完整分類：[搭配 Amazon Inspector 使用 CycloneDX 命名空間](https://docs.aws.amazon.com/inspector/latest/user/cyclonedx-namespace.html)。

## 屬性常數
<a name="sbomgen-plugin-api-reference-property-constants"></a>

 內建屬性金鑰常數可透過 取得`sbomgen.properties`。以下每個常數都會解析為預留`amazon:inspector:sbom_generator:*`命名空間內的索引鍵。這些常數存在，因此 sbomgen 的內建掃描器會發出一致的屬性金鑰。**它們不是自訂外掛程式的延伸點** - 在自訂外掛程式中使用它們會寫入預留命名空間，這會隱藏 Inspector 依賴的值。請參閱[預留命名空間](#sbomgen-plugin-api-reference-reserved-namespaces)上述內容。

 自訂外掛程式作者應在自己的命名空間 （例如 `acme:my_plugin:*`) 下定義屬性，而不是重複使用這些常數。


| **常數** | **解析的值** | 
| --- | --- | 
| sbomgen.properties.NAMESPACE | amazon:inspector:sbom\_generator: | 
| sbomgen.properties.VENDOR | amazon:inspector:sbom\_generator:vendor | 
| sbomgen.properties.FILE\_SIZE\_BYTES | amazon:inspector:sbom\_generator:file\_size\_bytes | 
| sbomgen.properties.KERNEL\_COMPONENT | amazon:inspector:sbom\_generator:kernel\_component | 
| sbomgen.properties.RUNNING\_KERNEL | amazon:inspector:sbom\_generator:running\_kernel | 
| sbomgen.properties.UNRESOLVED\_VERSION | amazon:inspector:sbom\_generator:unresolved\_version | 
| sbomgen.properties.TRANSITIVE\_DEPENDENCY | amazon:inspector:sbom\_generator:experimental:transitive\_dependency | 
| sbomgen.properties.GO\_REPLACE\_DIRECTIVE | amazon:inspector:sbom\_generator:replaced\_by | 
| sbomgen.properties.DUPLICATE\_PACKAGE | amazon:inspector:sbom\_generator:is\_duplicate\_package | 
| sbomgen.properties.DUPLICATE\_PURL | amazon:inspector:sbom\_generator:duplicate\_purl | 
| sbomgen.properties.DOCKERFILE\_CHECK | amazon:inspector:sbom\_generator:dockerfile\_finding | 
| sbomgen.properties.CERTIFICATE\_FINDING | amazon:inspector:sbom\_generator:certificate\_finding | 
| sbomgen.properties.CERTIFICATE\_SUBJECT\_NAME | amazon:inspector:sbom\_generator:certificate:subject\_name | 
| sbomgen.properties.CERTIFICATE\_ISSUER\_NAME | amazon:inspector:sbom\_generator:certificate:issuer\_name | 
| sbomgen.properties.CERTIFICATE\_SIGNATURE\_ALGORITHM | amazon:inspector:sbom\_generator:certificate:signature\_algorithm | 
| sbomgen.properties.CERTIFICATE\_NOT\_VALID\_BEFORE | amazon:inspector:sbom\_generator:certificate:not\_valid\_before | 
| sbomgen.properties.CERTIFICATE\_NOT\_VALID\_AFTER | amazon:inspector:sbom\_generator:certificate:not\_valid\_after | 
| sbomgen.properties.WINDOWS\_REGISTRY\_KEY | amazon:inspector:sbom\_generator:registry\_key | 
| sbomgen.properties.SUBSCRIPTION\_ENABLED | amazon:inspector:sbom\_generator:subscription:enabled | 
| sbomgen.properties.SUBSCRIPTION\_NAME | amazon:inspector:sbom\_generator:subscription:name | 
| sbomgen.properties.SUBSCRIPTION\_LOCKED\_VERSION | amazon:inspector:sbom\_generator:subscription:locked\_version | 
| sbomgen.properties.OPENSSL\_FULL\_VERSION | amazon:inspector:sbom\_generator:openssl:full\_version | 
| sbomgen.properties.HARDENED\_IMAGE\_VENDOR | amazon:inspector:sbom\_generator:hardened\_image:vendor | 

## 掃描器群組
<a name="sbomgen-plugin-api-reference-scanner-groups"></a>

 探索外掛程式必須透過 宣告其掃描器群組`get_scanner_groups()`。群組會分類掃描器，並允許使用者選擇性地啟用或停用類別。常數可透過 取得`sbomgen.groups`：


| **常數** | **Value** | **Description** | 
| --- | --- | --- | 
| sbomgen.groups.OS | "os" | 作業系統套件管理員 (dpkg、rpm 等） | 
| sbomgen.groups.PROGRAMMING\_LANGUAGE | "programming-language-packages" | 語言套件管理員 (pip、npm、maven 等） | 
| sbomgen.groups.BINARY | "binary" | 編譯的二進位分析 (Go、Rust) | 
| sbomgen.groups.PACKAGE\_COLLECTOR | "pkg-scanner" | 一般套件集合 | 
| sbomgen.groups.EXTRA\_ECOSYSTEMS | "extra-ecosystems" | 其他生態系統 (curl、nginx 等） | 
| sbomgen.groups.CERTIFICATE | "certificate" | 憑證掃描 | 
| sbomgen.groups.CUSTOM | "custom" | 自動新增至透過 載入的所有自訂外掛程式 --plugin-dir | 
| sbomgen.groups.MACHINE\_LEARNING | "machine-learning" | 機器學習模型偵測 | 

 範例：

```
function get_scanner_groups()
    return {sbomgen.groups.PROGRAMMING_LANGUAGE, sbomgen.groups.PACKAGE_COLLECTOR}
end
```

## 元件類型常數
<a name="sbomgen-plugin-api-reference-component-type-constants"></a>

 中的 `component_type` 欄位`push_package()`必須是 CycloneDX 1.5 元件類型之一。常數可透過 取得`sbomgen.component_types`：


| **常數** | **Value** | 
| --- | --- | 
| sbomgen.component\_types.APPLICATION | "application" | 
| sbomgen.component\_types.FRAMEWORK | "framework" | 
| sbomgen.component\_types.LIBRARY | "library" | 
| sbomgen.component\_types.CONTAINER | "container" | 
| sbomgen.component\_types.PLATFORM | "platform" | 
| sbomgen.component\_types.OPERATING\_SYSTEM | "operating-system" | 
| sbomgen.component\_types.DEVICE | "device" | 
| sbomgen.component\_types.DEVICE\_DRIVER | "device-driver" | 
| sbomgen.component\_types.FIRMWARE | "firmware" | 
| sbomgen.component\_types.FILE | "file" | 
| sbomgen.component\_types.MACHINE\_LEARNING\_MODEL | "machine-learning-model" | 
| sbomgen.component\_types.DATA | "data" | 

 範例：

```
sbomgen.push_package({
    name = "requests",
    version = "2.28.1",
    purl_type = "pypi",
    component_type = sbomgen.component_types.LIBRARY,
})
```

## 平台常數
<a name="sbomgen-plugin-api-reference-platform-constants"></a>

 與 比較的常數`sbomgen.get_platform()`。可透過 取得`sbomgen.platform`：


| **常數** | **Value** | 
| --- | --- | 
| sbomgen.platform.LINUX | "linux" | 
| sbomgen.platform.WINDOWS | "windows" | 
| sbomgen.platform.DARWIN | "darwin" | 

 範例：

```
if sbomgen.get_platform() == sbomgen.platform.WINDOWS then
    -- Windows-specific logic
end
```

## 成品資訊
<a name="sbomgen-plugin-api-reference-artifact-info"></a>

### `sbomgen.get_platform()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-platform"></a>

 傳回執行時間平台字串 `"linux"`（例如 、`"windows"`、`"darwin"`)。

### `sbomgen.get_artifact_type()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-artifact-type"></a>

 傳回要掃描的成品類型 （例如 `"directory"`、 `"archive"`)。

### `sbomgen.should_collect_licenses()`
<a name="sbomgen-plugin-api-reference-sbomgen-should-collect-licenses"></a>

 `true` 如果使用者透過 啟用授權集合，則傳回 `--collect-licenses`。

### `sbomgen.get_env_vars()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-env-vars"></a>

 從成品傳回環境變數做為`{key, value}`項目資料表。

```
local env_vars = sbomgen.get_env_vars()
for _, env in ipairs(env_vars) do
    if env.key == "NODE_ENV" then
        sbomgen.log_info("Node environment: " .. env.value)
    end
end
```

### `sbomgen.get_system_drive()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-system-drive"></a>

 從成品的環境傳回系統磁碟機代號 （例如 `"C:"`)。讀取`SystemDrive`環境變數，`"C:"`若未設定，預設為 。這是相當於 的 Lua`strutils.GetSystemDriverLetter()`。

```
local drive = sbomgen.get_system_drive()
local program_files = drive .. "/Program Files/"
```

## 系統資訊
<a name="sbomgen-plugin-api-reference-system-info"></a>

 這些函數會傳回成品作業系統和硬體的相關中繼資料。如果資訊不可用 （例如，掃描沒有作業系統中繼資料的目錄時），值可能是空字串。


| **函數** | **傳回值** | 
| --- | --- | 
| sbomgen.get\_os\_name() | 作業系統名稱 （例如 "Ubuntu"、"Alpine Linux") | 
| sbomgen.get\_os\_version() | 作業系統版本 （例如 "22.04"、"3.18") | 
| sbomgen.get\_os\_codename() | 作業系統程式碼名稱 （例如，"jammy"、"bookworm") | 
| sbomgen.get\_os\_id() | 作業系統識別符 （例如 "ubuntu"、"alpine") | 
| sbomgen.get\_kernel\_name() | 核心名稱 （例如 "Linux") | 
| sbomgen.get\_kernel\_version() | 核心版本字串 | 
| sbomgen.get\_cpu\_arch() | CPU 架構 （例如 "x86\_64"、"aarch64") | 
| sbomgen.get\_hostname() | 系統的主機名稱 | 

## 一般表達式
<a name="sbomgen-plugin-api-reference-regular-expressions"></a>

 Lua 的內建模式缺少輪換 (`|`)、量化器範圍 (`{n,}`) 和 lookahead 等功能。為了縮小此差距，sbomgen 會直接公開 Go 的`regexp`套件。這些函數使用 Go regex 語法 (RE2)，而不是 Lua 模式。

### `sbomgen.regex_find(str, pattern)`
<a name="sbomgen-plugin-api-reference-sbomgen-regex-find-str-pattern"></a>

 傳回 Go regex 模式的第一個相符項目，或`nil`如果沒有相符項目，則傳回。
+ **傳回：** `string|nil, err`

```
local version = sbomgen.regex_find(content, "\\d+\\.\\d+\\.\\d+")
```

### `sbomgen.regex_match(str, pattern)`
<a name="sbomgen-plugin-api-reference-sbomgen-regex-match-str-pattern"></a>

 從第一個相符項目傳回擷取群組。索引 1 是完全相符，2\+ 是擷取群組。
+ **傳回：** `{string, ...}|nil, err`

```
local groups = sbomgen.regex_match(content, "(MySQL|MariaDB) (\\d+)\\.(\\d+)\\.(\\d+)")
if groups then
    local db_type = groups[2]   -- "MySQL" or "MariaDB"
    local major   = groups[3]
end
```

### `sbomgen.regex_find_all(str, pattern [, n])`
<a name="sbomgen-plugin-api-reference-sbomgen-regex-find-all-str-pattern-n"></a>

 傳回所有非重疊相符項目。傳遞`n`以限制結果 （預設值：全部）。
+ **傳回：** `{string, ...}|nil, err`

```
local versions = sbomgen.regex_find_all(content, "\\d+\\.\\d+\\.\\d+")
```

### `sbomgen.regex_replace(str, pattern, replacement)`
<a name="sbomgen-plugin-api-reference-sbomgen-regex-replace-str-pattern-replacement"></a>

 取代所有相符項目。取代字串可以使用 `$1`、 `$2`等 來擷取群組參考。
+ **傳回：** `string, err`

```
local cleaned = sbomgen.regex_replace(raw_version, "(1[6-9]\\d{8,}|buildkitsandbox.*)$", "")
```

### 何時使用 regex 與 Lua 模式
<a name="sbomgen-plugin-api-reference-when-to-use-regex-vs-lua-patterns"></a>

 將 Lua 的內建 `string.match`/`string.find` 用於簡單模式 — 它們速度更快，不需要逸出反斜線。當您需要`sbomgen.regex_*`時使用：
+ 變更： `(foo|bar)`
+ 量化器範圍： `\d{8,}`
+ Lua 模式無法表達的複雜角色類別

## 結構化剖析
<a name="sbomgen-plugin-api-reference-structured-parsing"></a>

 Sbomgen 公開輕量型協助程式，將結構化文字格式直接解碼為 Lua 資料表。

### `sbomgen.json_decode(str)`
<a name="sbomgen-plugin-api-reference-sbomgen-json-decode-str"></a>

 將 JSON 字串剖析為 Lua 資料表。
+ **傳回：** `table|nil, err`

```
local doc, err = sbomgen.json_decode('{"name":"requests","version":"2.28.1"}')
if err then return end
sbomgen.log_info(doc.name)
```

### `sbomgen.xml_decode(str)`
<a name="sbomgen-plugin-api-reference-sbomgen-xml-decode-str"></a>

 將 XML 字串剖析為 Lua 資料表。
+ **傳回：** `table|nil, err`

 XML 值使用下列形狀：
+ `_name` — 元素名稱
+ `_attr` — 屬性資料表，當存在時
+ `_text` — 裁剪文字內容，當存在時
+ 數值索引 `1..n` — 子元素

```
local doc, err = sbomgen.xml_decode('<package id="Newtonsoft.Json" version="13.0.3" />')
if err then return end
sbomgen.log_info(doc._attr.id)
```

## Windows 登錄檔
<a name="sbomgen-plugin-api-reference-windows-registry"></a>

 這些函數提供對 Windows 登錄檔的唯讀存取。在非 Windows 成品上， `registry_open_key`會傳回錯誤。登錄檔存取器會在第一次使用時延遲初始化，並支援即時 Windows API 存取 (Windows 上的本機主機掃描） 和檔案式 REGF hive 剖析 （容器/磁碟區掃描）。

### `sbomgen.registry_open_key(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-open-key-path"></a>

 開啟登錄機碼。傳回必須使用 關閉的金鑰控制代碼`registry_close`。
+ **傳回：** `key, err`

```
local key, err = sbomgen.registry_open_key("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\7-Zip")
if err then return end
-- use key...
sbomgen.registry_close(key)
```

### `sbomgen.registry_get_string(key, value_name)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-get-string-key-value-name"></a>

 從開啟的登錄機碼讀取字串值。
+ **傳回：** `string, err`

```
local version, err = sbomgen.registry_get_string(key, "DisplayVersion")
```

### `sbomgen.registry_get_integer(key, value_name)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-get-integer-key-value-name"></a>

 從開啟的登錄機碼讀取整數值。
+ **傳回：** `number, err`

### `sbomgen.registry_get_strings(key, value_name)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-get-strings-key-value-name"></a>

 從開啟的登錄機碼讀取多字串 (REG\_MULTI\_SZ) 值。傳回字串的資料表。
+ **傳回：** `{string, ...}, err`

```
local paths, err = sbomgen.registry_get_strings(key, "DependsOnService")
if paths then
    for _, p in ipairs(paths) do
        sbomgen.log_info("depends on: " .. p)
    end
end
```

### `sbomgen.registry_get_subkeys(key)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-get-subkeys-key"></a>

 傳回開啟登錄機碼下的所有子金鑰名稱。
+ **傳回：** `{string, ...}, err`

```
local subkeys, err = sbomgen.registry_get_subkeys(key)
for _, name in ipairs(subkeys) do
    local subkey, err = sbomgen.registry_open_key(parent_path .. "\\" .. name)
    -- ...
end
```

### `sbomgen.registry_close(key)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-close-key"></a>

 關閉登錄機碼控制代碼。垃圾收集器也會自動關閉金鑰控制代碼，但建議明確關閉。

## 記錄
<a name="sbomgen-plugin-api-reference-logging"></a>

 日誌訊息會寫入 sbomgen 的主控台輸出。外掛程式發出的每個訊息都會自動加上外掛程式來源標籤和生態系統的字首，例如：

```
[custom:python-pip] Parsing requirements.txt
```

 `log_info`、 `log_warn`和 `log_error`一律列印。 `log_debug`只會在使用 叫用 sbomgen 時列印`--verbose`。


| **函數** | **關卡** | **預設可見？** | 
| --- | --- | --- | 
| sbomgen.log\_debug(message) | DEBUG | 否 — 需要 --verbose | 
| sbomgen.log\_info(message) | INFO | 是 | 
| sbomgen.log\_warn(message) | WARN | 是 | 
| sbomgen.log\_error(message) | ERROR | 是 | 

 將 `string.format`用於格式化訊息：

```
sbomgen.log_info(string.format("found %d packages in %s", count, file_path))
```

## 偵錯 函數
<a name="sbomgen-plugin-api-reference-debugging-functions"></a>

### `sbomgen.breakpoint(message)`
<a name="sbomgen-plugin-api-reference-sbomgen-breakpoint-message"></a>

 列印`message`到 stderr 並封鎖執行，直到使用者按下 Enter。如果省略 `message` ， 會列印預設訊息。

 將此做為粗略偵錯工具使用，方法是將中斷點放置在外掛程式中的關鍵點，並使用 執行`--verbose`，以查看周圍的日誌輸出。

```
sbomgen.log_info("state: " .. some_variable)
sbomgen.breakpoint("paused after state dump — press Enter to continue")
```

## 測試 API
<a name="sbomgen-plugin-api-reference-testing-api"></a>

 全域`testing`資料表下的函數只能在 載入的外掛程式測試檔案 (`*_test.lua`) 內使用`inspector-sbomgen plugin test`。探索或集合外掛程式無法在執行時間使用這些外掛程式。測試檔案內也提供完整的 `sbomgen.*` API，但需要成品 （例如 `sbomgen.read_file()`) 的`sbomgen.*`函數只會在從掃描內呼叫時產生有意義的結果。如需敘述性指南，請參閱 [外掛程式測試指南](sbomgen-plugin-testing-guide.md)。

### 掃描函數
<a name="sbomgen-plugin-api-reference-scan-functions"></a>

 每個掃描函數都會建立指定類型的成品，針對該成品執行目前外掛程式的 探索→集合管道，並傳回結果調查結果。引`path`數會相對於測試檔案的目錄解析。


| **函數** | **成品種類** | 
| --- | --- | 
| testing.scan\_directory(path) | 目錄 | 
| testing.scan\_archive(path) | 目錄 ( 的別名scan\_directory) | 
| testing.scan\_localhost(path) | Localhost | 
| testing.scan\_binary(path) | 二進位 | 
| testing.scan\_volume(path) | 磁碟區 | 
| testing.scan\_container(path) | 容器 | 

 這六個都會傳回形狀如下的結果資料表。

### 結果形狀
<a name="sbomgen-plugin-api-reference-result-shape"></a>

 每個問題清單資料表只會投影下列欄位。特別是， `namespace`和 `purl_type` 不會單獨投影 - 它們會併入完整`purl`字串。

```
local result = testing.scan_directory("_testdata/example")
-- result.findings                        -- array of finding tables
-- result.findings[i].name                -- string
-- result.findings[i].version             -- string
-- result.findings[i].component_type      -- string
-- result.findings[i].purl                -- string (the full Package URL, or "" if none)
-- result.findings[i].properties          -- table<string, string>
-- result.findings[i].children            -- array of finding tables (same shape, recursive)
```

### 聲明
<a name="sbomgen-plugin-api-reference-assertions"></a>


| **函數** | **Signature** | **Description** | 
| --- | --- | --- | 
| testing.assert\_equals | (expected: any, actual: any, message?: string) | 如果 則失敗tostring(expected) \~= tostring(actual)。 | 
| testing.assert\_not\_equals | (expected: any, actual: any, message?: string) | 如果 則失敗tostring(expected) == tostring(actual)。 | 
| testing.assert\_true | (value: any, message?: string) | 如果 value為 false或 則失敗nil。 | 
| testing.assert\_false | (value: any, message?: string) | 如果 value不是 false，則失敗nil。 | 
| testing.assert\_nil | (value: any, message?: string) | 如果 value不是 則失敗nil。 | 
| testing.assert\_not\_nil | (value: any, message?: string) | 如果 value為 則失敗nil。 | 
| testing.assert\_contains | (haystack: string, needle: string, message?: string) | 如果 haystack 不包含 needle（子字串比對），則失敗。 | 
| testing.assert\_matches | (str: string, pattern: string, message?: string) | 如果 str 不符合指定的 Go (RE2) regex，則失敗。 | 
| testing.assert\_length | (tbl: table, expected: integer, message?: string) | 如果 \#tbl 不等於 ，則失敗expected。 | 

### 控制流程
<a name="sbomgen-plugin-api-reference-control-flow"></a>


| **函數** | **Signature** | **Description** | 
| --- | --- | --- | 
| testing.fail | (message: string) | 使用指定的訊息立即失敗目前的測試。 | 
| testing.skip | (message: string) | 略過目前的測試。結果會回報為略過，而非失敗。 | 

### 測試探索
<a name="sbomgen-plugin-api-reference-test-discovery"></a>

 名稱在檔案比對`test_`中以 開頭的任何全域 Lua 函數`*_test.lua`都會視為測試。測試檔案必須位於正常`{phase}/{platform}/{category}/{ecosystem}/`深度`init.lua`的 旁。修正資料會傳入測試檔案`_testdata/`旁 - 執行器在搜尋測試檔案`_testdata/`時不會下降至 。

## 錯誤處理
<a name="sbomgen-plugin-api-reference-error-handling"></a>

 可能失敗的 API 函數會傳回兩個值：`value, err`。成功時， `err`為 `nil`。失敗時，第一個值是 `nil`，而 `err`是錯誤字串。

```
local content, err = sbomgen.read_file(path)
if err then
    sbomgen.log_error("failed to read " .. path .. ": " .. err)
    return
end
-- content is safe to use here
```

 如果外掛程式引發未處理的 Lua 錯誤，sbomgen 會記錄警告並繼續下一個檔案或外掛程式。其他外掛程式不受影響。