免費開始
第 13b 章 客戶端、群組軟體與 CLI 管理:#pConfigFile

設定即程式碼:匯出、規劃、套用與 Git 管線

整個伺服器狀態以 YAML 檔案形式保存在 Git 中:租戶、網域(DKIM 選擇器、MTA-STS、路由)、含別名、轉寄和自動回覆的信箱、通訊群組清單、共用信箱、會議室、全域通訊錄與資源規則、共用與委派、SMTP、智慧主機、路由、傳輸規則、垃圾郵件與病毒防護、防火牆與自動封鎖、TLS、身分識別來源、API 金鑰(僅中繼資料)、Webhook、通知、維運警示、POP3、檔案、預約、封存以及 DNS 容錯移轉。nextxch-cli config plan 會像 terraform plan 一樣顯示將要建立、變更和刪除的內容;apply 會先檢查全部內容,再按固定順序套用。管理:系統 > 以檔案形式組態。

營運提示與架構說明

機密資訊絕對不會寫入檔案,也絕不匯出:密碼、權杖與金鑰會以 secretRef: {env: NAME} 或 secretRef: {file: path} 形式寫入,並在套用時解析(在 CI 執行器上由 nextxch-cli 解析;在伺服器上僅限 NEXTXCH_SECRET_* 變數以及 <data>/secrets/ 下方的檔案)。DKIM 金鑰、憑證與密碼雜湊保留在伺服器上。與 API v1 相同屬於 Business 功能;JSON Schema 為免費提供。

1. 檔案格式:apiVersion、kind、metadata.name、spec

一個檔案包含多個文件(以 --- 分隔),或一個資料夾中每個領域一個檔案(config export --split)。檔案中缺少的欄位在伺服器上保持不變;列表(別名、成員)作為整體計算。

參考 / 設定
# yaml-language-server: $schema=https://nextxch.com/schemas/nextxch-config-v1.schema.json
apiVersion: nextxch/v1
kind: Manifest            # optional: areas in which --prune may delete
metadata: {name: nextxch}
spec: {areas: [domains, accounts, sharing, transport]}
---
apiVersion: nextxch/v1
kind: Domain
metadata: {name: company.com}
spec:
  tenant: default
  catchAll: info@company.com
  dkim: {mode: dual, rsaSelector: s2026, ed25519Selector: ed2026}   # keys stay on the server
  mtaSts: {mode: enforce, maxAgeSeconds: 604800, mxHosts: [mail.company.com]}
---
apiVersion: nextxch/v1
kind: Account
metadata: {name: anna.smith@company.com}
spec:
  displayName: Anna Smith
  role: User                      # User, TenantAdmin, ServerAdmin, ComplianceAuditor
  quotaMb: 10240
  aliases: [anna@company.com]
  forwarding: {address: anna@private.example, keepCopy: true}
  outOfOffice: {enabled: false}
  password: {secretRef: {env: ANNA_PASSWORD}}   # never the password itself
---
apiVersion: nextxch/v1
kind: Account
metadata: {name: info@company.com}
spec: {type: shared, displayName: Info mailbox}   # user, shared, room, equipment
---
apiVersion: nextxch/v1
kind: Share
metadata: {name: "info@company.com/mailbox -> anna.smith@company.com"}
spec: {permissions: [read, write, sendAs]}
---
apiVersion: nextxch/v1
kind: SmtpSettings
metadata: {name: server}             # server-wide settings are always named "server"
spec:
  outboundSmartHost: smtp.provider.example
  outboundSmartPort: 587
  smartHostPassword: {secretRef: {file: secrets/smarthost.txt}}

2. 使用 nextxch-cli 的工作流程

先匯出並提交,然後透過 Pull Request 進行變更。計畫輸出範例:

參考 / 設定
export NEXTXCH_URL=https://mail.company.com
export NEXTXCH_API_KEY=smk_...            # key with config.read or config.write
nextxch-cli config export --split nextxch/
nextxch-cli config validate -f nextxch/    # offline: kinds and fields
nextxch-cli config plan -f nextxch/

  ~ Domain company.com
      mtaSts.mode: "testing" -> "enforce"
  ~ Account anna.smith@company.com
      quotaMb: 10240 -> 20480
      aliases: ["anna@company.com"] -> ["a.smith@company.com","anna@company.com"]
      ~ password: (secret changed)
  + Account info@company.com
      type: "shared"
      displayName: "Info mailbox"

Not in the file (1), deleted only with --prune:
    Account old@company.com

Plan: 1 to create, 2 to update, 0 to delete, 41 unchanged.
# exit code 2 = changes

nextxch-cli config apply -f nextxch/ --prune --yes
nextxch-cli config history

3. GitHub Actions:在提取要求時執行 plan,在合併時執行 apply

包含註解步驟的完整檔案:儲存庫中的 deploy/gitops/github-actions.yml。API 金鑰來自儲存庫密鑰,絕不來自該檔案。

參考 / 設定
name: nextxch config
on:
  pull_request: {paths: ["nextxch/**"]}
  push: {branches: [main], paths: ["nextxch/**"]}
permissions: {contents: read, pull-requests: write}
concurrency: {group: nextxch-config, cancel-in-progress: false}
env: {NEXTXCH_IMAGE: "nextxch/server:latest"}
jobs:
  plan:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Plan
        env:
          NEXTXCH_URL: ${{ vars.NEXTXCH_URL }}
          NEXTXCH_API_KEY: ${{ secrets.NEXTXCH_CONFIG_READ_KEY }}
        run: |
          set +e
          docker run --rm -e NEXTXCH_URL -e NEXTXCH_API_KEY -e NO_COLOR=1 -v "$PWD:/work" -w /work \
            --entrypoint nextxch-cli "$NEXTXCH_IMAGE" config plan -f nextxch/ --prune > plan.txt 2>&1
          code=$?; cat plan.txt; [ "$code" -ne 1 ]
      # danach: actions/github-script postet plan.txt als Kommentar (siehe deploy/gitops)
  apply:
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      - env:
          NEXTXCH_URL: ${{ vars.NEXTXCH_URL }}
          NEXTXCH_API_KEY: ${{ secrets.NEXTXCH_CONFIG_WRITE_KEY }}
          SMARTHOST_PASSWORD: ${{ secrets.SMARTHOST_PASSWORD }}
        run: |
          docker run --rm -e NEXTXCH_URL -e NEXTXCH_API_KEY -e SMARTHOST_PASSWORD -v "$PWD:/work" -w /work \
            --entrypoint nextxch-cli "$NEXTXCH_IMAGE" config apply -f nextxch/ --prune --yes

4. GitLab CI:以合併請求備註形式輸出 plan,在預設分支上執行 apply

完整檔案:deploy/gitops/gitlab-ci.yml。金鑰為已遮罩、受保護的 CI/CD 變數;resource_group 可防止兩個 apply 同時執行。

參考 / 設定
stages: [validate, plan, apply]
variables: {CONFIG_DIR: nextxch, NO_COLOR: "1"}
.nextxch-cli:
  image: {name: "nextxch/server:latest", entrypoint: [""]}
validate:
  extends: .nextxch-cli
  stage: validate
  script: [nextxch-cli config validate -f "$CONFIG_DIR"]
plan:
  extends: .nextxch-cli
  stage: plan
  rules: [{if: '$CI_PIPELINE_SOURCE == "merge_request_event"'}]
  variables: {NEXTXCH_API_KEY: $NEXTXCH_CONFIG_READ_KEY}
  script:
    - set +e
    - nextxch-cli config plan -f "$CONFIG_DIR" --prune > plan.txt 2>&1; code=$?
    - cat plan.txt; test "$code" -ne 1
  artifacts: {when: always, paths: [plan.txt]}
# plan-comment: curl auf /merge_requests/:iid/notes mit plan.txt (siehe deploy/gitops)
apply:
  extends: .nextxch-cli
  stage: apply
  resource_group: nextxch-config
  environment: production
  rules: [{if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'}]
  variables: {NEXTXCH_API_KEY: $NEXTXCH_CONFIG_WRITE_KEY}
  script: [nextxch-cli config apply -f "$CONFIG_DIR" --prune --yes]

5. 編輯器中的 JSON Schema 與 REST 呼叫

VS Code(Red Hat "YAML" 擴充功能)和 JetBrains IDE 會在輸入時檢查檔案。每台伺服器也在 /api/v1/config/schema 提供該結構描述。

參考 / 設定
# .vscode/settings.json
{
  "yaml.schemas": {
    "https://nextxch.com/schemas/nextxch-config-v1.schema.json": ["nextxch/*.yaml"]
  }
}

# Plan ohne CLI, direkt per REST (YAML als Body):
curl -s -X POST "$NEXTXCH_URL/api/v1/config/plan?prune=true" \
  -H "Authorization: Bearer $NEXTXCH_API_KEY" \
  -H "Content-Type: application/yaml" --data-binary @nextxch.yaml

6. 清單中的密鑰與無需重新啟動的 ACME

帶驗證標頭與來自管線的 HMAC 金鑰的 MTA 勾點、帶 Webhook 金鑰的警示目標,以及切換到使用 DNS-01 的 Let's Encrypt:一次套用,無需重新啟動。

參考 / 設定
apiVersion: nextxch/v1
kind: MtaFilters
metadata: {name: server}
spec:
  hooks:
    - name: spamcheck
      url: https://hooks.company.com/check
      stages: [data]
      authHeaderName: Authorization
      authHeaderValue: {secretRef: {env: HOOK_TOKEN}}   # in the plan: hooks[spamcheck].authHeaderValue
      hmacSecret: {secretRef: {file: secrets/hook-hmac.txt}}
---
apiVersion: nextxch/v1
kind: OpsAlerts
metadata: {name: server}
spec:
  targets:
    - name: pager
      type: webhook
      address: https://pager.company.com/hook
      secret: {secretRef: {env: PAGER_SECRET}}
---
apiVersion: nextxch/v1
kind: TlsSettings
metadata: {name: server}
spec:
  acme:
    enabled: true
    directoryUrl: https://acme-v02.api.letsencrypt.org/directory
    contactEmail: postmaster@company.com
    challenge: Dns01
    renewBeforeExpiryDays: 30

設定、預設值與最佳實務

設定 / 位置 說明 預設值 生產環境最佳實務
config export [--area a,b] [--split ordner/] [-o datei] 以確定性方式匯出伺服器狀態:固定文件順序、排序列表、無時間戳記。匯出兩次可得到相同的位元組,Git diff 僅顯示真實變更。 alle Bereiche 對儲存庫使用 --split(每個區域一個檔案:domains.yaml、accounts.yaml ...);小型 Pull Request 依然易於閱讀。
config plan -f datei|ordner [--prune] 按物件顯示 + 建立、~ 更新(欄位:舊值 -> 新值)與 - 刪除。結束代碼 0 = 無變更,2 = 有變更,1 = 錯誤。機密資訊僅顯示為 "(secret changed)"。 ohne Löschen 在提取請求上執行,並將結果作為評論發表(範例見下文)。
config apply -f ... [--prune] [--yes] [--force] [--dry-run] 先檢查所有內容(欄位、參照、機密、安全規則),然後按固定順序建立與更新(租戶、網域、帳號、清單、規則、共用、傳輸……),刪除則按相反順序進行。若某個步驟失敗,已完成的步驟將會復原。每項變更都會記錄至稽核日誌。 fragt nach 在管線中一律傳遞 --yes;否則在沒有終端機的情況下 apply 將會拒絕執行。--dry-run 等同於 plan。
--prune und Manifest 刪除僅在使用 --prune 時發生,且僅限 Manifest 文件所列的範圍(沒有 Manifest 時:僅限文件中出現的類型)。伺服器設定永遠不會被刪除。 aus 匯出會寫入 Manifest;如果您只管理部分內容,請縮小範圍。
Schutz: letzter Admin, Domain mit Postfächern 如果計劃會導致沒有任何活動的伺服器管理員,或要刪除仍有信箱的網域,則會被拒絕。--force 可強制執行(此時該網域會被停用而不是刪除)。API 金鑰不能吊銷自身。 aktiv 切勿在管線中硬式編碼 --force。
secretRef: {env: NAME} | {file: pfad} 參考至密碼遺失或機密,而非其值。nextxch-cli 會在執行器上解析它(任何變數、相對於設定的檔案)。伺服器本身僅讀取 NEXTXCH_SECRET_* 以及 <data>/secrets/ 下方的檔案。重新套用相同的值不會造成變更。 - 將機密從 GitHub/GitLab 機密儲存以環境變數形式傳遞給作業。
Scopes config.read / config.write REST:GET /api/v1/config/export、POST /api/v1/config/plan、POST /api/v1/config/apply、GET /api/v1/config/history、GET /api/v1/config/schema(免費)。金鑰:租戶整合金鑰;它們僅在其建立者仍為管理員時有效。伺服器管理員的金鑰可檢視整個伺服器,租戶管理員的金鑰僅可檢視該租戶。config.read 足以進行匯出與計畫,apply 則需要 config.write。 - 兩個金鑰:config.read 用於 Pull Request 中的 plan,config.write 僅用於 main 分支上的 apply 作業,並在可能的情況下限制在 Runner 的 IP 範圍內。
Mandanten-Admins 租戶管理員(會話或其某個金鑰)只能導出、規劃和應用其租戶內的對象:Domain(僅修改,不可創建或刪除)、Account、DistributionList、Share、GalVisibilityRule、ResourceAccessRule 和 Webhook。伺服器設置、租戶、身份源和 API 金鑰仍由伺服器管理員管理;角色為 ServerAdmin 或 ComplianceAuditor 的帳號不可操作。--prune 僅在自己的租戶內刪除,history 僅顯示自己的應用記錄。 - 適用於經銷商與部門:每個租戶使用自己的儲存庫與自己的金鑰。"tenant" 欄位可以省略,系統會自動填入自己的租戶。
secretRef in Listen 清單項目同樣透過 secretRef 接收密鑰:MtaFilters hooks[].authHeaderValue 與 hooks[].hmacSecret、OpsAlerts targets[].secret(Webhook 目標的 HMAC)。計畫透過其 id 或名稱來命名該項目,例如 hooks[spamcheck].authHeaderValue;清單中的明文值將遭到拒絕。 - 沒有 id 的項目會在首次套用時取得一個 id;匯出後請在檔案中保留這些 id,以便在重新排序清單時,密碼/祕密能正確對應到對應項目。
ACME zur Laufzeit TlsSettings.acme(enabled、directoryUrl、contactEmail、挑戰 Http01/TlsAlpn01/Dns01、renewBeforeExpiryDays、reusePrivateKeyForDane)無需重新啟動即可生效:appsettings.json 仍為基礎組態,差異保存在 <data>/acme-settings.json 中,並套用到整個叢集。變更目錄 URL 會在下一次訂單時建立新的 ACME 帳戶。 appsettings.json 請先使用 Let's Encrypt 測試目錄進行測試,然後再切換到生產環境。
Arten (kinds) Tenant、Domain、Account、DistributionList、GalVisibilityRule、ResourceAccessRule、Share、SmtpSettings、Route、TransportRules、SpamFilter、MtaFilters、FirewallRule、TlsSettings、IdentitySource、ApiKey、Webhook、Notifications、OpsAlerts、DnsFailover、Pop3、FileStorage、Booking、ArchivePolicy。所有欄位:JSON Schema。 - API 金鑰不會從檔案創建(其金鑰只存在一次);檔案可更改標籤和權限範圍,並透過 --prune 吊銷。會議室和預訂設置在每個叢集節點上保持一致。