auth: своя Bearer-авторизация agentik (сервер + клиент + standalone)
Добавлена собственная авторизация по токену. Это ОТДЕЛЬНАЯ подсистема: библиотека A2A (pw.binom.a2a) имеет свой независимый token, общих типов и общей логики не вводится. Поведение по умолчанию не меняется: token = null -> авторизация выключена, сервер открыт (обратная совместимость), CLI/TUI не затронуты. Сервер (:server): - новый route-scoped плагин BearerTokenPlugin (BearerTokenConfig); - agentikAgent(agent, path, token) ставит плагин на всё поддерево /agentik, когда token != null; иначе плагин не устанавливается; - при несовпадении заголовка Authorization: Bearer <token> -> 401 Unauthorized; - /health всегда открыт (liveness для балансировщика). Клиент (:client): - defaultAgentikHttpClient(token) навешивает Authorization: Bearer <token> через DefaultRequest на весь HttpClient -> накрывает все 10 вызовов и оба SSE; - AgentikAgent(id, baseUrl, token, httpClient) — token необязательный, 9 существующих мест создания агента не тронуты. Standalone: - AgentSection.authToken (env AGENTIK_TOKEN) -> /agentik; - AgentSection.a2aToken (env AGENTIK_A2A_TOKEN) -> /a2a; - два независимых значения, связи между ними нет. Тесты: BearerTokenTest (5), BearerHeaderTest (3) — 401 без токена и с чужим, 200 с верным, /health открыт, null -> открыто. Мутационная проверка пройдена.
This commit is contained in:
@@ -27,7 +27,8 @@ import pw.binom.agentik.proto.Agent
|
||||
fun AgentikAgent(
|
||||
id: String,
|
||||
baseUrl: String,
|
||||
httpClient: HttpClient = defaultAgentikHttpClient(),
|
||||
token: String? = null,
|
||||
httpClient: HttpClient = defaultAgentikHttpClient(token),
|
||||
): Agent = AgentClient(httpClient = httpClient, baseUrl = baseUrl, id = id)
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,10 @@ package pw.binom.agentik.client
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.cio.CIO
|
||||
import io.ktor.client.plugins.DefaultRequest
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
|
||||
/**
|
||||
@@ -11,8 +14,18 @@ import io.ktor.serialization.kotlinx.json.json
|
||||
*
|
||||
* `requestTimeout = 0` — defense-in-depth против read-таймаута на SSE:
|
||||
* основная защита в `HttpRequestBuilder.noSseReadTimeout()` ([SseTimeout]).
|
||||
*
|
||||
* При заданном [token] на ВСЕ запросы клиента навешивается
|
||||
* `Authorization: Bearer <token>` через плагин [DefaultRequest]. Это накрывает
|
||||
* все 10 REST-вызовов и оба SSE-потока сразу — заголовок живёт на HTTP-клиенте,
|
||||
* а не в отдельных запросах.
|
||||
*/
|
||||
fun defaultAgentikHttpClient(): HttpClient = HttpClient(CIO) {
|
||||
fun defaultAgentikHttpClient(token: String? = null): HttpClient = HttpClient(CIO) {
|
||||
engine { requestTimeout = 0 }
|
||||
install(ContentNegotiation) { json(agentikJson) }
|
||||
if (token != null) {
|
||||
install(DefaultRequest) {
|
||||
header(HttpHeaders.Authorization, "Bearer $token")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package pw.binom.agentik.client
|
||||
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.statement.bodyAsText
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.application.call
|
||||
import io.ktor.server.application.createRouteScopedPlugin
|
||||
import io.ktor.server.cio.CIO as ServerCIO
|
||||
import io.ktor.server.engine.EmbeddedServer
|
||||
import io.ktor.server.engine.embeddedServer
|
||||
import io.ktor.server.response.respondText
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.route
|
||||
import io.ktor.server.routing.routing
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
/**
|
||||
* Тесты клиентской части: [defaultAgentikHttpClient] с заданным `token` прикладывает
|
||||
* `Authorization: Bearer <token>` ко всем запросам через плагин `DefaultRequest`,
|
||||
* без токена — заголовок не отправляется.
|
||||
*
|
||||
* Сервер в тесте — локальный ktor-CIO с inline route-scoped Bearer-плагином (один в один
|
||||
* как боевой [pw.binom.agentik.server.BearerTokenPlugin]). Тестовый `:server` не зависит
|
||||
* от `:client`, поэтому боевой плагин тут переиспользовать нельзя — пересоздаём его
|
||||
* минимально, контракт тот же.
|
||||
*/
|
||||
class BearerHeaderTest {
|
||||
|
||||
private val TestBearer = createRouteScopedPlugin(
|
||||
name = "TestBearer",
|
||||
createConfiguration = ::BearerCfg,
|
||||
) {
|
||||
val expected = pluginConfig.token
|
||||
onCall { call ->
|
||||
if (expected == null) return@onCall
|
||||
if (call.request.headers[HttpHeaders.Authorization] != "Bearer $expected") {
|
||||
call.respondText("Unauthorized", ContentType.Text.Plain, HttpStatusCode.Unauthorized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class BearerCfg {
|
||||
var token: String? = null
|
||||
}
|
||||
|
||||
private suspend fun startServer(): Pair<EmbeddedServer<*, *>, Int> {
|
||||
val server = embeddedServer(ServerCIO, port = 0) {
|
||||
routing {
|
||||
route("/agentik") {
|
||||
install(TestBearer) { token = "secret" }
|
||||
get("/conversations") {
|
||||
call.respondText("[]")
|
||||
}
|
||||
}
|
||||
}
|
||||
}.start(wait = false)
|
||||
val port = server.engine.resolvedConnectors().first().port
|
||||
return server to port
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientWithTokenAttachesBearerHeader() = runBlocking {
|
||||
val (server, port) = startServer()
|
||||
try {
|
||||
val client = defaultAgentikHttpClient("secret")
|
||||
val resp = client.get("http://127.0.0.1:$port/agentik/conversations")
|
||||
assertEquals(HttpStatusCode.OK, resp.status)
|
||||
assertEquals("[]", resp.bodyAsText())
|
||||
} finally {
|
||||
server.stop(100, 200)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientWithoutTokenGets401(): Unit = runBlocking {
|
||||
val (server, port) = startServer()
|
||||
try {
|
||||
val client = defaultAgentikHttpClient(null)
|
||||
val resp = client.get("http://127.0.0.1:$port/agentik/conversations")
|
||||
assertEquals(HttpStatusCode.Unauthorized, resp.status)
|
||||
} finally {
|
||||
server.stop(100, 200)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clientWithWrongTokenGets401(): Unit = runBlocking {
|
||||
val (server, port) = startServer()
|
||||
try {
|
||||
val client = defaultAgentikHttpClient("wrong")
|
||||
val resp = client.get("http://127.0.0.1:$port/agentik/conversations")
|
||||
assertEquals(HttpStatusCode.Unauthorized, resp.status)
|
||||
} finally {
|
||||
server.stop(100, 200)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user