Skip to content

🙌 OpenHands: AI-Driven Development

feat: add automation event forwarding for GitHub webhooks (#13793)

Rohit Malhotra393a6bb8f890
diff --git a/enterprise/integrations/resolver_org_router.py b/enterprise/integrations/resolver_org_router.py
index a06eeaae32..ce22128168 100644
--- a/enterprise/integrations/resolver_org_router.py
+++ b/enterprise/integrations/resolver_org_router.py
@@ -16,21 +16,23 @@ from openhands.core.logger import openhands_logger as logger
async def resolve_org_for_repo(
provider: str,
full_repo_name: str,
- keycloak_user_id: str,
+ keycloak_user_id: str | None = None,
) -> UUID | None:
"""Determine the OpenHands org_id for a resolver conversation.
- If the repo's git organization is claimed by an OpenHands org AND the user
- is a member of that org, returns the claiming org's ID. Otherwise returns
- None (caller should fall back to user.current_org_id / personal workspace).
+ If the repo's git organization is claimed by an OpenHands org, returns the
+ claiming org's ID. When keycloak_user_id is provided, also verifies the user
+ is a member of that org.
Args:
provider: Git provider name ("github", "gitlab", "bitbucket")
full_repo_name: Full repository name (e.g., "OpenHands/foo")
- keycloak_user_id: The user's Keycloak UUID string
+ keycloak_user_id: The user's Keycloak UUID string (optional). If provided,
+ membership is verified before returning the org_id.
Returns:
- The org_id if the repo's org is claimed and user is a member, else None
+ The org_id if the repo's org is claimed (and user is a member when
+ keycloak_user_id is provided), else None
"""
git_org = full_repo_name.split('/')[0].lower()
@@ -44,6 +46,14 @@ async def resolve_org_for_repo(
)
return None
+ # Skip membership check if no user_id provided
+ if keycloak_user_id is None:
+ logger.info(
+ f'[OrgResolver] Resolved org {claim.org_id} '
+ f'for {provider}/{git_org} (no user membership check)',
+ )
+ return claim.org_id
+
member = await OrgMemberStore.get_org_member(
claim.org_id, UUID(keycloak_user_id)
)
diff --git a/enterprise/server/auth/constants.py b/enterprise/server/auth/constants.py
index 2e2d6cb3f1..20240a6cdc 100644
--- a/enterprise/server/auth/constants.py
+++ b/enterprise/server/auth/constants.py
@@ -56,6 +56,23 @@ RECAPTCHA_SITE_KEY = os.getenv('RECAPTCHA_SITE_KEY', '').strip()
RECAPTCHA_HMAC_SECRET = os.getenv('RECAPTCHA_HMAC_SECRET', '').strip()
RECAPTCHA_BLOCK_THRESHOLD = float(os.getenv('RECAPTCHA_BLOCK_THRESHOLD', '0.3'))
+# Automation Service
+AUTOMATION_SERVICE_URL = os.getenv('AUTOMATION_SERVICE_URL', '').strip()
+if AUTOMATION_SERVICE_URL and not AUTOMATION_SERVICE_URL.startswith(
+ ('http://', 'https://')
+):
+ raise ValueError(
+ f'AUTOMATION_SERVICE_URL must start with http:// or https://, '
+ f'got: {AUTOMATION_SERVICE_URL}'
+ )
+AUTOMATION_EVENT_FORWARDING_ENABLED = os.getenv(
+ 'AUTOMATION_EVENT_FORWARDING_ENABLED', 'false'
+) in ('1', 'true')
+# Shared secret for signing payloads sent to automation service (separate from GitHub webhook secret)
+AUTOMATION_WEBHOOK_SECRET = os.getenv('AUTOMATION_WEBHOOK_SECRET', '').strip()
+# Default HTTP timeout for automation service requests (seconds)
+AUTOMATION_SERVICE_TIMEOUT = int(os.getenv('AUTOMATION_SERVICE_TIMEOUT', '30'))
+
# Account Defender labels that indicate suspicious activity
SUSPICIOUS_LABELS = {
'SUSPICIOUS_LOGIN_ACTIVITY',
diff --git a/enterprise/server/routes/integration/github.py b/enterprise/server/routes/integration/github.py
index 204b8297f7..be3cf25a11 100644
--- a/enterprise/server/routes/integration/github.py
+++ b/enterprise/server/routes/integration/github.py
@@ -3,15 +3,20 @@ import hashlib
import hmac
import os
-from fastapi import APIRouter, Header, HTTPException, Request
+from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Request
from fastapi.responses import JSONResponse
from integrations.github.data_collector import GitHubDataCollector
from integrations.github.github_manager import GithubManager
from integrations.models import Message, SourceType
-from server.auth.constants import GITHUB_APP_WEBHOOK_SECRET
+from server.auth.constants import (
+ AUTOMATION_EVENT_FORWARDING_ENABLED,
+ GITHUB_APP_WEBHOOK_SECRET,
+)
from server.auth.token_manager import TokenManager
+from server.services.automation_event_service import AutomationEventService
from openhands.core.logger import openhands_logger as logger
+from openhands.integrations.provider import ProviderType
# Environment variable to disable GitHub webhooks
GITHUB_WEBHOOKS_ENABLED = os.environ.get('GITHUB_WEBHOOKS_ENABLED', '1') in (
@@ -22,6 +27,7 @@ github_integration_router = APIRouter(prefix='/integration')
token_manager = TokenManager()
data_collector = GitHubDataCollector()
github_manager = GithubManager(token_manager, data_collector)
+automation_event_service = AutomationEventService(token_manager)
def verify_github_signature(payload: bytes, signature: str):
@@ -46,13 +52,13 @@ def verify_github_signature(payload: bytes, signature: str):
@github_integration_router.post('/github/events')
async def github_events(
request: Request,
+ background_tasks: BackgroundTasks,
x_hub_signature_256: str = Header(None),
+ x_github_event: str = Header(None),
):
# Check if GitHub webhooks are enabled
if not GITHUB_WEBHOOKS_ENABLED:
- logger.info(
- 'GitHub webhooks are disabled by GITHUB_WEBHOOKS_ENABLED environment variable'
- )
+ logger.info('GitHub webhooks disabled by GITHUB_WEBHOOKS_ENABLED env variable')
return JSONResponse(
status_code=200,
content={'message': 'GitHub webhooks are currently disabled.'},
@@ -72,6 +78,16 @@ async def github_events(
content={'error': 'Installation ID is missing in the payload.'},
)
+ # Forward to automation service (fire-and-forget background task)
+ if AUTOMATION_EVENT_FORWARDING_ENABLED:
+ background_tasks.add_task(
+ automation_event_service.forward_event,
+ provider=ProviderType.GITHUB,
+ payload=payload_data,
+ installation_id=installation_id,
+ )
+
+ # Existing resolver bot processing
message_payload = {'payload': payload_data, 'installation': installation_id}
message = Message(source=SourceType.GITHUB, message=message_payload)
await github_manager.receive_message(message)
diff --git a/enterprise/server/services/automation_event_service.py b/enterprise/server/services/automation_event_service.py
new file mode 100644
index 0000000000..36f1a32dab
--- /dev/null
+++ b/enterprise/server/services/automation_event_service.py
@@ -0,0 +1,517 @@
+"""
+Service for forwarding Git provider webhook events to the automation service.
+
+This service is optimized for high-traffic scenarios:
+1. Resolves Git org → OpenHands org_id (via cached OrgGitClaim lookup)
+2. For personal repos, resolves to personal org (via cached provider→Keycloak mapping)
+3. Forwards minimal payload to automation service (just org_id + payload)
+4. Access control checks are deferred to automation execution time
+
+Supports multiple Git providers (GitHub, GitLab, Bitbucket, etc.).
+
+The lazy access control approach means:
+- Most webhooks only do cached lookups + HTTP forward
+- Membership checks only happen when an automation actually matches
+
+Security notes:
+- Uses AUTOMATION_WEBHOOK_SECRET (not provider webhook secret) for signing
+- Negative results are cached to prevent DoS via repeated lookups
+"""
+
+import asyncio
+import hashlib
+import hmac
+import json
+from dataclasses import dataclass
+from typing import Any
+from uuid import UUID
+
+import aiohttp
+from integrations.resolver_org_router import resolve_org_for_repo
+from server.auth.constants import (
+ AUTOMATION_SERVICE_TIMEOUT,
+ AUTOMATION_SERVICE_URL,
+ AUTOMATION_WEBHOOK_SECRET,
+)
+from server.auth.token_manager import TokenManager
+
+from openhands.core.logger import openhands_logger as logger
+from openhands.integrations.provider import ProviderType
+from openhands.server.shared import sio
+
+# Cache TTL constants
+ORG_CLAIM_CACHE_TTL_SECONDS = 3600 # 1 hour for org claims (rarely change)
+USER_ID_CACHE_TTL_SECONDS = 86400 # 24 hours for user ID mappings (never change)
+
+# Cache key prefixes (provider is appended dynamically)
+ORG_CLAIM_CACHE_PREFIX = 'automation:org_claim'
+USER_ID_CACHE_PREFIX = 'automation:idp_to_kc_user'
+
+
+@dataclass
+class OrgContext:
+ """Context for the resolved organization."""
+
+ org_id: UUID
+ git_org: str
+
+
+class AutomationEventService:
+ """
+ Service for forwarding webhook events to the automation service.
+
+ Optimized for high traffic with:
+ - Redis caching for org claim lookups (1 hour TTL)
+ - Redis caching for provider→Keycloak user ID mappings (24 hour TTL)
+ - Lazy access control (membership checks deferred to execution time)
+
+ Supports multiple Git providers (GitHub, GitLab, Bitbucket, etc.).
+ """
+
+ def __init__(self, token_manager: TokenManager):
+ from server.auth.constants import AUTOMATION_EVENT_FORWARDING_ENABLED
+
+ self.token_manager = token_manager
+
+ # Fail fast if forwarding is enabled but misconfigured
+ if AUTOMATION_EVENT_FORWARDING_ENABLED:
+ if not AUTOMATION_SERVICE_URL:
+ raise ValueError(
+ 'AUTOMATION_EVENT_FORWARDING_ENABLED=true but '
+ 'AUTOMATION_SERVICE_URL is not configured'
+ )
+ if not AUTOMATION_WEBHOOK_SECRET:
+ raise ValueError(
+ 'AUTOMATION_EVENT_FORWARDING_ENABLED=true but '
+ 'AUTOMATION_WEBHOOK_SECRET is not configured'
+ )
+
+ async def forward_event(
+ self,
+ provider: ProviderType,
+ payload: dict[str, Any],
+ installation_id: int | str,
+ ) -> None:
+ """
+ Forward a Git provider webhook event to the automation service.
+
+ This is designed to be called as a fire-and-forget background task.
+ The forward path is optimized for speed - only org resolution is done here.
+ Access control checks are deferred to automation execution time.
+
+ Args:
+ provider: The Git provider type (e.g., GITHUB, GITLAB, BITBUCKET)
+ payload: The raw webhook payload from the provider
+ installation_id: The provider's installation/webhook ID
+ """
+ org_id: UUID | None = None
+ try:
+ # Resolve org context (org_id and git_org name) - uses Redis cache
+ org_context = await self._resolve_org_context(provider, payload)
+ if not org_context:
+ return
+
+ org_id = org_context.org_id
+
+ # Build minimal payload and forward immediately
+ # Access control is NOT computed here - it's deferred to execution time
+ event_payload = self._build_event_payload(org_context, payload)
+ await self._send_to_automation_service(provider, org_id, event_payload)
+
+ except (aiohttp.ClientError, asyncio.TimeoutError) as e:
+ # Network errors are expected and recoverable
+ logger.error(
+ f'[AutomationEventService] Network error forwarding '
+ f'{provider.value} event (org_id={org_id}): {e}',
+ exc_info=True,
+ extra={'installation_id': installation_id},
+ )
+ except Exception as e:
+ # Log unexpected errors. Note: This is a background task, so exceptions
+ # won't surface to the HTTP caller - they're logged for debugging only.
+ logger.error(
+ f'[AutomationEventService] Unexpected error forwarding '
+ f'{provider.value} event (org_id={org_id}): {e}',
+ exc_info=True,
+ extra={'installation_id': installation_id},
+ )
+ # Don't re-raise in background task - just log for debugging
+
+ async def _resolve_org_context(
+ self, provider: ProviderType, payload: dict[str, Any]
+ ) -> OrgContext | None:
+ """
+ Resolve the organization context from the webhook payload.
+
+ Uses Redis caching for both org claims and user ID mappings.
+ Returns None if the org cannot be resolved (not claimed, no personal org).
+
+ Args:
+ provider: The Git provider type
+ payload: The webhook payload from the provider
+ """
+ git_org_name, owner_type, owner_id = self._extract_owner_info(provider, payload)
+
+ if not git_org_name:
+ logger.warning(
+ f'[AutomationEventService] No repository owner in '
+ f'{provider.value} payload, skipping'
+ )
+ return None
+
+ # Try to resolve via OrgGitClaim
+ org_id = await self._resolve_git_org(provider, git_org_name)
+
+ # Fallback for personal repos (owner_type indicates individual user)
+ if not org_id and owner_type == 'User':
+ org_id = await self._resolve_personal_org(provider, owner_id)
+ if org_id:
+ logger.info(
+ f'[AutomationEventService] Resolved personal repo owner '
+ f'{git_org_name} to personal org {org_id} ({provider.value})'
+ )
+
+ if not org_id:
+ logger.warning(
+ f'[AutomationEventService] {provider.value} org {git_org_name} '
+ f'not claimed and no personal org found, skipping'
+ )
+ return None
+
+ return OrgContext(org_id=org_id, git_org=git_org_name)
+
+ def _extract_owner_info(
+ self, provider: ProviderType, payload: dict[str, Any]
+ ) -> tuple[str | None, str | None, int | None]:
+ """
+ Extract owner information from the webhook payload.
+
+ Different providers structure their payloads differently, so this method
+ normalizes the extraction.
+
+ Args:
+ provider: The Git provider type
+ payload: The webhook payload
+
+ Returns:
+ Tuple of (git_org_name, owner_type, owner_id)
+ - git_org_name: The organization/user name that owns the repo
+ - owner_type: 'User' or 'Organization' (or provider-specific equivalent)
+ - owner_id: The numeric ID of the owner (for personal org resolution)
+ """
+ # Compare using .value to handle different ProviderType enum instances
+ # (e.g., test mocks may use a different enum class with the same values)
+ if provider == ProviderType.GITHUB:
+ repo = payload.get('repository', {})
+ owner = repo.get('owner', {})
+ return owner.get('login'), owner.get('type'), owner.get('id')
+
+ logger.warning(f'Unsupported provider ({provider.value})')
+ return None, None, None
+
+ def _build_event_payload(
+ self,
+ org_context: OrgContext,
+ payload: dict[str, Any],
+ ) -> dict[str, Any]:
+ """
+ Build the minimal event payload to forward to the automation service.
+
+ Access control is NOT included here - it's deferred to execution time.
+ This keeps the forward path fast for high-traffic scenarios.
+ """
+ return {
+ 'organization': {
+ 'git_org': org_context.git_org,
+ 'openhands_org_id': str(org_context.org_id),
+ },
+ 'payload': payload,
+ }
+
+ # =========================================================================
+ # Cached Org Resolution Methods
+ # =========================================================================
+
+ async def _resolve_git_org(
+ self, provider: ProviderType, git_org_name: str
+ ) -> UUID | None:
+ """
+ Resolve a Git organization name to an OpenHands org_id.
+
+ Uses Redis caching with 1-hour TTL. Caches both positive and negative
+ results to avoid repeated DB queries for unclaimed orgs.
+
+ Args:
+ provider: The Git provider type
+ git_org_name: The organization/user name from the provider
+
+ Note: Org names are normalized to lowercase for both cache keys and
+ DB queries. This matches the OrgGitClaim schema which stores
+ git_organization as lowercase.
+ """
+ normalized_org = git_org_name.lower()
+ cache_key = f'{ORG_CLAIM_CACHE_PREFIX}:{provider.value}:{normalized_org}'
+
+ # Check cache first
+ cached = await self._get_cached_value(cache_key)
+ if cached is not None:
+ if cached == 'none':
+ logger.debug(
+ f'[AutomationEventService] Cache hit (negative): '
+ f'{provider.value} org {git_org_name} not claimed'
+ )
+ return None
+ logger.debug(
+ f'[AutomationEventService] Cache hit: '
+ f'{provider.value} org {git_org_name} -> {cached}'
+ )
+ return UUID(cached)
+
+ # Cache miss - use resolve_org_for_repo without user_id (no membership check)
+ # Construct a minimal repo name since resolve_org_for_repo extracts the org
+ org_id = await resolve_org_for_repo(
+ provider=provider.value,
+ full_repo_name=f'{normalized_org}/',
+ )
+
+ # Cache the result (including negative results)
+ if org_id:
+ await self._set_cached_value(
+ cache_key, str(org_id), ORG_CLAIM_CACHE_TTL_SECONDS
+ )
+ return org_id
+ else:
+ # Cache negative result to avoid repeated DB queries
+ await self._set_cached_value(cache_key, 'none', ORG_CLAIM_CACHE_TTL_SECONDS)
+ return None
+
+ async def _resolve_personal_org(
+ self, provider: ProviderType, provider_user_id: int | str | None
+ ) -> UUID | None:
+ """
+ Resolve a provider user to their personal OpenHands org.
+
+ For personal repos (owner type is 'User'), the OpenHands org_id
+ is the user's keycloak user ID. This allows users to set up
+ automations on their personal repos without needing an OrgGitClaim.
+
+ Uses Redis caching for the provider→Keycloak user ID mapping (24h TTL).
+
+ Args:
+ provider: The Git provider type
+ provider_user_id: The user ID from the provider (numeric or string UUID)
+ """
+ if not provider_user_id:
+ return None
+
+ keycloak_id = await self._get_keycloak_user_id_cached(
+ provider, provider_user_id
+ )
+ if keycloak_id:
+ return UUID(keycloak_id)
+ return None
+
+ async def _get_keycloak_user_id_cached(
+ self, provider: ProviderType, provider_user_id: int | str
+ ) -> str | None:
+ """
+ Convert a provider user ID to a Keycloak user ID.
+
+ Uses Redis caching with 24-hour TTL since this mapping never changes.
+ Caches negative results to avoid repeated Keycloak queries.
+
+ Args:
+ provider: The Git provider type
+ provider_user_id: The user ID from the provider
+ """
+ cache_key = f'{USER_ID_CACHE_PREFIX}:{provider.value}:{provider_user_id}'
+
+ # Check cache first
+ cached = await self._get_cached_value(cache_key)
+ if cached is not None:
+ if cached == 'none':
+ logger.debug(
+ f'[AutomationEventService] Cache hit (negative): '
+ f'{provider.value} user {provider_user_id} not in Keycloak'
+ )
+ return None
+ logger.debug(
+ f'[AutomationEventService] Cache hit: '
+ f'{provider.value} user {provider_user_id} -> Keycloak {cached}'
+ )
+ return cached
+
+ # Cache miss - query Keycloak
+ try:
+ keycloak_id = await self.token_manager.get_user_id_from_idp_user_id(
+ str(provider_user_id), provider
+ )
+
+ # Cache the result (including negative results)
+ if keycloak_id:
+ await self._set_cached_value(
+ cache_key, keycloak_id, USER_ID_CACHE_TTL_SECONDS
+ )
+ else:
+ # Cache negative result to prevent repeated Keycloak queries
+ await self._set_cached_value(
+ cache_key, 'none', USER_ID_CACHE_TTL_SECONDS
+ )
+
+ return keycloak_id
+ except Exception as e:
+ # Log at warning level to surface programmer errors and API issues
+ logger.warning(
+ f'[AutomationEventService] Failed to get keycloak ID for '
+ f'{provider.value} user {provider_user_id}: {e}'
+ )
+ return None
+
+ # =========================================================================
+ # Generic Redis Cache Helpers
+ # =========================================================================
+
+ async def _get_cached_value(self, cache_key: str) -> str | None:
+ """
+ Get a cached value from Redis.
+
+ Returns the cached string value, or None if not cached or Redis unavailable.
+ Falls back to DB/API queries if Redis is unavailable (graceful degradation).
+
+ Warning: When Redis is unavailable, every webhook will hit the DB directly.
+ Monitor logs for 'Redis unavailable' warnings to detect degradation.
+ """
+ try:
+ redis = getattr(sio.manager, 'redis', None)
+ if not redis:
+ # Log at warning level - this is a significant degradation that
+ # will cause DB load. Monitor these logs for alerting.
+ logger.warning(
+ '[AutomationEventService] Redis unavailable for cache read, '
+ 'falling back to direct DB queries (this will increase DB load)'
+ )
+ return None
+
+ cached = await redis.get(cache_key)
+ if cached is None:
+ return None
+
+ # Redis returns bytes, decode to string
+ return cached.decode('utf-8') if isinstance(cached, bytes) else cached
+ except Exception as e:
+ # Log at warning level - cache errors cause DB fallback
+ logger.warning(
+ f'[AutomationEventService] Redis cache read error '
+ f'(falling back to DB): {e}'
+ )
+ return None
+
+ async def _set_cached_value(
+ self, cache_key: str, value: str, ttl_seconds: int
+ ) -> None:
+ """
+ Set a cached value in Redis with TTL.
+
+ Fails silently if Redis is unavailable (graceful degradation).
+ """
+ try:
+ redis = getattr(sio.manager, 'redis', None)
+ if not redis:
+ # Silent failure - read path already logs the warning
+ return
+
+ await redis.setex(cache_key, ttl_seconds, value)
+ except Exception as e:
+ # Log at warning level for visibility
+ logger.warning(f'[AutomationEventService] Redis cache write error: {e}')
+
+ def _sign_payload(self, payload_bytes: bytes) -> str:
+ """
+ Sign a payload using the dedicated automation shared secret.
+
+ Uses AUTOMATION_WEBHOOK_SECRET (not GitHub webhook secret) to maintain
+ separate trust boundaries between GitHub webhooks and internal services.
+
+ Returns the signature in the format 'sha256=<hex_digest>'.
+ """
+ signature = hmac.new(
+ AUTOMATION_WEBHOOK_SECRET.encode('utf-8'),
+ msg=payload_bytes,
+ digestmod=hashlib.sha256,
+ ).hexdigest()
+ return f'sha256={signature}'
+
+ async def _send_to_automation_service(
+ self,
+ provider: ProviderType,
+ org_id: UUID,
+ payload: dict[str, Any],
+ ) -> None:
+ """
+ Send the normalized payload to the automation service.
+
+ The payload is signed using AUTOMATION_WEBHOOK_SECRET so the
+ automation service can verify it came from the OpenHands server.
+
+ Args:
+ provider: The Git provider type
+ org_id: The OpenHands organization ID
+ payload: The event payload to send
+ """
+ if not AUTOMATION_SERVICE_URL:
+ logger.warning(
+ '[AutomationEventService] AUTOMATION_SERVICE_URL not configured'
+ )
+ return
+
+ # Build endpoint URL. AUTOMATION_SERVICE_URL may include path segments
+ # (e.g., https://example.com/api/automation), so we strip trailing slash
+ # and append our path. The provider is included in the URL path.
+ base_url = AUTOMATION_SERVICE_URL.rstrip('/')
+ url = f'{base_url}/v1/events/{org_id}/{provider.value}'
+
+ # Serialize payload to JSON bytes for signing
+ payload_bytes = json.dumps(payload, separators=(',', ':')).encode('utf-8')
+ signature = self._sign_payload(payload_bytes)
+
+ headers = {
+ 'Content-Type': 'application/json',
+ 'X-Hub-Signature-256': signature,
+ }
+
+ try:
+ async with aiohttp.ClientSession() as session:
+ async with session.post(
+ url,
+ data=payload_bytes,
+ headers=headers,
+ timeout=aiohttp.ClientTimeout(total=AUTOMATION_SERVICE_TIMEOUT),
+ ) as resp:
+ if resp.status >= 400:
+ # Try JSON first (expected interface), fall back to text
+ # for infrastructure errors (502/503 from load balancer)
+ try:
+ body = await resp.json()
+ except (aiohttp.ContentTypeError, ValueError):
+ body = await resp.text()
+ logger.warning(
+ f'[AutomationEventService] Automation service returned '
+ f'{resp.status} for {provider.value} org {org_id}: {body}'
+ )
+ else:
+ data = await resp.json()
+ matched = data.get('matched', 0)
+ logger.info(
+ f'[AutomationEventService] Forwarded {provider.value} '
+ f'event to org {org_id}: {matched} automations matched'
+ )
+ except asyncio.TimeoutError:
+ logger.warning(
+ f'[AutomationEventService] Timeout ({AUTOMATION_SERVICE_TIMEOUT}s) '
+ f'forwarding {provider.value} event to automation service'
+ )
+ except aiohttp.ClientError as e:
+ logger.warning(
+ f'[AutomationEventService] HTTP error forwarding '
+ f'{provider.value} event to automation service: {e}'
+ )
diff --git a/enterprise/tests/unit/integrations/test_resolver_org_router.py b/enterprise/tests/unit/integrations/test_resolver_org_router.py
index 01b47572b4..599a05eee6 100644
--- a/enterprise/tests/unit/integrations/test_resolver_org_router.py
+++ b/enterprise/tests/unit/integrations/test_resolver_org_router.py
@@ -109,3 +109,43 @@ async def test_extracts_git_org_lowercase_from_repo_name(mock_stores):
mock_claim_store.get_claim_by_provider_and_git_org.assert_called_once_with(
'github', 'myorg'
)
+
+
+async def test_returns_org_id_without_membership_check_when_no_user_id(mock_stores):
+ """When user_id is None, skip membership check and return org_id if claim exists."""
+ from enterprise.integrations.resolver_org_router import resolve_org_for_repo
+
+ mock_claim_store, mock_member_store = mock_stores
+
+ # Arrange
+ claim = MagicMock()
+ claim.org_id = CLAIMING_ORG_ID
+ mock_claim_store.get_claim_by_provider_and_git_org.return_value = claim
+
+ # Act - no user_id provided
+ result = await resolve_org_for_repo('github', 'OpenHands/foo')
+
+ # Assert
+ assert result == CLAIMING_ORG_ID
+ mock_claim_store.get_claim_by_provider_and_git_org.assert_called_once_with(
+ 'github', 'openhands'
+ )
+ # Membership check should NOT be called
+ mock_member_store.get_org_member.assert_not_called()
+
+
+async def test_returns_none_when_no_claim_and_no_user_id(mock_stores):
+ """When no claim exists and no user_id, return None."""
+ from enterprise.integrations.resolver_org_router import resolve_org_for_repo
+
+ mock_claim_store, mock_member_store = mock_stores
+ mock_claim_store.get_claim_by_provider_and_git_org.return_value = None
+
+ # Act - no user_id provided
+ result = await resolve_org_for_repo('github', 'UnclaimedOrg/repo')
+
+ # Assert
+ assert result is None
+ mock_member_store.get_org_member.assert_not_called()
diff --git a/enterprise/tests/unit/server/services/test_automation_event_service.py b/enterprise/tests/unit/server/services/test_automation_event_service.py
new file mode 100644
index 0000000000..53c57ffdcd
--- /dev/null
+++ b/enterprise/tests/unit/server/services/test_automation_event_service.py
@@ -0,0 +1,828 @@
+"""
+Unit tests for AutomationEventService.
+
+Tests the service that forwards GitHub webhook events to the automation service.
+
+The service is optimized for high-traffic with:
+- Redis caching for org claim lookups (1 hour TTL)
+- Redis caching for provider→Keycloak user ID mappings (24 hour TTL)
+- Lazy access control (membership checks deferred to execution time)
+- Separate AUTOMATION_WEBHOOK_SECRET for internal service communication
+"""
+
+import uuid
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from openhands.integrations.service_types import ProviderType
+
+# Default patches for constants
+CONSTANT_PATCHES = {
+ 'server.services.automation_event_service.AUTOMATION_WEBHOOK_SECRET': 'test-shared-secret',
+ 'server.services.automation_event_service.AUTOMATION_SERVICE_TIMEOUT': 30,
+}
+
+
+def mock_token_manager():
+ """Create a mock TokenManager."""
+ return MagicMock()
+
+
+def mock_org_git_claim():
+ """Create a mock OrgGitClaim."""
+ claim = MagicMock()
+ claim.org_id = uuid.UUID('12345678-1234-5678-1234-567812345678')
+ return claim
+
+
+def github_org_payload():
+ """Create a sample GitHub webhook payload for an organization repo."""
+ return {
+ 'repository': {
+ 'id': 123456,
+ 'full_name': 'test-org/test-repo',
+ 'private': False,
+ 'default_branch': 'main',
+ 'owner': {
+ 'login': 'test-org',
+ 'id': 789,
+ 'type': 'Organization',
+ },
+ },
+ 'sender': {
+ 'id': 12345,
+ 'login': 'testuser',
+ },
+ 'action': 'opened',
+ 'installation': {
+ 'id': 99999,
+ },
+ }
+
+
+def github_user_payload():
+ """Create a sample GitHub webhook payload for a personal/user repo."""
+ return {
+ 'repository': {
+ 'id': 654321,
+ 'full_name': 'testuser/personal-repo',
+ 'private': True,
+ 'default_branch': 'main',
+ 'owner': {
+ 'login': 'testuser',
+ 'id': 12345,
+ 'type': 'User',
+ },
+ },
+ 'sender': {
+ 'id': 12345,
+ 'login': 'testuser',
+ },
+ 'action': 'opened',
+ 'installation': {
+ 'id': 99999,
+ },
+ }
+
+
+def create_service(mock_token_manager):
+ """Helper to create a service with mocked sio and constants."""
+ with patch('server.services.automation_event_service.sio'), patch.dict(
+ 'os.environ', {}, clear=False
+ ):
+ for key, value in CONSTANT_PATCHES.items():
+ patch(key, value).start()
+
+ from server.services.automation_event_service import AutomationEventService
+
+ return AutomationEventService(mock_token_manager)
+
+
+class TestResolveGitOrg:
+ """Tests for _resolve_git_org method with caching."""
+
+ @pytest.mark.asyncio
+ async def test_resolve_git_org_cache_miss_found(
+ self, mock_token_manager, mock_org_git_claim
+ ):
+ """
+ GIVEN: Cache miss and org claim exists in DB
+ WHEN: _resolve_git_org is called
+ THEN: Org ID is returned and cached
+ """
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None) # Cache miss
+ mock_redis.setex = AsyncMock()
+
+ with patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ return_value=mock_org_git_claim.org_id,
+ ), patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ result = await service._resolve_git_org(ProviderType.GITHUB, 'test-org')
+
+ assert result == mock_org_git_claim.org_id
+ # Verify result was cached
+ mock_redis.setex.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_resolve_git_org_cache_hit(self, mock_token_manager):
+ """
+ GIVEN: Org ID is cached in Redis
+ WHEN: _resolve_git_org is called
+ THEN: Cached value is returned without calling resolve_org_for_repo
+ """
+ cached_org_id = '12345678-1234-5678-1234-567812345678'
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=cached_org_id.encode())
+
+ with patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ ) as mock_resolver, patch(
+ 'server.services.automation_event_service.sio'
+ ) as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ result = await service._resolve_git_org(ProviderType.GITHUB, 'test-org')
+
+ assert result == uuid.UUID(cached_org_id)
+ # resolve_org_for_repo should NOT be called
+ mock_resolver.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_resolve_git_org_cache_miss_not_found(self, mock_token_manager):
+ """
+ GIVEN: Cache miss and org claim does NOT exist in DB
+ WHEN: _resolve_git_org is called
+ THEN: None is returned and negative result is cached
+ """
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None) # Cache miss
+ mock_redis.setex = AsyncMock()
+
+ with patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ return_value=None,
+ ), patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ result = await service._resolve_git_org(
+ ProviderType.GITHUB, 'unclaimed-org'
+ )
+
+ assert result is None
+ # Verify negative result was cached
+ mock_redis.setex.assert_called_once()
+ call_args = mock_redis.setex.call_args
+ # Second positional arg is the value
+ assert call_args[0][2] == 'none' # Negative cache value
+
+ @pytest.mark.asyncio
+ async def test_resolve_git_org_negative_cache_hit(self, mock_token_manager):
+ """
+ GIVEN: Negative result is cached (org not claimed)
+ WHEN: _resolve_git_org is called
+ THEN: None is returned without calling resolve_org_for_repo
+ """
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=b'none') # Cached negative
+
+ with patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ ) as mock_resolver, patch(
+ 'server.services.automation_event_service.sio'
+ ) as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ result = await service._resolve_git_org(
+ ProviderType.GITHUB, 'unclaimed-org'
+ )
+
+ assert result is None
+ mock_resolver.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_resolve_git_org_includes_provider_in_cache_key(
+ self, mock_token_manager, mock_org_git_claim
+ ):
+ """
+ GIVEN: GitHub provider with an org name
+ WHEN: _resolve_git_org is called
+ THEN: Cache key includes the provider name
+ """
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+ mock_redis.setex = AsyncMock()
+
+ with patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ return_value=mock_org_git_claim.org_id,
+ ), patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+
+ # Call for GitHub
+ await service._resolve_git_org(ProviderType.GITHUB, 'test-org')
+ github_cache_key = mock_redis.setex.call_args_list[0][0][0]
+
+ # Cache key should include provider
+ assert 'github' in github_cache_key
+
+
+class TestResolvePersonalOrg:
+ """Tests for _resolve_personal_org method with caching."""
+
+ @pytest.mark.asyncio
+ async def test_resolve_personal_org_cache_miss_found(self, mock_token_manager):
+ """
+ GIVEN: Cache miss and user exists in Keycloak
+ WHEN: _resolve_personal_org is called
+ THEN: Keycloak ID is returned and cached
+ """
+ keycloak_id = '87654321-4321-8765-4321-876543218765'
+ mock_token_manager.get_user_id_from_idp_user_id = AsyncMock(
+ return_value=keycloak_id
+ )
+
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None) # Cache miss
+ mock_redis.setex = AsyncMock()
+
+ with patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ result = await service._resolve_personal_org(ProviderType.GITHUB, 12345)
+
+ assert result == uuid.UUID(keycloak_id)
+ mock_redis.setex.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_resolve_personal_org_cache_hit(self, mock_token_manager):
+ """
+ GIVEN: Keycloak ID is cached in Redis
+ WHEN: _resolve_personal_org is called
+ THEN: Cached value is returned without Keycloak query
+ """
+ keycloak_id = '87654321-4321-8765-4321-876543218765'
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=keycloak_id.encode())
+
+ with patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ result = await service._resolve_personal_org(ProviderType.GITHUB, 12345)
+
+ assert result == uuid.UUID(keycloak_id)
+ # Token manager should NOT be called
+ mock_token_manager.get_user_id_from_idp_user_id.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_resolve_personal_org_no_user_id(self, mock_token_manager):
+ """
+ GIVEN: No provider user ID provided
+ WHEN: _resolve_personal_org is called
+ THEN: None is returned immediately
+ """
+ service = create_service(mock_token_manager)
+ result = await service._resolve_personal_org(ProviderType.GITHUB, None)
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_resolve_personal_org_includes_provider_in_cache_key(
+ self, mock_token_manager
+ ):
+ """
+ GIVEN: GitHub provider with a user ID
+ WHEN: _resolve_personal_org is called
+ THEN: Cache key includes the provider name
+ """
+ keycloak_id = '87654321-4321-8765-4321-876543218765'
+ mock_token_manager.get_user_id_from_idp_user_id = AsyncMock(
+ return_value=keycloak_id
+ )
+
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+ mock_redis.setex = AsyncMock()
+
+ with patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+
+ # Call for GitHub
+ await service._resolve_personal_org(ProviderType.GITHUB, 12345)
+ github_cache_key = mock_redis.setex.call_args_list[0][0][0]
+
+ # Cache key should include provider
+ assert 'github' in github_cache_key
+
+
+class TestForwardEvent:
+ """Tests for forward_event method (minimal payload, no access control)."""
+
+ @pytest.mark.asyncio
+ async def test_forward_org_event_success(
+ self, mock_token_manager, github_org_payload, mock_org_git_claim
+ ):
+ """
+ GIVEN: A GitHub event from a claimed organization repo
+ WHEN: forward_event is called
+ THEN: Minimal payload is forwarded (no access_control)
+ """
+ from server.services.automation_event_service import AutomationEventService
+
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+ mock_redis.setex = AsyncMock()
+
+ with patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ return_value=mock_org_git_claim.org_id,
+ ), patch(
+ 'server.services.automation_event_service.sio'
+ ) as mock_sio, patch.object(
+ AutomationEventService,
+ '_send_to_automation_service',
+ new_callable=AsyncMock,
+ ) as mock_send:
+ mock_sio.manager.redis = mock_redis
+
+ service = AutomationEventService(mock_token_manager)
+ await service.forward_event(
+ provider=ProviderType.GITHUB,
+ payload=github_org_payload,
+ installation_id=99999,
+ )
+
+ mock_send.assert_called_once()
+ call_args = mock_send.call_args
+ # Provider is first arg, org_id is second
+ assert call_args[0][0] == ProviderType.GITHUB
+ assert call_args[0][1] == mock_org_git_claim.org_id
+
+ payload = call_args[0][2]
+ assert payload['organization']['git_org'] == 'test-org'
+ assert 'payload' in payload
+ # access_control should NOT be in payload (lazy evaluation)
+ assert 'access_control' not in payload
+
+ @pytest.mark.asyncio
+ async def test_forward_personal_repo_event_success(
+ self, mock_token_manager, github_user_payload
+ ):
+ """
+ GIVEN: A GitHub event from a personal repo with linked OpenHands account
+ WHEN: forward_event is called
+ THEN: Event is forwarded using the user's personal org (keycloak ID)
+ """
+ from server.services.automation_event_service import AutomationEventService
+
+ keycloak_id = '87654321-4321-8765-4321-876543218765'
+ mock_token_manager.get_user_id_from_idp_user_id = AsyncMock(
+ return_value=keycloak_id
+ )
+
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+ mock_redis.setex = AsyncMock()
+
+ with patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ return_value=None, # No org claim for personal repo
+ ), patch(
+ 'server.services.automation_event_service.sio'
+ ) as mock_sio, patch.object(
+ AutomationEventService,
+ '_send_to_automation_service',
+ new_callable=AsyncMock,
+ ) as mock_send:
+ mock_sio.manager.redis = mock_redis
+
+ service = AutomationEventService(mock_token_manager)
+ await service.forward_event(
+ provider=ProviderType.GITHUB,
+ payload=github_user_payload,
+ installation_id=99999,
+ )
+
+ mock_send.assert_called_once()
+ call_args = mock_send.call_args
+ # Provider is first arg, org_id is second (personal org = keycloak ID)
+ assert call_args[0][0] == ProviderType.GITHUB
+ assert call_args[0][1] == uuid.UUID(keycloak_id)
+ payload = call_args[0][2]
+ assert payload['organization']['git_org'] == 'testuser'
+ assert payload['organization']['openhands_org_id'] == keycloak_id
+
+ @pytest.mark.asyncio
+ async def test_forward_event_no_owner_in_payload(self, mock_token_manager):
+ """
+ GIVEN: A GitHub event with no repository owner in payload
+ WHEN: forward_event is called
+ THEN: Event is skipped with warning log
+ """
+ from server.services.automation_event_service import AutomationEventService
+
+ payload = {
+ 'repository': {},
+ 'sender': {'id': 12345, 'login': 'testuser'},
+ }
+
+ with patch('server.services.automation_event_service.sio'), patch(
+ 'server.services.automation_event_service.logger'
+ ) as mock_logger, patch.object(
+ AutomationEventService,
+ '_send_to_automation_service',
+ new_callable=AsyncMock,
+ ) as mock_send:
+ service = AutomationEventService(mock_token_manager)
+ await service.forward_event(
+ provider=ProviderType.GITHUB,
+ payload=payload,
+ installation_id=99999,
+ )
+
+ mock_send.assert_not_called()
+ mock_logger.warning.assert_called()
+ assert 'No repository owner' in str(mock_logger.warning.call_args)
+
+ @pytest.mark.asyncio
+ async def test_forward_event_org_not_claimed_and_not_personal(
+ self, mock_token_manager, github_org_payload
+ ):
+ """
+ GIVEN: A GitHub event from an org that isn't claimed (and isn't personal)
+ WHEN: forward_event is called
+ THEN: Event is skipped with warning log
+ """
+ from server.services.automation_event_service import AutomationEventService
+
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+ mock_redis.setex = AsyncMock()
+
+ with patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ return_value=None,
+ ), patch('server.services.automation_event_service.sio') as mock_sio, patch(
+ 'server.services.automation_event_service.logger'
+ ) as mock_logger, patch.object(
+ AutomationEventService,
+ '_send_to_automation_service',
+ new_callable=AsyncMock,
+ ) as mock_send:
+ mock_sio.manager.redis = mock_redis
+
+ service = AutomationEventService(mock_token_manager)
+ await service.forward_event(
+ provider=ProviderType.GITHUB,
+ payload=github_org_payload,
+ installation_id=99999,
+ )
+
+ mock_send.assert_not_called()
+ mock_logger.warning.assert_called()
+ assert 'not claimed' in str(mock_logger.warning.call_args)
+
+
+class TestExtractOwnerInfo:
+ """Tests for _extract_owner_info method."""
+
+ def test_extract_github_owner_info(self, mock_token_manager, github_org_payload):
+ """
+ GIVEN: A GitHub webhook payload
+ WHEN: _extract_owner_info is called
+ THEN: GitHub owner info is correctly extracted
+ """
+ service = create_service(mock_token_manager)
+ git_org, owner_type, owner_id = service._extract_owner_info(
+ ProviderType.GITHUB, github_org_payload
+ )
+
+ assert git_org == 'test-org'
+ assert owner_type == 'Organization'
+ assert owner_id == 789
+
+ def test_extract_github_user_owner_info(
+ self, mock_token_manager, github_user_payload
+ ):
+ """
+ GIVEN: A GitHub webhook payload from a personal repo
+ WHEN: _extract_owner_info is called
+ THEN: User owner info is correctly extracted
+ """
+ service = create_service(mock_token_manager)
+ git_org, owner_type, owner_id = service._extract_owner_info(
+ ProviderType.GITHUB, github_user_payload
+ )
+
+ assert git_org == 'testuser'
+ assert owner_type == 'User'
+ assert owner_id == 12345
+
+
+class TestBuildEventPayload:
+ """Tests for _build_event_payload method."""
+
+ def test_build_minimal_payload(self, mock_token_manager):
+ """
+ GIVEN: Org context and payload
+ WHEN: _build_event_payload is called
+ THEN: Minimal payload with only org + payload is returned
+ """
+ from server.services.automation_event_service import OrgContext
+
+ service = create_service(mock_token_manager)
+
+ org_context = OrgContext(
+ org_id=uuid.UUID('12345678-1234-5678-1234-567812345678'),
+ git_org='test-org',
+ )
+ test_payload = {'action': 'opened', 'sender': {'login': 'user'}}
+
+ result = service._build_event_payload(org_context, test_payload)
+
+ assert result == {
+ 'organization': {
+ 'git_org': 'test-org',
+ 'openhands_org_id': '12345678-1234-5678-1234-567812345678',
+ },
+ 'payload': test_payload,
+ }
+ # Verify NO access_control in payload
+ assert 'access_control' not in result
+
+
+class TestSendToAutomationService:
+ """Tests for _send_to_automation_service method."""
+
+ @pytest.mark.asyncio
+ async def test_send_success(self, mock_token_manager):
+ """
+ GIVEN: AUTOMATION_SERVICE_URL is configured
+ WHEN: _send_to_automation_service is called
+ THEN: Request is sent with correct signature and provider in URL
+ """
+
+ org_id = uuid.UUID('12345678-1234-5678-1234-567812345678')
+ payload = {'organization': {'git_org': 'test'}, 'payload': {}}
+
+ mock_response = MagicMock()
+ mock_response.status = 200
+ mock_response.json = AsyncMock(return_value={'matched': 2})
+
+ mock_post_context = MagicMock()
+ mock_post_context.__aenter__ = AsyncMock(return_value=mock_response)
+ mock_post_context.__aexit__ = AsyncMock(return_value=None)
+
+ mock_session_instance = MagicMock()
+ mock_session_instance.post = MagicMock(return_value=mock_post_context)
+
+ mock_session_context = MagicMock()
+ mock_session_context.__aenter__ = AsyncMock(return_value=mock_session_instance)
+ mock_session_context.__aexit__ = AsyncMock(return_value=None)
+
+ with patch(
+ 'server.services.automation_event_service.AUTOMATION_SERVICE_URL',
+ 'https://automation.example.com',
+ ), patch('server.services.automation_event_service.sio'), patch(
+ 'server.services.automation_event_service.aiohttp.ClientSession',
+ return_value=mock_session_context,
+ ):
+ service = create_service(mock_token_manager)
+ await service._send_to_automation_service(
+ ProviderType.GITHUB, org_id, payload
+ )
+
+ # Verify the POST was called
+ mock_session_instance.post.assert_called_once()
+ # Verify URL includes provider
+ call_args = mock_session_instance.post.call_args
+ url = call_args[0][0]
+ assert '/github' in url
+ assert str(org_id) in url
+
+ @pytest.mark.asyncio
+ async def test_send_includes_provider_in_url(self, mock_token_manager):
+ """
+ GIVEN: GitHub provider
+ WHEN: _send_to_automation_service is called
+ THEN: The URL includes the provider name
+ """
+ org_id = uuid.UUID('12345678-1234-5678-1234-567812345678')
+ payload = {}
+
+ mock_response = MagicMock()
+ mock_response.status = 200
+ mock_response.json = AsyncMock(return_value={'matched': 0})
+
+ mock_post_context = MagicMock()
+ mock_post_context.__aenter__ = AsyncMock(return_value=mock_response)
+ mock_post_context.__aexit__ = AsyncMock(return_value=None)
+
+ mock_session_instance = MagicMock()
+ mock_session_instance.post = MagicMock(return_value=mock_post_context)
+
+ mock_session_context = MagicMock()
+ mock_session_context.__aenter__ = AsyncMock(return_value=mock_session_instance)
+ mock_session_context.__aexit__ = AsyncMock(return_value=None)
+
+ with patch(
+ 'server.services.automation_event_service.AUTOMATION_SERVICE_URL',
+ 'https://automation.example.com',
+ ), patch('server.services.automation_event_service.sio'), patch(
+ 'server.services.automation_event_service.aiohttp.ClientSession',
+ return_value=mock_session_context,
+ ):
+ service = create_service(mock_token_manager)
+
+ # Test GitHub
+ await service._send_to_automation_service(
+ ProviderType.GITHUB, org_id, payload
+ )
+ github_url = mock_session_instance.post.call_args_list[0][0][0]
+ assert github_url.endswith('/github')
+
+ @pytest.mark.asyncio
+ async def test_send_no_url_configured(self, mock_token_manager):
+ """
+ GIVEN: AUTOMATION_SERVICE_URL is not configured
+ WHEN: _send_to_automation_service is called
+ THEN: Warning is logged and nothing is sent
+ """
+ org_id = uuid.UUID('12345678-1234-5678-1234-567812345678')
+ payload = {}
+
+ with patch(
+ 'server.services.automation_event_service.AUTOMATION_SERVICE_URL', None
+ ), patch('server.services.automation_event_service.sio'), patch(
+ 'server.services.automation_event_service.logger'
+ ) as mock_logger:
+ service = create_service(mock_token_manager)
+ await service._send_to_automation_service(
+ ProviderType.GITHUB, org_id, payload
+ )
+
+ mock_logger.warning.assert_called()
+ assert 'not configured' in str(mock_logger.warning.call_args)
+
+
+class TestSignPayload:
+ """Tests for _sign_payload method."""
+
+ def test_sign_payload(self, mock_token_manager):
+ """
+ GIVEN: A payload bytes
+ WHEN: _sign_payload is called
+ THEN: HMAC-SHA256 signature is returned in correct format
+ """
+ with patch(
+ 'server.services.automation_event_service.AUTOMATION_WEBHOOK_SECRET',
+ 'test-shared-secret',
+ ), patch('server.services.automation_event_service.sio'):
+ service = create_service(mock_token_manager)
+ payload_bytes = b'{"test": "data"}'
+
+ signature = service._sign_payload(payload_bytes)
+
+ assert signature.startswith('sha256=')
+ assert len(signature) == 71 # 'sha256=' + 64 hex chars
+
+ def test_sign_payload_uses_dedicated_secret(self, mock_token_manager):
+ """
+ GIVEN: AUTOMATION_WEBHOOK_SECRET is configured
+ WHEN: _sign_payload is called
+ THEN: The dedicated secret is used (not GitHub webhook secret)
+ """
+ import hashlib
+ import hmac
+
+ # Use the default test secret from CONSTANT_PATCHES
+ shared_secret = 'test-shared-secret'
+ payload_bytes = b'{"test": "data"}'
+
+ # Calculate expected signature with the shared secret
+ expected_sig = hmac.new(
+ shared_secret.encode('utf-8'),
+ msg=payload_bytes,
+ digestmod=hashlib.sha256,
+ ).hexdigest()
+
+ with patch(
+ 'server.services.automation_event_service.AUTOMATION_WEBHOOK_SECRET',
+ shared_secret,
+ ), patch('server.services.automation_event_service.sio'):
+ service = create_service(mock_token_manager)
+ signature = service._sign_payload(payload_bytes)
+
+ assert signature == f'sha256={expected_sig}'
+
+
+class TestCacheHelpers:
+ """Tests for generic cache helper methods."""
+
+ @pytest.mark.asyncio
+ async def test_get_cached_value_hit(self, mock_token_manager):
+ """
+ GIVEN: Value exists in Redis cache
+ WHEN: _get_cached_value is called
+ THEN: Decoded string value is returned
+ """
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=b'cached-value')
+
+ with patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ result = await service._get_cached_value('test-key')
+
+ assert result == 'cached-value'
+
+ @pytest.mark.asyncio
+ async def test_get_cached_value_miss(self, mock_token_manager):
+ """
+ GIVEN: Value does not exist in Redis cache
+ WHEN: _get_cached_value is called
+ THEN: None is returned
+ """
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+
+ with patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ result = await service._get_cached_value('test-key')
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_get_cached_value_redis_unavailable(self, mock_token_manager):
+ """
+ GIVEN: Redis is unavailable
+ WHEN: _get_cached_value is called
+ THEN: None is returned (graceful degradation)
+ """
+ with patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = None
+
+ service = create_service(mock_token_manager)
+ result = await service._get_cached_value('test-key')
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_set_cached_value_success(self, mock_token_manager):
+ """
+ GIVEN: Redis is available
+ WHEN: _set_cached_value is called
+ THEN: Value is stored with TTL
+ """
+ mock_redis = AsyncMock()
+ mock_redis.setex = AsyncMock()
+
+ with patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = mock_redis
+
+ service = create_service(mock_token_manager)
+ await service._set_cached_value('test-key', 'test-value', 3600)
+
+ mock_redis.setex.assert_called_once_with('test-key', 3600, 'test-value')
+
+ @pytest.mark.asyncio
+ async def test_set_cached_value_redis_unavailable(self, mock_token_manager):
+ """
+ GIVEN: Redis is unavailable
+ WHEN: _set_cached_value is called
+ THEN: No error is raised (silent failure)
+ """
+ with patch('server.services.automation_event_service.sio') as mock_sio:
+ mock_sio.manager.redis = None
+
+ service = create_service(mock_token_manager)
+ # Should not raise
+ await service._set_cached_value('test-key', 'test-value', 3600)