How DS2API Uses the X-Ds2-Target-Account Header for Account Pinning
The X-Ds2-Target-Account header allows API clients to explicitly select a specific managed account from the DS2API pool, overriding the default automatic assignment behavior.
The CJackHwang/ds2api repository implements the X-Ds2-Target-Account header as a request-scoped override mechanism for account selection. This header bridges the gap between client intent and server-side resource allocation, enabling precise routing to specific managed accounts defined in the server configuration.
Header Extraction in the Auth Resolver
When DS2API receives a request, the authentication resolver immediately extracts the target account identifier from the incoming headers. In internal/auth/request.go (lines 72–78), the Determine method retrieves and sanitizes the header value:
target := strings.TrimSpace(req.Header.Get("X-Ds2-Target-Account"))
The trimmed target string is then passed to acquireManagedRequestAuth, which initiates the account binding process. If the header is absent or contains only whitespace, the resolver treats the request as having no preference, triggering the default pool selection behavior.
Account Pool Selection Logic
The account pool in internal/account/pool_acquire.go (lines 15–33) handles the actual resource allocation through the AcquireWait method. This method implements a priority-based selection algorithm:
- Explicit targeting: When
targetcontains a valid account identifier,AcquireWaitattempts to acquire that specific resource exclusively viaacquireLocked. - Fallback behavior: If the requested account is unavailable or the target string is empty, the pool falls back to selecting any free managed account from the available set.
// Acquire a specific target, waiting if necessary
acc, ok := p.AcquireWait(ctx, target, tried)
The pool maintains thread safety through its internal locking mechanisms, ensuring that the X-Ds2-Target-Account header respects concurrent request boundaries and prevents double-allocation of single-use accounts.
CORS Configuration for Cross-Origin Requests
DS2API explicitly whitelists the custom header in its CORS middleware to support browser-based clients. The defaultCORSAllowHeaders slice in internal/server/router.go (lines 157–162) includes the header among standard authorization fields:
var defaultCORSAllowHeaders = []string{
"Content-Type",
"Authorization",
"X-API-Key",
"X-Ds2-Target-Account",
// …
}
This configuration ensures that preflight OPTIONS requests succeed when web applications attempt to send the targeting header across origins.
Testing and Validation
The repository includes comprehensive test coverage for header-based account selection. In internal/auth/auth_edge_test.go (line 387), unit tests verify that setting the header forces the resolver to bind to the requested account:
req.Header.Set("X-Ds2-Target-Account", "acc2@test.com")
These tests validate both the happy path (successful targeting) and edge cases (invalid identifiers, missing headers, and concurrent access scenarios).
Client Implementation Example
To utilize the header in production requests, clients include it alongside authentication credentials:
curl -H "X-API-Key: <your-api-key>" \
-H "X-Ds2-Target-Account: acc2@example.com" \
https://api.ds2.example.com/v1/chat/completions
Summary
- The
X-Ds2-Target-Accountheader enables request-level pinning to specific managed accounts in DS2API. - Extraction occurs in
internal/auth/request.go, where the resolver sanitizes the header value before passing it to the account pool. - Selection logic in
internal/account/pool_acquire.goprioritizes explicit targets throughAcquireWait, falling back to automatic selection when necessary. - Browser compatibility is guaranteed by CORS configuration in
internal/server/router.gothat explicitly allows the custom header. - Behavioral contracts are enforced by unit tests in
internal/auth/auth_edge_test.goverifying correct account binding and error handling.
Frequently Asked Questions
What happens if the requested account in the X-Ds2-Target-Account header is already in use?
According to the pool implementation in internal/account/pool_acquire.go, the AcquireWait method either waits for the account to become available or falls back to the next free account if the target cannot be immediately acquired. The exact behavior depends on the pool's current state and the exclude map passed to the acquisition function.
Is the X-Ds2-Target-Account header case-sensitive?
The header follows standard HTTP conventions where the header name itself is case-insensitive per RFC 7230, but the account identifier value extracted in internal/auth/request.go is used exactly as provided (after strings.TrimSpace processing). Account matching against the pool depends on the exact string value configured in the server's account registry.
Do I need to include the X-Ds2-Target-Account header in every request?
No. As implemented in internal/auth/request.go, the header is optional. When omitted or empty, DS2API automatically selects any available managed account from the pool, functioning as a load-balanced proxy rather than a targeted one.
How does DS2API prevent unauthorized account access via this header?
The resolver validates the requested account against the configured pool in internal/account/pool_acquire.go. If the identifier does not match a valid managed account, the acquireLocked check fails, and the system either selects a fallback account or returns an authentication error, preventing access to undefined or restricted resources.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →