Entrust Identity Verification (이전 명칭: Onfido) 로그 수집

다음에서 지원:

이 문서에서는 Google Cloud Storage V2를 사용하여 Entrust Identity Verification (이전 명칭: Onfido) 로그를 Google Security Operations에 수집하는 방법을 설명합니다. 파서는 원시 Onfido 인증 확인 및 보고서 로그를 Google SecOps UDM 스키마로 변환합니다.

Entrust Identity Verification은 문서 확인, 생체 인식 분석, 사기 감지를 자동화하는 클라우드 기반 신원 확인 플랫폼입니다. 지원자, 인증 확인, 보고서를 관리하는 REST API를 제공하여 조직이 애플리케이션에 신원 확인 워크플로를 통합할 수 있습니다.

시작하기 전에

다음 기본 요건이 충족되었는지 확인합니다.

  • Google SecOps 인스턴스
  • Cloud Storage API가 사용 설정된 GCP 프로젝트
  • GCS 버킷을 만들고 관리할 수 있는 권한
  • GCS 버킷의 IAM 정책을 관리할 수 있는 권한
  • Cloud Run 서비스, Pub/Sub 주제, Cloud Scheduler 작업을 만들 수 있는 권한
  • API 액세스 권한이 있는 Entrust Identity Verification (이전 명칭: Onfido) 계정
  • 검사 및 보고서를 읽을 수 있는 충분한 권한이 있는 Onfido API 토큰

Onfido API 사용자 인증 정보 수집

API 토큰 가져오기

  1. Onfido 대시보드에 로그인합니다.
  2. 개발자 > API 토큰으로 이동합니다.
  3. 기존 라이브 API 토큰을 복사하거나 API 토큰 생성을 클릭하여 새 토큰을 만듭니다.
  4. 토큰 이름을 입력합니다 (예: Google Security Operations Integration).
  5. 토큰 유형으로 라이브를 선택합니다.
  6. API 토큰을 복사하여 안전하게 저장합니다.

권한 확인

API 토큰에 필요한 권한이 있는지 확인하려면 다음 단계를 따르세요.

  1. Onfido 대시보드에 로그인합니다.
  2. 개발자 > API 토큰으로 이동합니다.
  3. 토큰이 게시됨 상태로 나열되어 있고 취소되지 않았는지 확인합니다.
  4. API 액세스를 테스트하여 토큰에 검사 및 보고서에 대한 읽기 액세스 권한이 있는지 확인합니다.

API 액세스 테스트

  • 통합을 진행하기 전에 사용자 인증 정보를 테스트하세요.

    # Replace with your actual API token
    ONFIDO_API_TOKEN="your-api-token"
    
    # Test API access - list checks
    curl -v -H "Authorization: Token token=${ONFIDO_API_TOKEN}" \
      "[https://api.onfido.com/v3.6/checks](https://api.onfido.com/v3.6/checks)"
    

성공적인 응답은 checks 배열이 포함된 JSON 객체와 함께 HTTP 200을 반환합니다.

Google Cloud Storage 버킷 만들기

  1. Google Cloud 콘솔로 이동합니다.
  2. 프로젝트를 선택하거나 새 프로젝트를 만듭니다.
  3. 탐색 메뉴에서 Cloud Storage> 버킷으로 이동합니다.
  4. 버킷 만들기를 클릭합니다.

  5. 다음 구성 세부정보를 제공합니다.

    설정 값
    버킷 이름 지정 전역적으로 고유한 이름 (예: onfido-verification-logs)을 입력합니다.
    위치 유형 필요에 따라 선택 (리전, 이중 리전, 멀티 리전)
    위치 위치를 선택합니다 (예: us-central1).
    스토리지 클래스 Standard (자주 액세스하는 로그에 권장)
    액세스 제어 균일 (권장)
    보호 조치 선택사항: 객체 버전 관리 또는 보관 정책 사용 설정
  6. 만들기를 클릭합니다.

Cloud Run 함수의 서비스 계정 만들기

Cloud Run 함수에는 GCS 버킷에 쓸 수 있고 Pub/Sub에 의해 호출될 수 있는 권한이 있는 서비스 계정이 필요합니다.

서비스 계정 만들기

  1. GCP 콘솔에서 IAM 및 관리자 > 서비스 계정으로 이동합니다.
  2. 서비스 계정 만들기를 클릭합니다.
  3. 다음 구성 세부정보를 제공합니다.
    • 서비스 계정 이름: onfido-logs-collector-sa을 입력합니다.
    • 서비스 계정 설명: Service account for Cloud Run function to collect Onfido verification logs을 입력합니다.
  4. 만들고 계속하기를 클릭합니다.
  5. 이 서비스 계정에 프로젝트에 대한 액세스 권한 부여 섹션에서 다음 역할을 추가합니다.
    1. 역할 선택을 클릭합니다.
    2. 스토리지 객체 관리자를 검색하여 선택합니다.
    3. + 다른 역할 추가를 클릭합니다.
    4. Cloud Run 호출자를 검색하여 선택합니다.
    5. + 다른 역할 추가를 클릭합니다.
    6. Cloud Functions 호출자를 검색하여 선택합니다.
  6. 계속을 클릭합니다.
  7. 완료를 클릭합니다.

이러한 역할은 다음 작업에 필요합니다.

  • 스토리지 객체 관리자: GCS 버킷에 로그를 쓰고 상태 파일을 관리합니다.
  • Cloud Run 호출자: Pub/Sub가 함수를 호출하도록 허용
  • Cloud Functions 호출자: 함수 호출 허용

GCS 버킷에 IAM 권한 부여

GCS 버킷에 대한 쓰기 권한을 서비스 계정에 부여합니다.

  1. Cloud Storage> 버킷으로 이동합니다.
  2. 버킷 이름을 클릭합니다.
  3. 권한 탭으로 이동합니다.
  4. 액세스 권한 부여를 클릭합니다.
  5. 다음 구성 세부정보를 제공합니다.
    • 주 구성원 추가: 서비스 계정 이메일 (예: onfido-logs-collector-sa@PROJECT_ID.iam.gserviceaccount.com)을 입력합니다.
    • 역할 할당: 스토리지 객체 관리자를 선택합니다.
  6. 저장을 클릭합니다.

Pub/Sub 주제 만들기

Cloud Scheduler가 게시하고 Cloud Run 함수가 구독할 Pub/Sub 주제를 만듭니다.

  1. GCP Console에서 Pub/Sub > 주제로 이동합니다.
  2. 주제 만들기를 클릭합니다.
  3. 다음 구성 세부정보를 제공합니다.
    • 주제 ID: onfido-logs-trigger를 입력합니다.
    • 다른 설정은 기본값으로 둡니다.
  4. 만들기를 클릭합니다.

로그를 수집하는 Cloud Run 함수 만들기

Cloud Run 함수는 Cloud Scheduler의 Pub/Sub 메시지에 의해 트리거되어 Onfido API에서 확인 검사와 보고서를 가져와 GCS에 작성합니다.

  1. GCP 콘솔에서 Cloud Run으로 이동합니다.
  2. 서비스 만들기를 클릭합니다.
  3. 함수를 선택합니다 (인라인 편집기를 사용하여 함수 만들기).
  4. 구성 섹션에서 다음 구성 세부정보를 입력합니다.

    설정 값
    서비스 이름 onfido-logs-collector
    리전 GCS 버킷과 일치하는 리전을 선택합니다 (예: us-central1).
    런타임 Python 3.12 이상 선택
  5. 트리거 (선택사항) 섹션에서 다음을 수행합니다.

    1. + 트리거 추가를 클릭합니다.
    2. Cloud Pub/Sub를 선택합니다.
    3. Cloud Pub/Sub 주제 선택에서 onfido-logs-trigger을 선택합니다.
    4. 저장을 클릭합니다.
  6. 인증 섹션에서 다음을 구성합니다.

    1. 인증 필요를 선택합니다.
    2. ID 및 액세스 관리 (IAM)를 확인합니다.
  7. 아래로 스크롤하고 컨테이너, 네트워킹, 보안을 펼칩니다.

  8. 보안 탭으로 이동합니다.

    • 서비스 계정: onfido-logs-collector-sa를 선택합니다.
  9. 컨테이너 탭으로 이동합니다.

    1. 변수 및 보안 비밀을 클릭합니다.
    2. 각 환경 변수에 대해 + 변수 추가를 클릭합니다.
    변수 이름 예시 값 설명
    GCS_BUCKET onfido-verification-logs GCS 버킷 이름
    GCS_PREFIX onfido-logs 로그 파일의 접두사
    STATE_KEY onfido-logs/state.json 상태 파일 경로
    ONFIDO_API_TOKEN your-api-token-here Onfido API 토큰
    MAX_RECORDS 1000 실행당 최대 레코드 수
    PAGE_SIZE 100 페이지당 레코드 수
    LOOKBACK_HOURS 24 초기 전환 확인 기간
  10. 변수 및 보안 비밀 섹션에서 요청까지 아래로 스크롤합니다.

    • 요청 제한 시간: 600초 (10분)를 입력합니다.
  11. 설정 탭으로 이동합니다.

    • 리소스 섹션에서 다음을 수행합니다.
      • 메모리: 512MiB 이상을 선택합니다.
      • CPU: 1을 선택합니다.
  12. 버전 확장 섹션에서 다음을 수행합니다.

    • 최소 인스턴스 수: 0를 입력합니다.
    • 최대 인스턴스 수: 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', 'onfido-logs')
    STATE_KEY = os.environ.get('STATE_KEY', 'onfido-logs/state.json')
    ONFIDO_API_TOKEN = os.environ.get('ONFIDO_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'))
    
    API_BASE = '[https://api.onfido.com/v3.6](https://api.onfido.com/v3.6)'
    
    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 Onfido verification
        checks and reports and write to GCS.
    
        Args:
            cloud_event: CloudEvent object containing Pub/Sub message
        """
    
        if not all([GCS_BUCKET, ONFIDO_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"])
                    # Overlap by 2 minutes to catch any delayed events
                    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 checks
            checks, newest_check_time = fetch_checks(
                api_token=ONFIDO_API_TOKEN,
                start_time=last_time,
                end_time=now,
                page_size=PAGE_SIZE,
                max_records=MAX_RECORDS,
            )
    
            # Fetch reports for each check
            all_records = []
            for check in checks:
                check_record = check.copy()
                check_id = check.get('id')
                if check_id:
                    reports = fetch_reports(api_token=ONFIDO_API_TOKEN, check_id=check_id)
                    check_record['reports'] = reports
                all_records.append(check_record)
    
            if not all_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 all_records]) + '\n'
            blob.upload_from_string(ndjson, content_type='application/x-ndjson')
    
            print(f"Wrote {len(all_records)} records to gs://{GCS_BUCKET}/{object_key}")
    
            # Update state with newest event time
            if newest_check_time:
                save_state(bucket, STATE_KEY, newest_check_time)
            else:
                save_state(bucket, STATE_KEY, now.isoformat())
    
            print(f"Successfully processed {len(all_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_checks(api_token: str, start_time: datetime, end_time: datetime, page_size: int, max_records: int):
        """
        Fetch verification checks from the Onfido API with pagination and rate limiting.
    
        Args:
            api_token: Onfido API token
            start_time: Start time for check query
            end_time: End time for check query
            page_size: Number of records per page
            max_records: Maximum total records to fetch
    
        Returns:
            Tuple of (checks list, newest_event_time ISO string)
        """
        headers = {
            'Authorization': f'Token token={api_token}',
            'Accept': 'application/json',
            'User-Agent': 'GoogleSecOps-OnfidoCollector/1.0'
        }
    
        records = []
        newest_time = None
        page_num = 0
        backoff = 1.0
        current_page = 1
    
        while True:
            page_num += 1
    
            if len(records) >= max_records:
                print(f"Reached max_records limit ({max_records})")
                break
    
            url = f"{API_BASE}/checks?page={current_page}&per_page={page_size}"
    
            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'))
    
                page_results = data.get('checks', [])
    
                if not page_results:
                    print(f"No more results (empty page)")
                    break
    
                # Filter checks within the time window
                filtered = []
                for check in page_results:
                    created_at = check.get('created_at')
                    if created_at:
                        try:
                            check_time = parse_datetime(created_at)
                            if start_time <= check_time <= end_time:
                                filtered.append(check)
                            if newest_time is None or check_time > parse_datetime(newest_time):
                                newest_time = created_at
                        except Exception as e:
                            print(f"Warning: Could not parse check time: {e}")
                            filtered.append(check)
    
                print(f"Page {page_num}: Retrieved {len(page_results)} checks, {len(filtered)} in time window")
                records.extend(filtered)
    
                # Check for more results
                if len(page_results) < page_size:
                    print(f"Reached last page (size={len(page_results)} < limit={page_size})")
                    break
    
                current_page += 1
    
            except Exception as e:
                print(f"Error fetching checks: {e}")
                return [], None
    
        print(f"Retrieved {len(records)} total checks from {page_num} pages")
        return records[:max_records], newest_time
    
    def fetch_reports(api_token: str, check_id: str):
        """
        Fetch reports for a specific check from the Onfido API.
    
        Args:
            api_token: Onfido API token
            check_id: Check ID to fetch reports for
    
        Returns:
            List of report objects
        """
        headers = {
            'Authorization': f'Token token={api_token}',
            'Accept': 'application/json',
            'User-Agent': 'GoogleSecOps-OnfidoCollector/1.0'
        }
    
        url = f"{API_BASE}/reports?check_id={check_id}"
    
        try:
            response = http.request('GET', url, headers=headers)
    
            if response.status == 429:
                time.sleep(2)
                response = http.request('GET', url, headers=headers)
    
            if response.status != 200:
                print(f"Error fetching reports for check {check_id}: HTTP {response.status}")
                return []
    
            data = json.loads(response.data.decode('utf-8'))
            reports = data.get('reports', [])
            return reports
    
        except Exception as e:
            print(f"Error fetching reports for check {check_id}: {e}")
            return []
    
    • 두 번째 파일: 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 Console에서 Cloud Scheduler로 이동합니다.
  2. 작업 만들기를 클릭합니다.

  3. 다음 구성 세부정보를 제공합니다.

    설정 값
    이름 onfido-logs-collector-hourly
    리전 Cloud Run 함수와 동일한 리전 선택
    주파수 0 * * * * (매시간 정각)
    시간대 시간대 선택 (UTC 권장)
    타겟 유형 Pub/Sub
    주제 onfido-logs-trigger 선택
    메일 본문 {} (빈 JSON 객체)
  4. 만들기를 클릭합니다.

일정 빈도 옵션

로그 볼륨 및 지연 시간 요구사항에 따라 빈도를 선택합니다.

빈도 크론 표현식 사용 사례
5분마다 */5 * * * * 대용량, 저지연
15분마다 */15 * * * * 검색량 보통
1시간마다 0 * * * * 표준 (권장)
6시간마다 0 */6 * * * 양이 적은 일괄 처리
매일 0 0 * * * 이전 데이터 수집

통합 테스트

  1. Cloud Scheduler 콘솔에서 작업을 찾습니다.
  2. 강제 실행을 클릭하여 작업을 수동으로 트리거합니다.
  3. 몇 초 동안 기다립니다.
  4. Cloud Run > 서비스로 이동합니다.
  5. onfido-logs-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 checks, X in time window
    Wrote X records to gs://bucket-name/onfido-logs/logs_YYYYMMDD_HHMMSS.ndjson
    Successfully processed X records
    
  8. Cloud Storage> 버킷으로 이동합니다.

  9. 버킷 이름을 클릭합니다.

  10. onfido-logs/ 폴더로 이동합니다.

  11. 현재 타임스탬프를 사용하여 새 .ndjson 파일이 생성되었는지 확인합니다.

로그에 오류가 표시되는 경우:

  • HTTP 401: 환경 변수에서 Onfido API 토큰 확인
  • HTTP 403: API 토큰에 라이브 액세스 권한이 있고 취소되지 않았는지 확인합니다.
  • HTTP 429: 비율 제한 - 함수가 백오프를 사용하여 자동으로 재시도됩니다.
  • 환경 변수 누락: 필수 변수가 모두 설정되었는지 확인

Onfido 로그를 수집하도록 Google SecOps에서 피드 구성

  1. SIEM 설정> 피드로 이동합니다.
  2. 새 피드 추가를 클릭합니다.
  3. 단일 피드 구성을 클릭합니다.
  4. 피드 이름 필드에 피드 이름을 입력합니다(예: Onfido Verification Logs).
  5. 소스 유형으로 Google Cloud Storage V2를 선택합니다.
  6. 로그 유형으로 Onfido를 선택합니다.
  7. 서비스 계정 가져오기를 클릭합니다. 고유한 서비스 계정 이메일이 표시됩니다(예:

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  8. 이 이메일 주소를 복사합니다. 다음 단계에서 사용합니다.

  9. 다음을 클릭합니다.

  10. 다음 입력 매개변수의 값을 지정합니다.

    • 스토리지 버킷 URL: 다음 접두사 경로를 사용하여 GCS 버킷 URI를 입력합니다.

      gs://onfido-verification-logs/onfido-logs/
      
      • 다음과 같이 바꿉니다.
        • onfido-verification-logs: GCS 버킷 이름입니다.
        • onfido-logs: 로그가 저장되는 선택적 접두사/폴더 경로입니다 (루트의 경우 비워 둠).
    • 소스 삭제 옵션: 환경설정에 따라 삭제 옵션을 선택합니다.

      • 삭제 안함: 전송 후 파일을 삭제하지 않습니다 (테스트에 권장).
      • 전송된 파일 삭제: 전송이 완료되면 파일을 삭제합니다.
      • 전송된 파일 및 빈 디렉터리 삭제: 전송이 완료되면 파일과 빈 디렉터리를 삭제합니다.
    • 최대 파일 기간: 지난 일수 동안 수정된 파일을 포함합니다. 기본값은 180일입니다.

    • 애셋 네임스페이스: 애셋 네임스페이스입니다.

    • 수집 라벨: 이 피드의 이벤트에 적용할 라벨입니다.

  11. 다음을 클릭합니다.

  12. 확정 화면에서 새 피드 구성을 검토한 다음 제출을 클릭합니다.

Google SecOps 서비스 계정에 IAM 권한 부여

Google SecOps 서비스 계정에는 GCS 버킷에 대한 스토리지 객체 뷰어 역할이 필요합니다.

  1. Cloud Storage> 버킷으로 이동합니다.
  2. 버킷 이름을 클릭합니다.
  3. 권한 탭으로 이동합니다.
  4. 액세스 권한 부여를 클릭합니다.

  5. 다음 구성 세부정보를 제공합니다.

    • 주 구성원 추가: Google SecOps 서비스 계정 이메일을 붙여넣습니다.
    • 역할 할당: 스토리지 객체 뷰어를 선택합니다.
  6. 저장을 클릭합니다.

UDM 매핑 테이블

로그 필드 UDM 매핑 논리
read_only_udm.metadata.vendor_name 'ONFIDO'로 설정합니다.
read_only_udm.metadata.product_name 'ONFIDO'로 설정합니다.
read_only_udm.metadata.log_type 'ONFIDO'로 설정합니다.

변경 로그

이 파서의 변경 로그 보기

도움이 더 필요하신가요? 커뮤니티 회원 및 Google SecOps 전문가에게 문의하여 답변을 받으세요.