RFC: pluggable authenticator API
まだ誰も着手していません。
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 25/100
- issue の種類
- 機能追加
- 明瞭さ
- おおむね明確
- 活発さ
- 活発
- 技術スタック
- swift
調査の方向性
Start by reading the proposed HTTPClientAuthenticator and HTTPClientExchange interfaces in the issue, then compare them with the linked httpx authentication and swift-openapi-runtime middleware examples. The proposal describes support for multiple authentication schemes, proxy authentication, and connection pinning; done would mean agreeing on an API that covers those use cases. This is RFC design work with no implementation files or tests named.
索引モデルが issue の本文から書いたものです。
説明
There have been long-standing requests for advanced authentication schemes: #354, #355, #393, #687. I've tried to design a flexible API for this.
The proposed API is largely inspired by Python's httpx. To make this approach work in Swift, it uses an async/await technique similar to swift-openapi-runtime's ClientMiddleware. Here's the interface:
public protocol HTTPClientAuthenticator: Sendable {
func authenticate(
_ request: HTTPClientRequest, exchange: HTTPClientExchange
) async throws -> HTTPClientResponse
}
public struct HTTPClientExchange: Sendable {
public enum Peer: Sendable {
case origin(host: String, port: Int), proxy(host: String, port: Int)
}
public var peer: Peer { ... }
/// Sends on the exchange's connection, opening a new one if none. Throws
/// .connectionChanged before writing if the connection was pinned and is now lost.
public func send(_ request: HTTPClientRequest) async throws -> HTTPClientResponse
/// Reserves a physical connection for this exchange, opening one if needed.
/// The same connection is returned by subsequent calls unless it closes or
/// is released. Use this when the scheme is connection-based (NTLM) or when
/// you need to view the certificate before making a request (TLS channel binding).
public func pinConnection() async throws -> HTTPClientConnection
public func pinConnection(with identity: some Hashable & Sendable) async throws -> HTTPClientConnection
/// Drains any pending response and returns the connection to the pool.
/// Call this before issuing a long-running operation.
public func releaseConnection() async
/// Records that the pinned connection has completed authentication, so the next
/// exchange that pins it sees `isAuthenticated == true` and can skip the token.
/// If the identity wasn't specified at the time of pinning, the connection
/// is closed on release instead of being returned to the pool.
public func markConnectionAuthenticated()
}
public struct HTTPClientConnection: Sendable {
public let httpVersion: HTTPVersion
public let tlsInfo: HTTPClient.TLSInfo?
public let isAuthenticated: Bool
}
// HTTPClient.Configuration
/// Default authenticator for all requests.
public var authenticator: (any HTTPClientAuthenticator)?
// HTTPClientRequest
/// Per-request override of the client's default authenticator.
public var authenticator: (any HTTPClientAuthenticator)?
// HTTPClient.Configuration.Proxy
/// Proxy authenticator. Called with `exchange.peer = .proxy(...)`.
public var authenticator: (any HTTPClientAuthenticator)?
And the actual usage:
let negotiate = NegotiateAuthenticator(
mutualAuthentication: .required,
channelBinding: .automatic
)
var config = HTTPClient.Configuration()
config.authenticator = negotiate // Set the default authenticator for all requests
config.proxy = .server(host: "proxy.corp.example.com", port: 3128)
config.proxy?.authenticator = negotiate // Use the same authenticator for the proxy
let client = HTTPClient(eventLoopGroupProvider: .singleton, configuration: config)
Some examples of authenticators
public struct BasicAuthenticator: HTTPClientAuthenticator {
public let username: String
public let password: String
public func authenticate(
_ request: HTTPClientRequest, exchange: HTTPClientExchange
) async throws -> HTTPClientResponse {
let token = Data("\(username):\(password)".utf8).base64EncodedString()
var request = request
request.headers.replaceOrAdd(name: exchange.peer.credentialsHeader, value: "Basic \(token)")
return try await exchange.send(request)
}
}
public struct NegotiateAuthenticator: HTTPClientAuthenticator {
public let mutualAuthentication: MutualAuthentication
public let channelBinding: ChannelBindingPolicy
public func authenticate(
_ request: HTTPClientRequest, exchange: HTTPClientExchange
) async throws -> HTTPClientResponse {
let peer = exchange.peer
let cred = try await GSSCredentialHandle.acquire()
let conn = try await exchange.pinConnection(with: NegotiateIdentity(principal: cred.principal))
var response = try await exchange.send(request)
var context: GSSContext?
for _ in 0..<3 {
guard response.status == peer.challengeStatus,
let challenge = response.negotiateChallenge(for: peer) else { break }
if context == nil {
let binding = try peer.isProxy ? nil : channelBinding.makeBinding(from: conn.tlsInfo)
context = try GSSContext(target: spn(for: peer), channelBinding: binding)
}
guard let token = try await context!.step(challenge) else { break }
var retry = request
retry.headers.replaceOrAdd(name: peer.credentialsHeader, value: "Negotiate \(token)")
response = try await exchange.send(retry)
}
guard let context, response.status != peer.challengeStatus else { return response }
if mutualAuthentication == .required { try await context.step(response.negotiateChallenge(for: peer)) }
exchange.markConnectionAuthenticated()
return response
}
}
extension HTTPClientExchange.Peer {
public var isProxy: Bool { if case .proxy = self { true } else { false } }
public var challengeStatus: HTTPResponseStatus { isProxy ? .proxyAuthenticationRequired : .unauthorized }
public var challengeHeader: String { isProxy ? "Proxy-Authenticate" : "WWW-Authenticate" }
public var credentialsHeader: String { isProxy ? "Proxy-Authorization" : "Authorization" }
}
The interface should cover all authentication schemes: Basic, Bearer with token refresh, Digest, NTLM, Negotiate, SCRAM, request signing, etc.
For comparison, this is what other libraries offer:
- httpx: Similar to this proposal, but lacks access to the connection before a request is sent and does not support connection pinning (this proposal provides both through
pinConnection()). - Apache HttpClient: A flexible API, but is not as easy to use since it's a state machine with multiple methods. Connection pinning is possible.
- OkHttp: Also an object with a single
authenticate()method, but a multi-leg authentication requires repeated calls. Otherwise, it allows channel binding to be implemented via a network interceptor, although connection pinning is not possible. - reqwest via reqwest-middleware: Custom authentication via middleware. Similar to this proposal, but you cannot pin a connection or see the certificate before receiving a response.
- .NET: Supports multiple authentication schemes out of the box, including those that require connection pinning and channel binding. It also allows you to override
Send, although you cannot access the connection there.
How the API looks like in other libraries
httpx (Python)
class ChallengeAuth(httpx.Auth):
def __init__(self, user, password):
self.user, self.password = user, password
def auth_flow(self, request):
response = yield request
if response.status_code != 401:
return # No authentication needed -> finish here
challenge = response.headers["WWW-Authenticate"]
request.headers["Authorization"] = build_header(challenge, request, self.user, self.password)
yield request
client = httpx.Client(auth=ChallengeAuth("alice", "s3cret"))
Apache HttpClient 5 (Java)
public final class TokenScheme implements AuthScheme {
private String nonce;
private boolean complete;
@Override public String getName() { return "Token"; }
@Override public boolean isConnectionBased() { return false; }
@Override public void processChallenge(AuthChallenge challenge, HttpContext ctx) { nonce = challenge.getValue(); }
@Override public boolean isResponseReady(HttpHost host, CredentialsProvider creds, HttpContext ctx) {
return creds.getCredentials(new AuthScope(host), ctx) != null;
}
@Override public String generateAuthResponse(HttpHost host, HttpRequest request, HttpContext ctx) {
complete = true;
return "Token " + sign(nonce, request);
}
@Override public boolean isChallengeComplete() { return complete; }
@Override public String getRealm() { return null; }
@Override public Principal getPrincipal() { return null; }
}
CloseableHttpClient client = HttpClients.custom()
.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeFactory>create()
.register("Token", ctx -> new TokenScheme())
.register(StandardAuthScheme.BASIC, BasicSchemeFactory.INSTANCE)
.build())
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultRequestConfig(RequestConfig.custom()
.setTargetPreferredAuthSchemes(List.of("Token", StandardAuthScheme.BASIC))
.build())
.build();
OkHttp (Kotlin)
class ChallengeAuthenticator(private val user: String, private val password: String) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
if (response.request.header("Authorization") != null) return null // Already tried: give up
val challenge = response.challenges().firstOrNull { it.scheme == "Token" } ?: return null
return response.request.newBuilder()
.header("Authorization", buildHeader(challenge, response.request, user, password))
.build()
}
}
val client = OkHttpClient.Builder()
.authenticator(ChallengeAuthenticator("alice", "s3cret")) // 401 from the origin
.proxyAuthenticator { route, response -> /* 407 from a proxy */ null }
.build()
reqwest (Rust)
struct ChallengeAuth { user: String, password: String }
#[async_trait::async_trait]
impl Middleware for ChallengeAuth {
async fn handle(&self, req: Request, ext: &mut Extensions, next: Next<'_>)
-> reqwest_middleware::Result<Response>
{
let retry = req.try_clone();
let resp = next.clone().run(req, ext).await?;
if resp.status() != StatusCode::UNAUTHORIZED { return Ok(resp); }
let Some(challenge) = resp.headers().get(WWW_AUTHENTICATE).cloned() else { return Ok(resp) };
let Some(mut retry) = retry else { return Ok(resp) };
retry.headers_mut().insert(AUTHORIZATION, build_header(&challenge, &retry, &self.user, &self.password));
next.run(retry, ext).await
}
}
let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new())
.with(ChallengeAuth { user: "alice".into(), password: "s3cret".into() })
.build();
.NET HttpClient (C#)
Built-in authentication:
var handler = new SocketsHttpHandler
{
Credentials = CredentialCache.DefaultCredentials,
// Or a custom CredentialCache:
// cache.Add(new Uri("https://intranet/"), "Negotiate", new NetworkCredential("alice", "s3cret", "CORP"));
PreAuthenticate = true,
Proxy = new WebProxy("http://proxy.corp:3128") { Credentials = CredentialCache.DefaultCredentials },
};
var client = new HttpClient(handler);
Customization:
sealed class TokenRefreshHandler(ITokenSource tokens) : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
request.Headers.Authorization = new("Bearer", await tokens.GetAsync(ct));
var response = await base.SendAsync(request, ct);
if (response.StatusCode != HttpStatusCode.Unauthorized) return response;
response.Dispose(); // Release the connection
request.Headers.Authorization = new("Bearer", await tokens.RefreshAsync(ct));
return await base.SendAsync(request, ct);
}
}
var client = new HttpClient(new TokenRefreshHandler(tokens) { InnerHandler = new SocketsHttpHandler() });
- 主要言語
- Swift
- スター
- 1.1k
- フォーク
- 159
- 平均マージ
- 18時間 43分
- マージ済み PR(30日)
- 2
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートなし
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
swift-server/async-http-client のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 73/100
swift-server/async-http-client#950 · コメント 1 件 ·
-
RequestBag keeps the request body after an early response with status >= 300対応中かも @beshkenadze が 28 日前に担当しました。 オープン
難易度 3/5 1〜2日 初心者へのやさしさ 68/100
-
HTTP/2 stream stays half-closed after an early response with status >= 300対応中かも @beshkenadze が 28 日前に担当しました。 オープン
難易度 4/5 3〜5日 初心者へのやさしさ 55/100
-
Transaction keeps the request body after an early response with status >= 300対応中かも @beshkenadze が 28 日前に担当しました。 オープン
難易度 4/5 3〜5日 初心者へのやさしさ 35/100
-
難易度 4/5 3〜5日 初心者へのやさしさ 22/100
swift-server/async-http-client の issue をすべて見る
似ている issue
-
bug
難易度 2/5 1〜3時間 初心者へのやさしさ 70/100
swiftlang/swift-org-website#1608 ·
メンテナーはふだん 2 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 65/100
-
難易度 2/5 1〜3時間 初心者へのやさしさ 65/100
haacked/switchboard#460 ·
メンテナーはふだん 1 日以内に返信
-
難易度 1/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 67/100
manaflow-ai/cmux#47572 ·
メンテナーはふだん 1 日以内に返信