diff --git a/README.md b/README.md index 7c14cf2..5154776 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,23 @@ task test:model pipeline нестабильным. Максимальное время ответа по умолчанию — 120 секунд; локально его можно изменить параметром `-MaxSeconds` у `scripts/run-natural-calendar.ps1`. +## Acceptance-тест подключения календаря + +`tests/connection-widget.js` проверяет путь до внешней интеграции без настоящего Google-аккаунта. +Conversation Service должен определить, что Google Calendar ещё не подключён, а Channel Gateway — +вернуть публичный виджет `connection` со свежей ссылкой авторизации. Сценарий проверяет HTTPS-адрес +Google, параметры `state`, PKCE `code_challenge`, отсутствие `client_secret` и новую ссылку при +повторном запросе с тем же `requestKey`. + +Окружением владеет `deploy`. Из него выполни: + +```powershell +task test:connection +``` + +Команда включает только тестовую конфигурацию Google OAuth. Она не вызывает Google и не передаёт +OAuth client secret в контейнер k6. Поэтому сценарий воспроизводим в локальной разработке и CI. + Runner сам получает короткоживущий JWT у локального Keycloak. В CI вместо тестового логина и пароля можно передать готовый `ACTION_TOKEN`. Скрипт принимает только локальные HTTP-адреса. Проверочный API `fake-calendar` доступен только в тестовом режиме и требует отдельный `X-Test-Key`; секреты не diff --git a/SERVICE.md b/SERVICE.md index 36ce943..b27e63e 100644 --- a/SERVICE.md +++ b/SERVICE.md @@ -9,5 +9,6 @@ | Первый acceptance-путь | Channel Gateway → Conversation Service → Agent Runtime → Widget decision через Channel Gateway → Action Service → Temporal → Calendar MCP | | Локальный запуск | `task test:e2e` против уже поднятого окружения | | Проверка AI-модели | `task test:model` против model-профиля; не входит в обычный CI | +| Проверка внешнего подключения | `task test:connection`: виджет Google Calendar, state, PKCE и свежая OAuth-ссылка | | Граница ответственности | Не поднимает сервисы и не содержит их component-тесты | diff --git a/Taskfile.yml b/Taskfile.yml index bdc4324..e94fd38 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -39,6 +39,11 @@ tasks: cmds: - '{{.POWERSHELL}} {{.POWERSHELL_ARGS}} -File ./scripts/run-natural-calendar.ps1' + test:connection: + desc: Проверить предложение подключения Google Calendar + cmds: + - '{{.POWERSHELL}} {{.POWERSHELL_ARGS}} -File ./scripts/run-connection.ps1' + test:load: desc: Выполнить настраиваемый нагрузочный тест cmds: diff --git a/scripts/check.ps1 b/scripts/check.ps1 index ccc05c1..2d920d4 100644 --- a/scripts/check.ps1 +++ b/scripts/check.ps1 @@ -1,5 +1,5 @@ $ErrorActionPreference = "Stop" -foreach ($file in @(".env.example", "compose.yaml", "Taskfile.yml", "tests/smoke.js", "tests/calendar-event.js", "tests/natural-calendar.js", "scripts/run-calendar.ps1", "scripts/run-natural-calendar.ps1", "chaos/pod-delay.yaml", "README.md", "AGENTS.md", "SERVICE.md")) { +foreach ($file in @(".env.example", "compose.yaml", "Taskfile.yml", "tests/smoke.js", "tests/calendar-event.js", "tests/natural-calendar.js", "tests/connection-widget.js", "scripts/run-calendar.ps1", "scripts/run-natural-calendar.ps1", "scripts/run-connection.ps1", "chaos/pod-delay.yaml", "README.md", "AGENTS.md", "SERVICE.md")) { if (-not (Test-Path $file)) { throw "Required file is missing: $file" } } if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { throw "Docker is not installed." } @@ -42,6 +42,21 @@ foreach ($required in @("verify:", "test:smoke:", "test:e2e:", "test:model:", "t if ($taskfile -notmatch [regex]::Escape($required)) { throw "Taskfile does not contain $required." } } +$connectionScript = Get-Content tests/connection-widget.js -Raw +foreach ($required in @("connection", "google-calendar", "schemaVersion", "button", "https://accounts.google.com/", "state", "code_challenge", "fresh authorization URL", "/api/v1/conversations/messages")) { + if ($connectionScript -notmatch [regex]::Escape($required)) { throw "Connection acceptance test does not contain $required." } +} +if ($connectionScript -match "GOOGLE_OAUTH_CLIENT_SECRET") { + throw "Connection acceptance test must not receive the OAuth client secret." +} + +$connectionRunner = Get-Content scripts/run-connection.ps1 -Raw +foreach ($required in @("connection-widget.js", "ACTION_TOKEN", "DOCKER_NETWORK", "CHANNEL_URL")) { + if ($connectionRunner -notmatch [regex]::Escape($required)) { throw "Connection runner does not contain $required." } +} + +if ($taskfile -notmatch '(?m)^ test:connection:') { throw "Taskfile does not contain test:connection." } + $ci = Get-Content .github/workflows/ci.yml -Raw foreach ($required in @("go-task/setup-task", "task verify", "task test:smoke")) { if ($ci -notmatch [regex]::Escape($required)) { throw "CI does not use $required." } diff --git a/scripts/run-connection.ps1 b/scripts/run-connection.ps1 new file mode 100644 index 0000000..3f2996d --- /dev/null +++ b/scripts/run-connection.ps1 @@ -0,0 +1,65 @@ +param( + [string]$ChannelUrl = "", + [string]$KeycloakUrl = "", + [string]$DockerNetwork = "" +) + +$ErrorActionPreference = "Stop" + +function Get-Setting([string]$Name, [switch]$Secret) { + $value = [Environment]::GetEnvironmentVariable($Name) + if (-not $value -and (Test-Path -LiteralPath ".env")) { + $line = Get-Content -LiteralPath ".env" | Where-Object { $_ -match "^$([regex]::Escape($Name))=" } | Select-Object -Last 1 + if ($line) { $value = $line.Substring($line.IndexOf('=') + 1) } + } + if (-not $value -and -not $Secret -and (Test-Path -LiteralPath ".env.example")) { + $line = Get-Content -LiteralPath ".env.example" | Where-Object { $_ -match "^$([regex]::Escape($Name))=" } | Select-Object -Last 1 + if ($line) { $value = $line.Substring($line.IndexOf('=') + 1) } + } + if (-not $value) { throw "Set $Name in the environment or local .env file." } + return $value +} + +function Assert-LocalUrl([string]$Url) { + $uri = [Uri]$Url + $allowedHosts = @("localhost", "127.0.0.1", "host.docker.internal") + if ($DockerNetwork) { $allowedHosts += "channel-gateway" } + if ($uri.Scheme -ne "http" -or $uri.Host -notin $allowedHosts) { + throw "Connection acceptance test allows local HTTP URLs only." + } +} + +$DockerNetwork = if ($DockerNetwork) { $DockerNetwork } else { [Environment]::GetEnvironmentVariable("DOCKER_NETWORK") } +if ($DockerNetwork -and $DockerNetwork -notmatch '^[a-zA-Z0-9][a-zA-Z0-9_.-]+$') { + throw "DOCKER_NETWORK contains unsupported characters." +} +$ChannelUrl = if ($ChannelUrl) { $ChannelUrl } else { Get-Setting "CHANNEL_URL" } +$KeycloakUrl = if ($KeycloakUrl) { $KeycloakUrl } else { Get-Setting "KEYCLOAK_URL" } +Assert-LocalUrl $ChannelUrl +Assert-LocalUrl $KeycloakUrl + +$token = [Environment]::GetEnvironmentVariable("ACTION_TOKEN") +if (-not $token) { + $tokenResponse = Invoke-RestMethod -Method Post ` + -Uri "$KeycloakUrl/realms/$(Get-Setting 'OIDC_REALM')/protocol/openid-connect/token" ` + -Body @{ + client_id = Get-Setting "OIDC_CLIENT_ID" + username = Get-Setting "TEST_USERNAME" -Secret + password = Get-Setting "TEST_PASSWORD" -Secret + grant_type = "password" + } + $token = $tokenResponse.access_token +} +if ($token.Split('.').Count -ne 3) { throw "ACTION_TOKEN is not a JWT." } + +$dockerArgs = @("run", "--rm", "--add-host", "host.docker.internal:host-gateway") +if ($DockerNetwork) { $dockerArgs += @("--network", $DockerNetwork) } +$dockerArgs += @( + "--volume", "${PWD}/tests:/tests:ro", + "--env", "CHANNEL_URL=$ChannelUrl", + "--env", "ACTION_TOKEN=$token", + (Get-Setting "K6_IMAGE"), "run", "/tests/connection-widget.js" +) + +& docker @dockerArgs +if ($LASTEXITCODE -ne 0) { throw "Connection widget acceptance scenario failed." } diff --git a/tests/connection-widget.js b/tests/connection-widget.js new file mode 100644 index 0000000..4667143 --- /dev/null +++ b/tests/connection-widget.js @@ -0,0 +1,89 @@ +import http from 'k6/http'; +import { check, fail } from 'k6'; + +const channelUrl = requiredUrl('CHANNEL_URL'); +const userToken = required('ACTION_TOKEN'); + +export const options = { + scenarios: { + connection_widget: { + executor: 'shared-iterations', + vus: 1, + iterations: 1, + }, + }, + thresholds: { + checks: ['rate==1'], + http_req_failed: ['rate==0'], + }, +}; + +export default function () { + const requestKey = `connection-test-${Date.now()}-${__VU}-${__ITER}`; + const first = sendMessage(requestKey); + const second = sendMessage(requestKey); + + check(first, { + 'reply asks for a connection': (reply) => reply.type === 'connection', + 'widget uses the public schema': (reply) => + reply.card?.schemaVersion === 1 && reply.card?.widget === 'connection', + 'widget asks for Google Calendar': (reply) => reply.card?.provider === 'google-calendar', + 'button contains a Google HTTPS URL': (reply) => + reply.card?.button?.url?.startsWith('https://accounts.google.com/'), + 'button contains PKCE and state': (reply) => + hasQuery(reply.card?.button?.url, 'state') && + hasQuery(reply.card?.button?.url, 'code_challenge') && + reply.card?.button?.url?.includes('code_challenge_method=S256'), + 'button does not expose client secret': (reply) => + !reply.card?.button?.url?.includes('client_secret'), + }); + check(second, { + 'repeated request keeps the connection widget': (reply) => reply.type === 'connection', + 'repeated request gets a fresh authorization URL': (reply) => + reply.card?.button?.url !== first.card?.button?.url, + }); +} + +function sendMessage(requestKey) { + const response = http.post( + `${channelUrl}/api/v1/conversations/messages`, + JSON.stringify({ + requestKey, + text: 'Создай встречу "Проверка подключения" с 2030-09-08T12:00:00+03:00 до 2030-09-08T12:30:00+03:00', + context: { + locale: 'ru-RU', + timeZone: 'Europe/Moscow', + }, + }), + { + headers: { + Authorization: `Bearer ${userToken}`, + 'Content-Type': 'application/json', + }, + }, + ); + if (response.status !== 200) { + fail(`conversation route did not return a connection widget: got ${response.status}`); + } + const reply = response.json().reply; + if (reply?.type !== 'connection' || reply.card?.widget !== 'connection') { + fail('conversation route returned no connection widget'); + } + return reply; +} + +function hasQuery(url, name) { + return typeof url === 'string' && new RegExp(`[?&]${name}=[^&]+`).test(url); +} + +function required(name) { + const value = __ENV[name]; + if (!value) { + throw new Error(`${name} is required`); + } + return value; +} + +function requiredUrl(name) { + return required(name).replace(/\/$/, ''); +}