收集 Recordia 記錄

支援的服務:

本文說明如何使用 Google Cloud Storage V2,將 Recordia 記錄檔擷取至 Google Security Operations。

Recordia (Comunycarse 推出) 是通話錄音和法規遵循平台,適用於金融服務和客服中心。這項解決方案可擷取及封存語音和影片互動,並提供品質管理、法規遵循和數據分析工具。剖析器會從 Recordia 通話中繼資料和稽核事件擷取欄位,並對應至統合式資料模型 (UDM),擷取工作階段詳細資料、來電者/被來電者資訊、使用者活動和安全性嚴重性。

事前準備

請確認您符合下列必要條件:

  • Google SecOps 執行個體
  • 已啟用 Cloud Storage API 的 GCP 專案
  • 建立及管理 GCS bucket 的權限
  • 具備管理 GCS bucket IAM 政策的權限
  • 建立 Cloud Run 服務、Pub/Sub 主題和 Cloud Scheduler 工作的權限
  • 具備 Recordia 平台特殊權限,且已啟用 API 存取權 (請與 Comunycarse 支援團隊聯絡,取得 API 憑證)

建立 Google Cloud Storage bucket

  1. 前往 Google Cloud 控制台。
  2. 選取專案或建立新專案。
  3. 在導覽選單中,依序前往「Cloud Storage」>「Bucket」。
  4. 按一下「建立值區」。
  5. 提供下列設定詳細資料:

    設定 值
    為 bucket 命名 輸入全域不重複的名稱 (例如 recordia-logs)
    位置類型 請根據需求選擇 (單一區域、雙區域、多區域)
    位置 選取位置 (例如 us-central1)
    儲存空間級別 標準 (建議用於經常存取的記錄)
    存取控管 統一 (建議)
    保護工具 選用:啟用物件版本管理或資料保留政策
  6. 點選「建立」。

收集 Recordia API 憑證

取得 API 憑證

  1. 請與 Recordia 客戶經理或 Comunycarse 支援團隊聯絡,要求 API 存取權。
  2. 取得下列憑證:

    • API 基準網址:Recordia 執行個體的基準網址 (例如 https://api.recordia.net)
    • API 權杖:用於驗證的不記名權杖

驗證權限

如要確認 API 憑證具備必要權限,請按照下列步驟操作:

  1. 登入 Recordia 管理入口網站。
  2. 前往「Settings」或「API」部分。
  3. 確認帳戶已啟用 API 存取權。
  4. 如果無法存取 API 設定,請與 Comunycarse 支援團隊聯絡。

測試 API 存取權

  • 請先測試憑證,再繼續整合:

    # Replace with your actual credentials
    API_TOKEN="<your-api-token>"
    API_BASE="https://api.recordia.net"
    
    # Test API access - list recordings
    curl -v -H "Authorization: Bearer ${API_TOKEN}" \
      "${API_BASE}/v1/recordings?from=2024-01-01T00:00:00Z&to=2024-01-02T00:00:00Z"
    

建立 Cloud Run 函式的服務帳戶

Cloud Run 函式需要服務帳戶,且該帳戶須具備寫入 GCS bucket 的權限,並可由 Pub/Sub 叫用。

建立服務帳戶

  1. 在 GCP 控制台中,依序前往「IAM & Admin」(IAM 與管理) >「Service Accounts」(服務帳戶)。
  2. 按一下「Create Service Account」(建立服務帳戶)。
  3. 提供下列設定詳細資料:
    • 服務帳戶名稱:輸入 recordia-collector-sa
    • 服務帳戶說明:輸入 Service account for Cloud Run function to collect Recordia logs
  4. 按一下「建立並繼續」。
  5. 在「將專案存取權授予這個服務帳戶」部分,新增下列角色:
    1. 按一下「請選擇角色」。
    2. 搜尋並選取「Storage 物件管理員」。
    3. 點選「+ 新增其他角色」。
    4. 搜尋並選取「Cloud Run Invoker」。
    5. 點選「+ 新增其他角色」。
    6. 搜尋並選取「Cloud Functions 叫用者」。
  6. 按一下「繼續」。
  7. 按一下「完成」。

這些角色適用於:

  • Storage 物件管理員:將記錄檔寫入 GCS bucket 並管理狀態檔案
  • Cloud Run 叫用者:允許 Pub/Sub 叫用函式
  • Cloud Functions 叫用者:允許叫用函式

授予 GCS bucket 的 IAM 權限

授予服務帳戶 GCS bucket 的寫入權限:

  1. 依序前往「Cloud Storage」>「Bucket」。
  2. 點選 bucket 名稱 (例如 recordia-logs)。
  3. 前往「權限」分頁。
  4. 按一下「授予存取權」。
  5. 提供下列設定詳細資料:
    • 新增主體:輸入服務帳戶電子郵件地址 (例如 recordia-collector-sa@PROJECT_ID.iam.gserviceaccount.com)
    • 指派角色:選取「Storage 物件管理員」
  6. 按一下「儲存」。

建立 Pub/Sub 主題

建立 Pub/Sub 主題,Cloud Scheduler 會發布至該主題,Cloud Run 函式則會訂閱該主題。

  1. 在 GCP 控制台中,依序前往「Pub/Sub」>「主題」。
  2. 按一下「建立主題」。
  3. 提供下列設定詳細資料:
    • 主題 ID:輸入 recordia-logs-trigger
    • 其他設定保留預設值
  4. 點選「建立」。

建立 Cloud Run 函式來收集記錄

Cloud Run 函式會由 Cloud Scheduler 的 Pub/Sub 訊息觸發,從 Recordia API 擷取錄音中繼資料和稽核事件,並寫入 GCS。

  1. 在 GCP 控制台中,前往「Cloud Run」。
  2. 按一下「Create service」(建立服務)。
  3. 選取「函式」(使用直接修改建立函式)。
  4. 在「Configure」(設定) 部分,提供下列設定詳細資料:

    設定 值
    服務名稱 recordia-collector
    區域 選取與 GCS bucket 相符的區域 (例如 us-central1)
    執行階段 選取「Python 3.12」或更新版本
  5. 在「Trigger (optional)」(觸發條件 (選用)) 部分:

    1. 按一下「+ 新增觸發條件」。
    2. 選取「Cloud Pub/Sub」。
    3. 在「Select a Cloud Pub/Sub topic」(選取 Cloud Pub/Sub 主題) 中,選擇 Pub/Sub 主題 (recordia-logs-trigger)。
    4. 按一下「儲存」。
  6. 在「Authentication」(驗證) 部分:

    1. 選取「需要驗證」。
    2. Identity and Access Management (IAM)。
  7. 向下捲動並展開「容器、網路、安全性」。

  8. 前往「安全性」分頁:

    • 「Service account」(服務帳戶):選取服務帳戶 (recordia-collector-sa)
  9. 前往「容器」分頁:

    1. 按一下「Variables & Secrets」(變數與密鑰)。
    2. 針對每個環境變數,按一下「+ 新增變數」:
    變數名稱 範例值 說明
    GCS_BUCKET recordia-logs GCS bucket 名稱
    GCS_PREFIX recordia 記錄檔的前置字串
    STATE_KEY recordia/state.json 狀態檔案路徑
    API_BASE https://api.recordia.net Recordia API 基準網址
    API_TOKEN your-bearer-token Recordia API 不記名權杖
    MAX_RECORDS 1000 每次執行的記錄數上限
    PAGE_SIZE 100 每頁記錄數
    LOOKBACK_HOURS 24 初始回溯期
  10. 在「Variables & Secrets」(變數與密鑰) 部分,向下捲動至「Requests」(要求):

    • 要求逾時:輸入 600 秒 (10 分鐘)
  11. 前往「設定」分頁:

    • 在「Resources」(資源) 部分:
      • 「記憶體」:選取「512 MiB」或以上
      • CPU:選取「1」
  12. 在「Revision scaling」(修訂版本資源調度) 部分:

    • 「執行個體數量下限」:輸入 0
    • 「Maximum number of instances」(執行個體數量上限):輸入 100 (或根據預期負載調整)
  13. 點選「建立」。

  14. 等待服務建立完成 (1 至 2 分鐘)。

  15. 服務建立後,內嵌程式碼編輯器會自動開啟。

新增函式程式碼

  1. 在「進入點」欄位中輸入 main。
  2. 在內嵌程式碼編輯器中,建立兩個檔案:

    • 第一個檔案 - main.py:

      import functions_framework
      from google.cloud import storage
      import json
      import os
      import urllib3
      from datetime import datetime, timezone, timedelta
      import time
      
      # Initialize HTTP client with timeouts
      http = urllib3.PoolManager(
        timeout=urllib3.Timeout(connect=5.0, read=30.0),
        retries=False,
      )
      
      # Initialize Storage client
      storage_client = storage.Client()
      
      # Environment variables
      GCS_BUCKET = os.environ.get('GCS_BUCKET')
      GCS_PREFIX = os.environ.get('GCS_PREFIX', 'recordia')
      STATE_KEY = os.environ.get('STATE_KEY', 'recordia/state.json')
      API_BASE = os.environ.get('API_BASE')
      API_TOKEN = os.environ.get('API_TOKEN')
      MAX_RECORDS = int(os.environ.get('MAX_RECORDS', '1000'))
      PAGE_SIZE = int(os.environ.get('PAGE_SIZE', '100'))
      LOOKBACK_HOURS = int(os.environ.get('LOOKBACK_HOURS', '24'))
      
      def parse_datetime(value: str) -> datetime:
        """Parse ISO datetime string to datetime object."""
        if value.endswith("Z"):
          value = value[:-1] + "+00:00"
        return datetime.fromisoformat(value)
      
      @functions_framework.cloud_event
      def main(cloud_event):
        """
        Cloud Run function triggered by Pub/Sub to fetch Recordia
        recording metadata and audit events and write to GCS.
      
        Args:
          cloud_event: CloudEvent object containing Pub/Sub message
        """
      
        if not all([GCS_BUCKET, API_BASE, API_TOKEN]):
          print('Error: Missing required environment variables')
          return
      
        try:
          # Get GCS bucket
          bucket = storage_client.bucket(GCS_BUCKET)
      
          # Load state
          state = load_state(bucket, STATE_KEY)
      
          # Determine time window
          now = datetime.now(timezone.utc)
          last_time = None
      
          if isinstance(state, dict) and state.get("last_event_time"):
            try:
              last_time = parse_datetime(state["last_event_time"])
              last_time = last_time - timedelta(minutes=2)
            except Exception as e:
              print(f"Warning: Could not parse last_event_time: {e}")
      
          if last_time is None:
            last_time = now - timedelta(hours=LOOKBACK_HOURS)
      
          print(f"Fetching logs from {last_time.isoformat()} to {now.isoformat()}")
      
          # Fetch recordings
          records, newest_event_time = fetch_recordings(
            api_base=API_BASE,
            token=API_TOKEN,
            start_time=last_time,
            end_time=now,
            page_size=PAGE_SIZE,
            max_records=MAX_RECORDS,
          )
      
          if not records:
            print("No new log records found.")
            save_state(bucket, STATE_KEY, now.isoformat())
            return
      
          # Write to GCS as NDJSON
          timestamp = now.strftime('%Y%m%d_%H%M%S')
          object_key = f"{GCS_PREFIX}/logs_{timestamp}.ndjson"
          blob = bucket.blob(object_key)
      
          ndjson = '\n'.join([json.dumps(record, ensure_ascii=False) for record in records]) + '\n'
          blob.upload_from_string(ndjson, content_type='application/x-ndjson')
      
          print(f"Wrote {len(records)} records to gs://{GCS_BUCKET}/{object_key}")
      
          # Update state with newest event time
          if newest_event_time:
            save_state(bucket, STATE_KEY, newest_event_time)
          else:
            save_state(bucket, STATE_KEY, now.isoformat())
      
          print(f"Successfully processed {len(records)} records")
      
        except Exception as e:
          print(f'Error processing logs: {str(e)}')
          raise
      
      def load_state(bucket, key):
        """Load state from GCS."""
        try:
          blob = bucket.blob(key)
          if blob.exists():
            state_data = blob.download_as_text()
            return json.loads(state_data)
        except Exception as e:
          print(f"Warning: Could not load state: {e}")
      
        return {}
      
      def save_state(bucket, key, last_event_time_iso: str):
        """Save the last event timestamp to GCS state file."""
        try:
          state = {'last_event_time': last_event_time_iso}
          blob = bucket.blob(key)
          blob.upload_from_string(
            json.dumps(state, indent=2),
            content_type='application/json'
          )
          print(f"Saved state: last_event_time={last_event_time_iso}")
        except Exception as e:
          print(f"Warning: Could not save state: {e}")
      
      def fetch_recordings(api_base: str, token: str, start_time: datetime, end_time: datetime, page_size: int, max_records: int):
        """
        Fetch recording metadata from Recordia API with pagination.
      
        Args:
          api_base: API base URL
          token: Bearer token for authentication
          start_time: Start time for log query
          end_time: End time for log query
          page_size: Number of records per page
          max_records: Maximum total records to fetch
      
        Returns:
          Tuple of (records list, newest_event_time ISO string)
        """
        base_url = api_base.rstrip('/')
        endpoint = f"{base_url}/v1/recordings"
      
        headers = {
          'Authorization': f'Bearer {token}',
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'User-Agent': 'GoogleSecOps-RecordiaCollector/1.0',
        }
      
        records = []
        newest_time = None
        page_num = 0
        backoff = 1.0
        offset = 0
      
        from_time = start_time.strftime('%Y-%m-%dT%H:%M:%SZ')
        to_time = end_time.strftime('%Y-%m-%dT%H:%M:%SZ')
      
        while True:
          page_num += 1
      
          if len(records) >= max_records:
            print(f"Reached max_records limit ({max_records})")
            break
      
          current_limit = min(page_size, max_records - len(records))
          url = f"{endpoint}?from={from_time}&to={to_time}&offset={offset}&limit={current_limit}"
      
          try:
            response = http.request('GET', url, headers=headers)
      
            # Handle rate limiting with exponential backoff
            if response.status == 429:
              retry_after = int(response.headers.get('Retry-After', str(int(backoff))))
              print(f"Rate limited (429). Retrying after {retry_after}s...")
              time.sleep(retry_after)
              backoff = min(backoff * 2, 30.0)
              continue
      
            backoff = 1.0
      
            if response.status != 200:
              print(f"HTTP Error: {response.status}")
              response_text = response.data.decode('utf-8')
              print(f"Response body: {response_text}")
              return [], None
      
            data = json.loads(response.data.decode('utf-8'))
      
            if isinstance(data, list):
              page_results = data
            else:
              page_results = data.get('recordings', data.get('results', []))
      
            if not page_results:
              print(f"No more results (empty page)")
              break
      
            print(f"Page {page_num}: Retrieved {len(page_results)} recordings")
            records.extend(page_results)
      
            # Track newest event time
            for event in page_results:
              try:
                event_time = event.get('startTime') or event.get('timestamp') or event.get('date')
                if event_time:
                  if newest_time is None or parse_datetime(event_time) > parse_datetime(newest_time):
                    newest_time = event_time
              except Exception as e:
                print(f"Warning: Could not parse event time: {e}")
      
            # Check for more results
            if len(page_results) < current_limit:
              print(f"Reached last page (size={len(page_results)} < limit={current_limit})")
              break
      
            offset += len(page_results)
      
          except Exception as e:
            print(f"Error fetching recordings: {e}")
            return [], None
      
        print(f"Retrieved {len(records)} total recordings from {page_num} pages")
        return records, newest_time
      
    • 第二個檔案 - requirements.txt:

      functions-framework==3.*
      google-cloud-storage==2.*
      urllib3>=2.0.0
      
  3. 按一下「部署」,即可儲存並部署函式。

  4. 等待部署作業完成 (2 至 3 分鐘)。

建立 Cloud Scheduler 工作

Cloud Scheduler 會定期將訊息發布至 Pub/Sub 主題,觸發 Cloud Run 函式。

  1. 在 GCP 控制台中,前往「Cloud Scheduler」。
  2. 點選「建立工作」。
  3. 提供下列設定詳細資料:

    設定 值
    名稱 recordia-collector-hourly
    區域 選取與 Cloud Run 函式相同的區域
    頻率 0 * * * * (每小時整點)
    時區 選取時區 (建議選取世界標準時間)
    目標類型 Pub/Sub
    主題 選取 Pub/Sub 主題 (recordia-logs-trigger)
    郵件內文 {} (空白 JSON 物件)
  4. 點選「建立」。

排程頻率選項

根據記錄量和延遲時間需求選擇頻率:

頻率 Cron 運算式 用途
每 5 分鐘 */5 * * * * 高流量、低延遲
每 15 分鐘 */15 * * * * 中等音量
每小時 0 * * * * 標準 (建議)
每 6 小時 0 */6 * * * 低量、批次處理
每天 0 0 * * * 歷來資料集合

測試整合

  1. 在 Cloud Scheduler 控制台中找到您的工作。
  2. 按一下「強制執行」,手動觸發工作。
  3. 稍等幾秒鐘。
  4. 依序前往「Cloud Run」>「服務」。
  5. 按一下函式名稱 (recordia-collector)。
  6. 點選「記錄」分頁標籤。
  7. 確認函式是否執行成功。尋找:

    Fetching logs from YYYY-MM-DDTHH:MM:SS+00:00 to YYYY-MM-DDTHH:MM:SS+00:00
    Page 1: Retrieved X recordings
    Wrote X records to gs://recordia-logs/recordia/logs_YYYYMMDD_HHMMSS.ndjson
    Successfully processed X records
    
  8. 依序前往「Cloud Storage」>「Bucket」。

  9. 點選 bucket 名稱 (recordia-logs)。

  10. 前往前置字元資料夾 (recordia/)。

  11. 確認系統已建立新的 .ndjson 檔案,並加上目前的時間戳記。

如果記錄中顯示錯誤:

  • HTTP 401:檢查環境變數中的 API 權杖
  • HTTP 403:確認 API 權杖有權存取錄製端點
  • HTTP 429:頻率限制 - 函式會自動重試,並採用輪詢機制
  • 缺少環境變數:確認已設定所有必要變數

擷取 Google SecOps 服務帳戶

Google SecOps 會使用專屬服務帳戶,從 GCS bucket 讀取資料。您必須授予這個服務帳戶值區存取權。

取得服務帳戶電子郵件地址

  1. 依序前往「設定」>「資料管理」>「動態饋給」。如果使用的是 SIEM 專用平台,請依序前往「設定」>「動態饋給」。
  2. 按一下「新增動態饋給」。
  3. 按一下「設定單一動態饋給」。
  4. 在「Feed name」(動態饋給名稱) 欄位中,輸入動態饋給名稱 (例如 Recordia Logs)。
  5. 選取「Google Cloud Storage V2」做為「來源類型」。
  6. 選取「Recordia」做為「記錄類型」。
  7. 按一下「Get Service Account」(取得服務帳戶)。
  8. 系統會顯示專屬服務帳戶電子郵件地址,例如:

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  9. 複製這個電子郵件地址,下一個步驟將會用到。

  10. 點選「下一步」。

  11. 指定下列輸入參數的值:

    • Storage bucket URL:輸入 GCS bucket URI,並加上前置字元路徑:

      gs://recordia-logs/recordia/
      
      • 取代:
        • recordia-logs:GCS bucket 名稱。
        • recordia:儲存記錄檔的選用前置字元/資料夾路徑 (留空則為根目錄)。
    • 來源刪除選項:根據偏好選取刪除選項:

      • Never:轉移後一律不刪除任何檔案 (建議用於測試)。
      • 刪除已轉移的檔案:在成功轉移後刪除檔案。
      • 刪除已轉移的檔案和空白目錄:成功轉移後,刪除檔案和空白目錄。

    • 檔案存在時間上限:納入過去幾天內修改過的檔案 (預設為 180 天)

    • 資產命名空間:資產命名空間

    • 擷取標籤:要套用至這個動態饋給事件的標籤

  12. 點選「下一步」。

  13. 在「完成」畫面中檢查新的新聞動態消息設定,然後按一下「提交」。

將 IAM 權限授予 Google SecOps 服務帳戶

Google SecOps 服務帳戶需要 GCS bucket 的 Storage 物件檢視者角色。

  1. 依序前往「Cloud Storage」>「Bucket」。
  2. 點選 bucket 名稱 (例如 recordia-logs)。
  3. 前往「權限」分頁。
  4. 按一下「授予存取權」。
  5. 提供下列設定詳細資料:
    • 新增主體:貼上 Google SecOps 服務帳戶電子郵件地址
    • 指派角色:選取「Storage 物件檢視者」
  6. 按一下「儲存」。

UDM 對應表

記錄欄位 UDM 對應 邏輯
record_id, batch_id, ProviderId, ProviderGroupId, TrackingId, RecordingType, Format, Owner, NotEncrypted, Hash, CustomData, CustomDataFormat additional.fields 與從每個欄位建構的標籤物件合併 (如果不是空白),其中 label.key 設為特定字串,label.value.string_value 設為欄位值
client_ip,client_ip1 intermediary.ip 與 client_ip 合併,再與 client_ip1 合併
corp_user intermediary.user.userid 直接複製值
說明 metadata.description 直接複製值
auth_user,src_ip metadata.event_type 如果 auth_user 不為空白,則設為「USER_UNCATEGORIZED」;如果 src_ip 不為空白,則設為「STATUS_UNCATEGORIZED」;否則設為「GENERIC_EVENT」
metadata.product_event_type 如果 event_info 與「RECORDING BATCH」相符,則設為「RECORDING BATCH」
CallId metadata.product_log_id 直接複製值
user_agent network.http.parsed_user_agent 已複製值並轉換為 parseduseragent 類型
user_agent network.http.user_agent 直接複製值
session_id network.session_id 直接複製值
src_ip principal.ip 直接複製值
網址 principal.url 直接複製值
CallingParty principal.user.phone_numbers 直接複製值
auth_user principal.user.userid 直接複製值
嚴重性 security_result.action_details 如果嚴重性為 ["INFO", "DEBUG"],則直接複製值
嚴重性 security_result.severity 如果嚴重性為 ["INFO", "DEBUG"],則設為「LOW」
CalledParty target.user.phone_numbers 直接複製值
metadata.vendor_name 設為「Comunycarse」
metadata.product_name 設為「Recordia」

變更記錄

查看這個剖析器的變更記錄

還有其他問題嗎?向社群成員和 Google SecOps 專家尋求解答。