Commit Graph
64 Commits
Author SHA1 Message Date
Paweł Banaszewski a3f25a491e feat: forward bridged routes in AI Gateway proxy mode (#30226)
Enable bridged request forwarding in AI Gateway proxy mode. Responses
are captured through `TeeBuffer`.
Proxies are created per-request reusing transports.

Handle `http.ErrAbortHandler` inside the circuit-breaker wrapper so
aborted responses are classified by HTTP status before the panic is
propagated.

Generated by Coder Agents on behalf of @pawbana.
2026-11-17 18:02:24 +00:00
Sas SwartandClaude Opus 5.5 1ec94c74dc fix(coderd): return 500, not 403, when AI Gateway authorization hits a database error (#31617)
When coderd's `IsAuthorized` hits a database error, the AI Gateway
answers 403. A coderd outage therefore looks to clients like a
permission problem. The gateway can't tell coderd's own failures from
rejected requests, because coderd returns both as plain errors. Worse,
the API key and user lookups turn any database error into
`ErrUnknownKey` or `ErrUnknownUser`.

coderd now marks each database failure in `IsAuthorized` with the dRPC
error code `proto.ErrCodeInternal`, where the failure happens. This
covers the key, user, workspace, organization membership and effective
group lookups. The key and user lookups return `ErrUnknownKey` and
`ErrUnknownUser` only for `sql.ErrNoRows`. Rejections carry no code. The
gateway answers a coded error with 500 and every other error with 403.

dRPC sends the code with the error, so the protocol version doesn't
change. A gateway and coderd on different versions keep today's 403,
because the older side neither sets nor reads the code.

A connection that drops during the `IsAuthorized` call still gets a 403.
That's left for a follow-up.

`TestAuthorization_InternalErrors` covers each database failure and each
rejection on the direct, workspace token and delegated paths.
`TestServeHTTP_FailureModes` covers the gateway's status codes.

Refs AIGOV-737

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 07:39:54 +02:00
Susana Ferreira c83914f514 feat: resolve the chat organization for Coder Agents AI Gateway requests (#31584)
## Description

Resolves Coder Agents requests to the chat's organization instead of the
organization of the user's effective group, so budgets and cost follow
the chat's organization. coderd checks that the user is still a member
of that organization and that it isn't deleted, and rejects the request
otherwise.

## Changes

- Add `delegated_organization_id` to `IsAuthorizedRequest`, part of
aibridged API v1.6, which is not released yet.
- aibridged sends the chat organization from the delegated attribution
on delegated requests.
- `IsAuthorized` accepts the delegated organization only on delegated
(`key_id`) requests, and rejects it otherwise.
- The org resolver resolves the chat organization with source `chatd`,
after checking membership. The membership check is shared with the
workspace path.
- Add `TestAuthorization_DelegatedOrgResolution`, extend
`TestServeHTTP_ResolvedOrganization` with a delegated chat request, and
make `TestIntegrationResolvedOrganization` table-driven, with a case per
organization source and a delegated request with a workspace.

Closes AIGOV-713

> [!NOTE]
> Generated by Coder Agents on behalf of @ssncferreira.
2026-11-03 16:39:43 +00:00
Sas Swart 15365c69cf feat: use the resolved organization for AI Gateway budgets and cost (1/2) (#31120)
`IsAuthorized` resolves the workspace organization, but uses it only to
reject requests; nothing downstream reads it. The budget check and cost
each resolve the group site-wide, so a user working in an org B
workspace can be billed in org A, and no interception records its
organization.

Resolve the request organization once, in `IsAuthorized`. A workspace
session token resolves to the workspace's organization (source
`workspace`). Any other request, including chatd requests until
AIGOV-713, resolves to the organization of the user's site-wide
effective group (source `effective_group`). Return the source in
`IsAuthorizedResponse`.

Have aibridged pass the organization to `IsBudgetExceeded`, which
resolves the budget inside it, and stamp the organization and source on
`RecordInterception`. Resolve cost's effective group inside the
organization stored on the interception. When there is no organization,
behave site-wide as before.

Move `resolveOrganization` and the workspace checks into
`orgresolver.go`, and leave a slot for the chat organization
(AIGOV-713). Bump the aibridged API to v1.6, adding
`IsAuthorizedResponse.organization_source` and
`IsBudgetExceededRequest.organization_id`.

aibridged checks only the shape of the organization (both fields or
neither, and a valid non-nil UUID), not the source value. That lets a
newer coderd add a source without breaking older gateways.

Behaviour changes to review:

- Spend follows the workspace's organization. A user whose budgets are
all in org A has no limit in an org B workspace if B has none.
- A database error while resolving the organization now returns 403 from
`IsAuthorized`, instead of 500 from `IsBudgetExceeded`.
- Requests without a workspace make up to three extra budget queries in
`IsAuthorized`.
- The user spend status endpoint (`GET /api/v2/users/{user}/ai/spend`)
stays site-wide, so it can disagree with where a request was charged.

The org-aware price lookup follows in #31121.

Part of AIGOV-716. Stacked on #31119.

---

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-30 13:35:23 +02:00
Sas Swart 161b7233d9 feat(coderd): store the organization on AI Gateway interceptions (#31118)
Adds `organization_id` (FK to `organizations`, `ON DELETE RESTRICT`) and
`organization_source` (new enum: `workspace`, `chatd`,
`effective_group`) to `aibridge_interceptions`, with a check constraint
that keeps them set or unset together. Cost and pricing run later, in
`RecordTokenUsage`, so they need the organization that AIGOV-716a
resolves once per request stored on the interception row.

`RecordInterceptionRequest` gains `organization_id` (18) and
`organization_source` (19), and the aibridged API moves to v1.5.
`RecordInterception` stores a valid pair; any other combination is
logged as a warning and stored as NULLs, so a gateway bug never turns
into an HTTP 500 for the user. A well-formed ID for an organization that
does not exist fails on the FK, like an unknown `initiator_id`. Nothing
sends the fields yet, so behaviour is unchanged until AIGOV-716a.

**Malformed values are stored as empty, not rejected.** A failed
`RecordInterception` returns HTTP 500 to the user, so the server logs a
warning and stores NULLs instead. The one exception is a well-formed ID
for an organization that does not exist: the foreign key rejects it, the
same as an unknown `initiator_id` today.

Part of AIGOV-712

*This PR was generated by Coder Agents on behalf of @SasSwart.*
2026-10-28 10:52:35 +02:00
Sas Swart 946c2f0e04 feat: resolve orgs from workspace session tokens in AI Gateway requests (#30902)
Add an AI Gateway org resolver at the coderd IsAuthorized boundary,
detect workspace session tokens, load the workspace org, validate the
user is still a member of that org, reject missing workspaces or invalid
membership, and return the resolved org in IsAuthorizedResponse while
leaving it unused by downstream policy. Include tests for successful
workspace-token resolution, missing workspace rejection, invalid org
membership rejection, and compatibility with the existing ServeHTTP
flow.

Fixes AIGOV-714
2026-10-26 11:40:51 +02:00
Danny Kopping 30499fdcfa fix(coderd/aibridged): allow evicted bridges ten minutes to drain (#30830)
AI Gateway evicts cached request bridges after 15 minutes and currently
gives in-flight requests only five seconds to finish, cutting off
otherwise healthy model calls and streams.

Give evicted bridges up to ten minutes to drain without changing the
cache TTL. New acquisitions use a replacement bridge while the retired
one drains. Pool shutdown retains a five-second cancellation grace
period for cached and already-retired bridges, even when an acquisition
is blocked initializing MCP connections. Requests still running at the
drain deadline are cancelled.

Refs
[AIGOV-672](https://linear.app/codercom/issue/AIGOV-672/aibridged-15-minute-bridge-ttl-cancels-in-flight-ai-gateway-requests).
The separate acquisition/admission race tracked in
[AIGOV-609](https://linear.app/codercom/issue/AIGOV-609) is outside this
change.

---

Created by OpenCode on behalf of @dannykopping.
2026-10-22 15:46:27 +02:00
Paweł Banaszewski f08bfddfa7 feat: validate AI Gateway actor and credentials in proxy mode (#30225)
Extends the AI Gateway `forwardingHandler` with actor check, provider
credential resolution, and initial interception metadata.
Missing provider credentials return 403
Credential resolution failures return 500 with details kept in logs.
AWS-signed bridged credentials remain unsupported.

Generated by Coder Agents on behalf of @pawbana.
2026-10-07 16:51:19 +00:00
Paweł Banaszewski 7cfc38d0e7 feat: wire AI Gateway proxy routing and recorder dependencies (#29725)
Adds `forwardingHandler` for "bridged" routes in proxy mode. Wires
provider snapshots to a shared mux and recorder, tracing, circuit
breakers, and the server-owned inflight gate.

Generated by Coder Agents on behalf of @pawbana.
2026-10-05 17:33:07 +00:00
Paweł Banaszewski ffc7dadfe2 refactor: use typed AI Gateway actor identity (#30258)
Adds typed AI Gateway actor identity, including the API key ID used by
recording.

Recorders now read the authenticated API key ID from each call context
instead of capturing request identity at construction time. This allows
one recorder to be reused safely across sequential and concurrent
requests. Includes context helper coverage and recorder regression
tests.

Generated by Coder Agents on behalf of @pawbana.
2026-10-05 14:00:15 +00:00
Paweł Banaszewski f96d2696a4 chore: extract recorder construction (#30224)
Extract `newRecorder` from the interception pool into helper.
This lets the proxy use the same recorder construction code.

Generated by Coder Agents on behalf of @pawbana.
2026-10-02 16:18:52 +02:00
Paweł Banaszewski 7e64b46721 fix: drain proxy requests before closing DRPC (#29724)
Keep DRPC available while admitted AI Gateway proxy requests drain,
rather than canceling the DRPC connection lifecycle at the start of
shutdown.
After shutdown reject new handler acquisition immediately.
Once requests finish or the shutdown context expires, cancel remaining
proxy requests and the DRPC lifecycle. Shutdown stops waiting for the
DRPC connection loop when its deadline expires.
Reconnects skip initialization once a backend is selected.

Generated by Coder Agents on behalf of @pawbana.
2026-10-01 12:25:11 +00:00
Cian Johnston 8742d2484c feat: add opt-in AI Gateway actor email headers (#29930)
Add opt-in forwarding of the authenticated Coder account email through
`--ai-gateway-actor-header-meta-email`,
`CODER_AI_GATEWAY_ACTOR_HEADER_META_EMAIL`, or
`ai_gateway.actor_header_meta_email`. The option defaults to empty:
enabling `send_actor_headers` alone does not forward email. Set a
destination header explicitly to opt in; accounts without an email omit
it.

Carry authenticated email through the Gateway authorization response and
strip client-supplied standard/configured email headers before applying
trusted identity. The additive protocol field joins unreleased Gateway
API v1.3 alongside workspace attribution. Includes email configuration
precedence, authorization compatibility, captured upstream request
tests, and matching documentation.

Refs https://linear.app/codercom/issue/AIGOV-601

Generated with Coder Agents on behalf of @johnstcn.
2026-09-29 20:07:49 +01:00
Cian Johnston 05d1fa8a4c feat: configure AI Gateway actor identity headers (#29929)
Allows configuring AI Gateway actor ID and username headers independently through
`--ai-gateway-actor-header-id` and
`--ai-gateway-actor-header-username` or associated environment
variables and YAML settings. 

- Defaults to existing header name, an empty string disables that attribute. 
- Existing `send_actor_headers` gate remains off by default.
- Validates header names, case-insensitive collisions, and protected
destinations for embedded and standalone gateways.
- Strips standard and configured identity destinations before injecting authenticated values.
- Adds coverage for configuration precedence, captured upstream request, and generated help/API documentation.

Refs https://linear.app/codercom/issue/AIGOV-601

Generated with Coder Agents on behalf of @johnstcn.
2026-09-29 18:22:59 +01:00
Susana Ferreira e5a449e172 feat: record provider model on AI Gateway token usage (#30086)
## Description

Record the model reported by the upstream provider on each AI Gateway
token usage and send it to coderd as `provider_model` on
`RecordTokenUsageRequest`. The provider can report a different model
than the one requested (for example, an alias or a dated snapshot), and
pricing only by the requested model leaves those requests unpriced.

This PR only captures and transmits the model. coderd ignores it for
now, and storing it and using it for price lookup will be added upstack.

Related to https://linear.app/codercom/issue/AIGOV-650

## Changes

- Add `ProviderModel` to `recorder.TokenUsageRecord`, set from the
response `model` in the messages, chat completions, and responses
interceptors (blocking and streaming).
- Add `provider_model` to `RecordTokenUsageRequest`, as part of the
unreleased aibridged API v1.3.
- Assert the recorded provider model in the interceptor and integration
tests.

> [!NOTE]
> Generated by Claude Code on behalf of @ssncferreira.
2026-09-29 17:47:27 +01:00
Sas Swart 813b8c151f feat: make AI Gateway content recording optional (#30031)
Add `--ai-gateway-disable-content-recording`, which stops user prompts,
tool
calls and model thoughts from being stored. Cost control reads none of
those
tables, so budgets, spend accounting and enforcement are unaffected.

A dropped record is still logged, so pairing the option with
`--ai-gateway-structured-logging-source=gateway` keeps the SIEM export
for
records that are never persisted. The gateway warns at startup when
content is
dropped while coderd is the only emitter, since those records then reach
neither
the database nor a SIEM.

Covered end to end for the embedded and the standalone gateway, and
documented
alongside cost controls.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 11:48:53 +02:00
Sas Swart 23fb35d185 feat: let the AI Gateway emit the structured interception records (#30030)
coderd emitted the structured interception records as they arrived over
DRPC, so
a record the gateway never sends cannot be exported.

- Add `--ai-gateway-structured-logging-source` (`coderd`, `gateway`,
`both`) and
teach the gateway's `LogRecorder` to emit the same format where the
records
originate. Gateway lines omit `thread_parent_id` and `thread_root_id`,
which
  are resolved by a database lookup only coderd can perform.
- Reaching the serving pool required repairing the pool options: they
were
derived at construction sites and discarded, so the server always built
its
pool with the defaults. They are now derived from the deployment
configuration
in one place and passed to the pool that serves requests. The server
reports
those options, and its ownership of the `key_pool_state` collector, so a
second
  registration cannot silently reappear and panic startup.
- The standalone gateway inherits both structured logging options, since
it is
  now one of the processes that can emit.

This is the keystone of the stack: the flag, the mechanism that carries
it and
the behavior it selects land together, so
`TestAIGatewayStart_InheritedOptions`
and the gateway help output stay truthful at every commit.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 11:48:52 +02:00
Sas Swart 868dcd9c75 refactor: fold AI Gateway recorder client acquisition into DRPCRecorder (#29919)
`WrappedRecorder` existed to resolve a client per record call and to
stamp
timestamps. With stamping moved to the creation sites, resolving a
client is all
it did, and `DRPCRecorder` is the only recorder that needs one.

Give `DRPCRecorder` the client function and delete `WrappedRecorder`, so
the
chain has one fewer layer and `NewRecorder` takes the recorder it
decorates.

Each PR targets the one before it. Together they are #29664, which stays
open
until the stack is merged; the tip of the stack is byte-identical to its
tree.

<details>
<summary>Why the stack is ordered this way</summary>

The final design is a chain of recorder decorators:

    +---------------------+
    |    AsyncRecorder    |  all records except the interception start
    +---------------------+
    |     LogRecorder     |  emit the structured record
    +---------------------+
    | ValidatingRecorder  |  refuse malformed records
    +---------------------+
    |  caller middleware  |  record policy, e.g. drop content
    +---------------------+
    |    TraceRecorder    |
    +---------------------+
    |    DRPCRecorder     |  acquire client, send to coderd
    +---------------------+

Ordering constraints:

- The record type constants (1) are the vocabulary both emitters and the
  validator use, so they come first.
- Validation (5) rejects unset timestamps, so records must already be
stamped
where they are created (3). Stamping at creation leaves
`WrappedRecorder`
  doing nothing but client acquisition, which is why it is folded into
  `DRPCRecorder` (4) and not before.
- coderd's server-time fallback (2) is what keeps a gateway of an older
version
  from persisting zero times once the gateway owns stamping (3).
- PRs 1 to 5 change no user-visible surface. Each deployment option then
lands
with the code that reads it: the log source with gateway-side emission
(6),
content recording with the filter that drops the records (7). Pool
options are
plumbed to the serving pool in 6, where the first option that needs them
  arrives, rather than as an unused hook beforehand.

</details>

---
🤖 Raised by [Coder Agents](https://coder.com) on behalf of @SasSwart.
2026-09-29 10:47:22 +02:00
Seth ShelnuttandCian Johnston faa9815cd6 feat: configure Claude Platform for AWS on Anthropic providers (#29049)
This PR adds configuration plumbing for Claude Platform on AWS

## Summary

Makes Claude Platform for AWS configurable as a settings variant of
`type=anthropic`, discriminated by `_type: "claude_platform_aws"`.
Settings contain only `region` and `workspace_id`, plus the schema
version. No new provider type or database enum is introduced.

The API persists and projects those settings to the gateway. Provider
keys can be added or removed independently: allowed BYOK takes
precedence, followed by stored keys, then ambient SigV4 when neither key
source applies. Model-availability hints and keyless provider
construction reflect that ambient capability. Rejected or exhausted keys
do not fall back to IAM.

Removes Claude Platform-specific AWS identity fields, secret
redaction/merge behavior, external-ID handling, and mode/key consistency
checks. Bedrock configuration remains intact. Environment-based provider
seeding was removed upstream and is not restored. The Claude Platform
form and Experimental label remain follow-up work in #29050.

## Authentication limitation

Each Claude Platform provider uses either the gateway's ambient AWS
credentials when no provider keys are stored, or its stored API-key
pool. In either case, a client credential takes precedence when BYOK is
enabled. Rejected BYOK or an exhausted provider key pool does not fall
back to ambient IAM.

There is no per-provider AWS identity selection: keyless providers on
the same gateway share its ambient AWS credential chain and cannot
configure separate AWS access keys or assumed roles. Each provider still
has its own Claude Platform workspace ID and separate provider
attribution in Coder's usage/cost records; this does not imply separate
AWS billing accounts.

## Validation

- Race tests passed for SDK, daemon projection, db2sdk, chatprovider,
and targeted CLI/API configuration tests.
- Installed pre-commit hook passed, including generation, frontend/Go
lint, and build.
- Tests cover settings round trips, validation, adding/removing the last
key without settings changes, keyless construction, model availability,
and Bedrock regressions.

Generated by Coder Agents on behalf of @johnstcn and @Shelnutt2

Co-authored-by: Cian Johnston <cian@coder.com>
2026-09-29 09:20:31 +01:00
Paweł Banaszewski ce80607e17 fix: propagate cancellation and aborts in the in-memory transport (#29723)
Fixes cancellation and abort handling in the in-memory transport coderd
uses to call AI Gateway in-process.

Generated by Coder Agents on behalf of @pawbana.
2026-09-28 23:24:39 +02:00
Paweł Banaszewski 382a8763ff chore: move to be shared gateway types and helpers (#29718)
Moves client identification, credential handling, header
processing, and error categorization into shareable packages.

Generated by Coder Agents on behalf of @pawbana.
2026-09-28 09:49:56 +00:00
Michael Suchacz 926e4afc39 fix(coderd/aibridged): ignore empty response body writes (#29728) 2026-09-22 19:02:06 +02:00
Paweł Banaszewski 44eb71f922 chore: move aibridge proxy code and helpers to separate packages (#29573)
Move the stateless AI Gateway router into `aibridge/x/proxy`.
Extract shared routing helpers into `aibridge/routing` and move provider
and recorder helpers to their owning packages. Update callers and tests
without changing behavior.

Generated by Coder Agents.
2026-09-21 12:26:09 +02:00
Paweł Banaszewski c47eb47393 feat: add stateless AI Gateway proxy mode (#29349)
Adds proxy mode to the AI Gateway. No AI provider is supported in this
mode yet.
2026-09-18 16:47:16 +02:00
Cian Johnston 19076beb8d feat: attribute AI Gateway usage to workspaces (#29235)
- Adds nullable `workspace_id` to AI Gateway interceptions without a
foreign key or index.
- Derives direct attribution from strictly parsed server-minted workspace
session-token names, excluding user-created tokens and validating the
embedded owner.
- Derives delegated Coder Agents attribution from the persisted chat
workspace ID.
- Records `workspace_id` through the additive v1.3 gateway protocol and
structured interception logs.
- Exposes attribution in session details through
`interception_attributions`, including tool-less interceptions and null
values for unknown attribution.

Closes AIGOV-637

Generated by Coder Agents.
2026-09-18 15:22:02 +01:00
Paweł Banaszewski 263f2c207e feat: register AI Gateway proxy experiment and share provider helpers (#29347)
- Add `ai-gateway-reverse-proxy` experiment and update generated API
types and documentation. The experiment has no runtime effect yet.
- Extract shared (will be used by next PRs in stack) provider routing
and key-pool enumeration helpers.
- Log unsupported routes at Debug level.
2026-09-17 10:27:48 +02:00
Sas Swart 98bf16098e feat: add a LogRecorder for AI Gateway (#29136)
Write middleware for the Recorder interface that are responsible for the logging and
tracing of all calls to a Recorder.

Simplify existing Recorders by removing logging and tracing that is now
done by the new Decorators.

Ensures consistent logging coverage for the entire interface.
Reduce local code complexity in other implementations of the Recorder.

Given the ensured logging coverage, this allows us to implement the
feature flag to drop persistence of this information to the Coder
control plane database
2026-09-15 17:35:29 +02:00
Yevhenii Shcherbina b405d57638 feat: resolve bedrock inference profiles when a provider is written (#29112)
Follow-up to #28877, which resolved Bedrock application inference
profile (AIP) ARNs while constructing a provider in the gateway. Review
found two consequences of putting an AWS call on that path: a transient
failure dropped the provider from the reloaded snapshot until the next
provider change or restart, and the initial reload blocked `coder
server` startup for up to 30s per AIP-configured provider under an
uncancelable context.

Resolution now happens once, in coderd, when a provider is created or
updated. The result is stored with the provider and travels to the
gateway in the existing provider payload, so the gateway makes no
Bedrock control-plane call at startup, on reload, or on a request.

The resolved identifiers live in the provider's encrypted settings blob
as `resolved_model` and `resolved_small_fast_model`. A table keyed by
ARN was tried and dropped: the server always writes the resolution as
part of the same provider write, so it needs no separate lifecycle,
migration, or clearing rules.

Resolution runs before the write, so a failed lookup rejects the save
and stores nothing. Create resolves its own request, which carries the
complete configuration. Update cannot: a `PATCH` supplies the model
identifiers but inherits credentials from the stored row, so stored +
patch is merged before the transaction to resolve against, then merged
again inside it against the row being written. Both merges take the
model identifiers from the patch, so they cannot disagree, and no AWS
call happens inside a database transaction.

Reporting the failure at save time means an operator learns immediately
that an ARN is wrong, deleted, or that the identity lacks
`bedrock:GetInferenceProfile`, instead of discovering it later through a
Bedrock 400 on adaptive-only models. Providers configured with plain
model IDs store no resolution and make no AWS call, because those
identifiers are already model identities.

Resolution uses the provider's own credential configuration: static
access keys when set, otherwise the AWS default credential chain, and
the role from `role_arn` when configured. An AIP ARN embeds the account
ID, so resolving under a different principal cannot return another
account's profile; it can only fail with a permission error, which
surfaces as a rejected write.

Using an AIP ARN now requires coderd to reach
`bedrock.{region}.amazonaws.com`. Deployments where only the gateway has
AWS egress cannot configure AIP ARNs, and they find out when they save.

<details>
<summary>Implementation plan</summary>

## Goal

Resolve Bedrock AIP ARNs once, when a provider is created or updated,
and persist the result. The gateway reads the resolved model from the
provider payload and makes no AWS call on the boot, reload, or request
paths.

## Identity

coderd resolves for every credential mode. An AIP ARN carries the
account ID, so resolving under a different principal either succeeds
with the same answer or fails with a permission error. The risk is a
false negative, not a wrong answer.

- **Static access keys, with or without `role_arn`.** The settings fully
determine the identity, so coderd reaches the same principal the gateway
will.
- **AWS default credential chain.** coderd resolves under its own
environment, which may legitimately lack `bedrock:GetInferenceProfile`
even where the gateway has it. The save then reports an actionable
message.

## Behavior at write time

1. Skip when neither `model` nor `small_fast_model` is an AIP ARN. This
is the common case and costs nothing.
2. Otherwise resolve both identifiers with a short deadline, before the
provider write.
3. On success, store the resolved identifiers in the same provider write
and publish normally.
4. On failure, surface the AWS error and store nothing. The remedy is to
fix the ARN, configure static access keys, or grant
`bedrock:GetInferenceProfile`.
5. Re-resolve on every save. Bedrock has no `UpdateInferenceProfile`, so
an ARN means one model forever, but re-resolving proves this provider's
own identity can read the profile.

## Gateway

`ResolvedModelWithFallback` and `ResolvedSmallFastModelWithFallback`
return the stored resolution when present and the configured identifier
otherwise. The fallback covers plain model IDs and providers saved
before this change, degrading to pre-#28877 behavior rather than
dropping the provider from the pool.

## Out of scope

- Normalizing directly configured system inference profile ARNs.
- Provisioned throughput and prompt router identifiers.
- Any gateway-side resolution, including a lazy fallback.
- Displaying the resolved model in the UI.

</details>

Relates to https://linear.app/codercom/issue/AIGOV-488

Created by Coder Agents on behalf of @evgeniy-scherbina.
2026-09-11 16:03:44 +00:00
Sas Swart d5e2ca74cd chore: rename recorderTranslation to DRPCRecorder (#29133)
The old name, `recorderTranslation`, did not clarify from what calls
were being translated, nor to what they were being translated. The new
name, `DRPCRecorder`, immediately explains that calls are being recorded
over DRPC.

This was a readability hurdle while trying to investigate touch points
for AIGOV-358.

This is the first step towards implementing either a /dev/null-esque
recorder or a logging recorder as per the requirements in AIGOV-358.
2026-09-09 16:55:45 +02:00
McKayla はな 2a8e390f0c refactor: replace most usage of ptr.Ref with new (#28282) 2026-08-26 11:57:56 -06:00
Cian Johnston 042421694f fix: surface duplicate AI provider hostname as warning, not error (#28208)
Two live `ai_providers` rows can share the same `base_url` hostname.
This is an intended configuration (AIGOV-97): the direct routing path
(`/api/v2/ai-gateway/{name}/...`) routes by provider name and fully
supports it. Only the MITM proxy path (`aibridgeproxyd`) cannot
disambiguate, because its `nameByHost` map is 1:1.

`classifyProviderRow` marked the second provider as
`ProviderStatusError`, which surfaced as a misleading log warning and a
`status=error` Prometheus label. The provider is not actually broken; it
is fully routable via the direct path. The error was only visible in
server logs and Prometheus, not in the API or UI.

This change:

- Extracts `BaseURLHostname` into `coderd/aibridged` and eliminates
three duplicate implementations (proxy classifier, chatprovider, and the
API layer now uses it for status checks).
- Downgrades the proxy classifier from `ProviderStatusError` to a new
`ProviderStatusProxyExcluded` status. The provider is not broken; it is
just not reachable via the MITM proxy path.
- Adds `Status *AIProviderStatus` to `codersdk.AIProvider` with
`Warnings []string`, matching the `WorkspaceProxy` precedent.
- Populates warnings on create, update, GET, and list when a provider's
hostname collides with another enabled provider.
- Adds an integration test proving that a duplicate provider is routable
via the direct path but not via the proxy path.

Refs AIGOV-596

Generated by Coder Agents



https://github.com/user-attachments/assets/bf323837-5121-4d1b-ab19-593f1d32374e
2026-08-24 13:27:22 +01:00
Paweł Banaszewski 63641b98c8 fix: treat a missing serve endpoint as a fatal dial error (#27864)
Adds 404 as a terminal error for establishing DRPC connection.

A standalone AI Gateway pointed at a coderd that does not expose
`/api/v2/ai-gateway/serve` gets a 404, which the connect loop classified
as transient and retried forever. Redialing cannot fix a missing
endpoint.
404 now is treated as terminal handshake failure. `--url` is expected to
point directly at coderd, so a 404 from an intermediary is not
distinguished.

Refs https://linear.app/codercom/issue/AIGOV-320/write-connection-tests

---

Generated with Coder Agents.
2026-08-19 13:19:20 +02:00
Michael Suchacz c8e8b21a88 feat: migrate aibridge injected-MCP proxy to official MCP Go SDK (#28060)
## Stack Context

PR 5 of 6 in a stack that migrates every Coder MCP surface from the
archived `github.com/mark3labs/mcp-go` library to the official
`github.com/modelcontextprotocol/go-sdk` v1.7.0.

Stack: #28056 -> #28057 -> #28058 -> #28059 -> #28060 -> #28061

## Why

The aibridge injected-MCP proxy now owns an official `*mcp.Client`,
`*mcp.StreamableClientTransport`, and `*mcp.ClientSession`.

- The proxy constructor accepts an optional `*http.Client` instead of
mark3labs options; the header-injecting wrapper shallow-copies a
supplied client so its Timeout, Jar, and redirect policy survive.
- Manual protocol version negotiation and the mark3labs five-second
close workaround are removed; the SDK negotiates during `Connect` and
fails when no mutually supported version exists.
- Repeated `Init` closes the previous session, and a failed tool fetch
closes the just-created session so transports do not leak.
- Tool and intercept types use the official pointer content types;
embedded resource blobs are re-encoded to base64 for model-facing text
because the SDK decodes them into raw bytes.
- `aibridge/mcpmock` is regenerated, and its stale `go:generate` source
path is corrected.

> Mux created this PR on Mike's behalf.
2026-08-13 10:38:14 +00:00
Paweł Banaszewski 8f5f15a92f fix: remove unbound Client() method from aibridged.Server (#27845)
Adds client context to `Client()` method in `aibridged.Server`,
effectivly renaming `ClientContext()` method as `Client()`.
Similarly `aibridged.ClientFuncWithContext` became
`aibridged.ClientFunc`.

`aibridged.Server.Client()` acquired a DRPC client with
`context.Background()`, callers in theory could wait indefinitely for
the daemon to connect to coderd.

Every call site already had a context except the recorder callback.
`aibridge.NewRecorder` takes a `func(context.Context) (Recorder, error)`
and acquires against the record call's context.
2026-08-04 16:57:16 +02:00
Paweł Banaszewski c9e68987c1 fix(coderd/aibridged): retain dialer notification (#27529)
Fixes flake caused by race in `TestReady/FalseBeforeConnection` test.
2026-07-27 17:43:59 +02:00
Yevhenii Shcherbina 63ec93a7ce feat: add AWS Bedrock mantle endpoint to AI Gateway (#26745)
Implements
https://linear.app/codercom/issue/AIGOV-213/add-bedrock-provider

# AWS Bedrock mantle support in AI Gateway

## Summary

Add support for the AWS Bedrock **mantle** endpoint
(`bedrock-mantle.{region}.api.aws/anthropic/v1/messages`) to AI Gateway.
Mantle serves Claude through the native Anthropic Messages API. We model
it as a `protocol` field on the existing Bedrock provider settings
(`invoke-model` default, or `mantle`) rather than as a new provider
type, and we treat mantle as a pure passthrough: SigV4-sign and forward,
no body translation.

## Background

Claude on AWS Bedrock is reachable through two endpoints, each speaking
exactly one wire protocol:

1. **InvokeModel** (existing): `bedrock-runtime.{region}.amazonaws.com`.
Model id in the URL path, request translated into Bedrock's InvokeModel
format, responses returned as a binary AWS eventstream. This is what AI
Gateway already supported for Bedrock.
2. **Mantle** (this doc):
`bedrock-mantle.{region}.api.aws/anthropic/v1/messages`. Native
Anthropic Messages API: model in the body, plain SSE streaming.

## Why a `protocol` field, not a new provider type

The alternative is to model mantle as its own `ai_provider_type`
(`bedrock-mantle`) alongside `bedrock`. I chose the `protocol` field
instead for two reasons:

1. Mantle reads more like a protocol of Bedrock than a separate
provider. It is the same AWS account, credentials, region, and IAM,
reached over a different wire protocol and host. One Bedrock provider
with two protocols (`invoke-model` default and `mantle`) models that
more organically than two provider types.
2. It avoids a database migration. The `protocol` field lives in the
settings JSON blob (empty resolves to `invoke-model`, so existing
providers are unaffected), whereas a new type means an enum value and
the `ALTER TYPE ... ADD VALUE` migration that goes with it.

## Why passthrough, not translation

The client already emits Bedrock-legal requests in mantle mode:

```sh
export CLAUDE_CODE_USE_MANTLE=1
export CLAUDE_CODE_SKIP_MANTLE_AUTH=1
export ANTHROPIC_BEDROCK_MANTLE_BASE_URL=https://<coder>/api/v2/aibridge/<provider-name>
```

So the gateway just forwards the body and SigV4-signs it (service
`bedrock-mantle`), and skips all the InvokeModel body-translation (model
remap, thinking conversion, beta-flag allowlist, field stripping). This
keeps the mantle path thin and avoids a second copy of translation logic
to maintain.

## Consequences

- Protocol-dependent fields: `model` / `small_fast_model` are used by
InvokeModel but ignored by mantle (the client sends the model), and
`base_url` is required for mantle but optional for InvokeModel.
Validation is protocol-aware.
- No central model control on mantle: because it is a passthrough, the
operator cannot pin the model.
- `region` and the `base_url` host must name the same region (the SigV4
scope must match the endpoint); a mismatch surfaces as `Credential
should be scoped to a valid region`.

## Draft UI

<img width="1100" height="579" alt="image"
src="https://github.com/user-attachments/assets/37bab46d-8958-4a96-9f47-1fef3493e1b6"
/>

## Follow-up PRs:
- https://github.com/coder/coder/pull/27156
2026-07-13 19:44:36 -04:00
Susana Ferreira 6580cdcf7f refactor: use AI budget period from deployment config (#27117)
## Description

Read the AI budget period from the deployment config on both the RPC server and the `/users/{user}/ai/spend` endpoint, instead of hardcoding `month`. Drops the `period_start` RPC parameter that was incorrectly introduced in #26915: the period should have been derived from the deployment config from the start.

## Changes

- Add `codersdk.NewAIBudgetPeriodFromString`, mirroring `NewAIBudgetPolicyFromString`.
- `aibridgedserver.Server` takes a `quartz.Clock`, reads `BudgetPeriod` from the deployment config at construction, and computes the period window inside `IsBudgetExceeded`.
- Remove `period_start` from `IsBudgetExceededRequest` and stop sending it from the daemon.
- The `userAISpendStatus` endpoint reads the period from `AIBridgeConfig.BudgetPeriod` instead of hardcoding month.

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by @ssncferreira
2026-07-13 17:52:45 +01:00
Danny Kopping ef0b5585d5 feat: record and expose terminal upstream interception errors (#26961)
Categorises the terminal error of a failed interception and persists it
on the interception record, then surfaces it on the AI Gateway API.

- Categorise into an enum (`bad_request`, `unauthorized`,
  `rate_limited`, `overloaded`, `server_error`, `unknown`), unwrapping
  the ResponseError envelope, the upstream Anthropic/OpenAI SDK errors,
  and key-pool exhaustion so blocking and streaming paths agree.
- Thread the type and raw message through the recorder dRPC into the
  `aibridge_interceptions` row (optional proto fields; NULL on success).
- Expose the error on the AI Gateway thread API from the root
  interception.

*This PR was produced by opencode (agent) using the `anthropic/claude-opus-4-8` model, under human direction and review.*
2026-07-09 15:36:56 +02:00
Danny Kopping affb359d13 feat: synchronise provider changes with WatchAIProviders (#27091)
## Why

PR #26797 was accidentally merged into the stale `graphite-base/26797`
branch instead of `main` (Graphite picked the wrong base), so its
changes never landed on `main`. This PR re-lands that work as a clean
cherry-pick onto the current `main`.

## What

Adds a `WatchAIProviders` streaming RPC to the `ProviderConfigurator`
service so a running standalone AI Gateway refetches its provider set
when the provider configuration changes. The server subscribes to
`AIProvidersChangedChannel` (published by the provider CRUD endpoints)
and forwards each event as a payload-free signal, plus one signal on
subscribe; the gateway calls `GetAIProviders` on each signal to rebuild
its pool. The aibridged API is bumped to v1.2.

Env-seeded providers don't need a signal: seeding finishes before coderd
serves the gateway connection, so the gateway's initial fetch already
reflects the seeded set.

## For reviewers

The change is split into two commits to make review easy:

1. **`feat: synchronise provider changes with WatchAIProviders`** is a
faithful cherry-pick of #26797, identical to the originally reviewed PR.
It is committed without pre-commit hooks because it does not build
against current `main` on its own.
2. **`fix: resolve cherry-pick conflicts against main`** contains only
the deltas needed to re-land on current `main`, and passes the full
pre-commit suite:
- `coderd/aibridged/proto/aibridged.pb.go` regenerated via the proto
make target (the cherry-picked copy was generated against the older
proto).
- `enterprise/cli/aigatewaystart.go` import block unioned; `main` added
`os` and `strings` while the PR added `sync`.
- Three `aibridgedserver.NewServer` test call sites that landed on
`main` after the original branch diverged now pass the new `pubsub`
argument.

Refs https://linear.app/codercom/issue/AIGOV-465

*This PR was produced by opencode (agent) using the
`anthropic/claude-opus-4-8` model, under human direction and review.*
2026-07-08 15:32:17 +02:00
Paweł Banaszewski 60d0859bde feat: add /healtz and /readyz endpoints to standalone Gateway (#26988)
Adds `/healthz` and `/readyz` endpoints to standalone AI Gateway.
* `/healthz`: returns 200 once the AI Gateways HTTP server is listening.
* `/readyz`: returns 200 when the DRPC connection to `coderd` is
established.

Cleanup:
Removed `initConnection*` fields from `aibridged.Server` as they where
not used anywhere.
2026-07-08 09:28:02 +00:00
Paweł BanaszewskiandDanny Kopping ccba3969ab feat: add ai-gateway start command (#26605)
> AI Tools were used to produce this PR

This PR adds `coder ai-gateway start` command that runs the AI Gateway
as an independent process.

- Standalone process doesn't have access to DB. Uses DRPC services under
`/api/v2/ai-gateway/serve`for auth, recording and provider
initialization.
- It only handles LLM traffic, other endpoints (eg. `/sessions`) are
only available though `coderd`.
- The standalone gateway reuses applicable flags from AI Gateway
deployment options. Provider-seeding and coderd-only options are
excluded.
- Only added to fat build, the slim build stub rejects the command.

Some wiring used by this new command is added.

**`NewWebsocketDialer`** - implements the standalone gateway's
connection to coderd's `/api/v2/ai-gateway/serve` endpoint. It upgrades
to a WebSocket, multiplexes with yamux, and wires all DRPC services.

**`AIGatewayDataPlaneMiddleware`** - extracts the per-request middleware
chain (concurrency limiting, rate limiting, BYOK gating) into a shared
function used by both the embedded route and the standalone gateway.

**`RootCmd.ResolveClientConnection`** - resolve the deployment URL and
builds an HTTP transport without requiring a session token. Used in
`ai-gateway start`command as it authenticates using different credential
type.

---------

Co-authored-by: Danny Kopping <danny@coder.com>
2026-07-08 11:12:53 +02:00
Susana Ferreira 64ca5ac9f8 refactor(coderd): add budget.CurrentPeriod for [start, end) windows (#26972)
## Description

Extracts the AI budget period computation into a shared
`budget.CurrentPeriod` helper. Pure refactor with no wire-value changes.

## Changes

- Add `budget.CurrentPeriod(now, period)` returning a
`PeriodWindow{Start, End}` in UTC. Unknown periods return an error,
matching the pattern used by `ResolveUserAIBudget` for unknown policies.
- Update the callers and respective tests to use `CurrentPeriod`.

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by
@ssncferreira
2026-07-06 10:37:27 +01:00
Danny Kopping dd216b96fe feat: record provider_item_id for tool usage (#26856)
## Summary

Plumbs the Responses output item id (added as `ToolUsageRecord.ItemID` in #26855) through to the database, captured independently of the `provider_tool_call_id` correlation key. Hosted tools (`web_search_call`, etc.) only have an item id; agentic tools have both.

`provider_item_id` is specific to the OpenAI Responses API; it stays empty for chat completions and Anthropic messages, which have no separate item id.

## Changes

- Migration `000534`: nullable `provider_item_id` column on `aibridge_tool_usages`.
- Proto: `item_id` field 11 on `RecordToolUsageRequest`.
- Server handler: persists `provider_item_id` and adds it to structured logging.
- Translator: maps `ToolUsageRecord.ItemID` to the proto field.

## Tests

- `TestRecordToolUsageProviderItemID`: real-database round-trip asserting `provider_item_id` persists for both hosted and agentic tools, independently of `provider_tool_call_id`.

Stacked on #26855. Linear: AIGOV-96

---

_This PR was produced by opencode (agent) using the_ _`anthropic/claude-opus-4-8`_ _model, under human direction and review._
2026-07-06 09:29:07 +02:00
Susana Ferreira 1989db0e2b feat(coderd): enforce ai budget on pre-request path (#26915)
## Description

Adds pre-request AI budget enforcement to `aibridged`. Requests are rejected with HTTP 403 when the user's aggregated spend for the current period has reached their effective limit.

## Changes

- Add `IsBudgetExceeded` RPC to `aibridgedserver`. Resolves the user's effective budget, aggregates spend over the caller-supplied `[period_start, now]` window, and returns whether the limit has been reached along with the effective limit.
- Wire the check into `aibridged`'s HTTP handler. The caller computes the period start (monthly for now) and passes it in the request.
- Reject exceeded requests with HTTP 403 Forbidden and a message directing the user to contact an administrator.
- Add `dbtime.StartOfMonth` alongside `StartOfDay` for period computation.
- Add real-DB tests covering the enforcement path: month-boundary excludes prior-period spend, and a new user override unblocks a previously-exceeded user.

Closes https://linear.app/codercom/issue/AIGOV-428/add-pre-request-budget-enforcement

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by @ssncferreira
2026-07-02 16:53:36 +01:00
Yevhenii Shcherbina db7f4438b4 feat: generate STS external ID for Bedrock role assumption (#26869)
Implements:
https://linear.app/codercom/issue/AIGOV-495/add-externalid-to-prevent-confused-deputy-problem

When a Bedrock provider assumes an IAM role via STS, the gateway now
generates a unique external ID for it and sends that value on every
`AssumeRole` call. The external ID guards against the [confused deputy
problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html)
on cross-account role assumption. Per [AWS's
recommendation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html),
the gateway generates and owns the value rather than accepting one from
the operator; that ownership is what makes it effective, since a party
who knows another's external ID can't induce the gateway to send it.

The external ID is server-owned and read-only over the API. It is
generated once, when a provider first has a `role_arn`, and is stable
thereafter. Clients cannot set it: create rejects any supplied
`external_id`, and update rejects a value that differs from the stored
one. An update may echo the stored value back unchanged, so the normal
read-modify-write flow (GET the provider, change a field, PATCH the full
settings object) keeps working. The value is not a secret and is
returned on GET so operators can copy it into the target role's trust
policy as an `sts:ExternalId` condition.

It is persisted in the existing JSON settings blob, so there is no
migration or audit-table change.
2026-07-01 20:44:15 +00:00
Sas Swart d179266cc7 feat: capture, persist, and strip Agent Firewall correlation headers in AI Bridge (#26529)
Wire the Agent Firewall correlation headers
(`X-Coder-Agent-Firewall-Session-Id` and
`X-Coder-Agent-Firewall-Sequence-Number`) through the AI Bridge
interception processor so that each interception is linked to its
originating firewall session.

Closes https://linear.app/codercom/issue/AIGOV-259

> Generated by Coder Agents on behalf of @SasSwart

**Data flow:**
`request header` → `bridge.go` reads + strips → `InterceptionRecord` →
`translator.go` → proto `RecordInterceptionRequest` →
`aibridgedserver.go` → DB
2026-06-30 14:01:27 +02:00
Danny Kopping ce94d42e19 feat: fetch providers over DRPC (#26650)
Closes [AIGOV-455](https://linear.app/codercom/issue/AIGOV-455/extend-drpc-with-buildproviders).

## Why

The AI Gateway (`aibridged`) is being split into a standalone process that must not touch the database. `coderd` stays the source of truth and seeds the `ai_providers` / `ai_provider_keys` tables from the environment. This PR adds a DRPC call so the gateway fetches provider config from `coderd` instead of reading the DB, for both the embedded and standalone daemons.

## What

- **Proto:** new `ProviderConfigurator` service with a unary `GetAIProviders` RPC, plus `AIProvider` / `AIProviderBedrock` messages. `CurrentMinor` bumped to 1 (additive).
- **Server (`coderd/aibridgedserver`):** `GetAIProviders` runs a read-only `InTx` under `LockIDAIProvidersEnvSeed` so it never returns a mid-seed snapshot, reads providers (incl. disabled) plus keys for enabled ones, and maps to proto under `dbauthz.AsAIBridged`. Unmappable rows are skipped and logged; plaintext keys and Bedrock secrets are never logged.
- **Client:** `DRPCProviderConfiguratorClient` wired into the client union, `dialer.go`, and `CreateInMemoryAIBridgeServer`.
- **cli:** `BuildProvidersFromProto` maps the response through the existing DB-neutral `buildProvider`. A shared `poolRPCReloader` does the fetch/build/replace for both daemons: the embedded daemon reloads on every `ai_providers` change and fails startup if it cannot subscribe; the standalone gateway drives the same reloader once at startup, retrying until success and staying interruptible.
- **Dead code removed:** `BuildProvidersFromConfig`, `ProvidersFromConfig`, `AIProviderFromConfig`, and the DB-read `BuildProviders` path.
2026-06-29 13:34:58 +02:00
Cian Johnston 5942cec329 fix: synchronize bridge and pool shutdown with in-flight requests (#26743)
When adding chatd tests to route through a real in-process `aibridged`
daemon (#26658), found two races:

- **Pool:** `CachedBridgePool.Shutdown` calls `cache.Close()` while an
in-flight `Acquire` runs `cache.Wait()`. ristretto closes the channel
`Wait` sends on.
- **Bridge:** `RequestBridge.ServeHTTP` does `inflightWG.Add(1)` after
the `b.closed` check, racing `Shutdown`'s `inflightWG.Wait()`.

## Fix

- `RequestBridge`: adds `admitMu` RWMutex to order `inflightWG.Add`
(ServeHTTP, read) before `close(b.closed)` (Shutdown, write).
- `CachedBridgePool`: adds `opsMu` + `opsWG` so `Shutdown` drains
in-flight `Acquire`/`ReplaceProviders` before `cache.Close()`
- Adds tests `TestRequestBridgeShutdownAdmissionRace` and
`TestPoolShutdownReplaceProviders` for above. (Note:
`TestRequestBridgeShutdownAdmissionRace` leverages a `serve_admission`
quartz trap added to `RequestBridge`).

---

> 🤖 Created by Coder Agents on behalf of @johnstcn.
2026-06-29 11:33:21 +01:00
Paweł Banaszewski 6189d6e386 feat: add /api/v2/aibridge/serve endpoint (#26506)
Adds a new enterprise-only `GET /api/v2/ai-gateway/serve` endpoint that standalone AI Gateway replicas use to connect to `coderd` over a DRPC-over-WebSocket transport, mirroring the existing in-memory path used by the embedded AI Bridge daemon.

- The endpoint upgrades the HTTP connection to a WebSocket, multiplexes it with yamux, and finally serves the three DRPC services (Recorder, MCPConfigurator, Authorizer).
- The `X-AI-Governance-Gateway-Key` header is used for authentication.
    - The key is looked up by its hashed secret
    - Missing or revoked keys return `401`.
- API version negotiation is enforced via a new `aibridged/proto` version (`v1.0`).
    - Incompatible versions return `400`.
- `FeatureAIBridge` entitlement is required.
- Key liveness (`last_used_at`) is recorded immediately on connection and refreshed every 60 seconds while the session remains open.
  - When key liveness detects the key was deleted (no rows where updated) session is closed.

#### Small refactors

* The three DRPC service registrations are extracted into `aibridgedserver.Register`, shared by both the in-memory and WebSocket paths.

* The literal `256 * 1024` used as the yamux-aligned WebSocket read limit is replaced with the named constant `drpcsdk.YamuxDefaultStreamWindowSize` in all call sites.
  * as noted in review comment https://github.com/coder/coder/pull/26506#discussion_r3461905223 order of `SetReadLimit` and `WebsocketNetConn` calls was fixed.
2026-06-26 18:27:37 +02:00
Yevhenii Shcherbina 8bf6f43016 feat: support cross-account Bedrock AssumeRole in AI Bridge (#26527)
# Support IAM role assumption for AWS Bedrock in AI Bridge

## Summary

Implements
https://linear.app/codercom/issue/AIGOV-371/support-dynamic-bedrock-assumerole-across-aws-accounts-for-ai-gateway

A Bedrock provider can now be configured with an IAM role to assume.
Before calling Bedrock, the gateway assumes that role via STS and signs
requests with the resulting temporary credentials. Whether the role
lives in the same account or another one is entirely a matter of the
role's trust policy.

## Problem

Many organizations prohibit long-lived AWS access keys and expect
workloads to authenticate through assumed IAM roles instead. A common
case is an organization that runs Bedrock across several AWS accounts,
one per business unit, and needs each unit's usage billed to its own
account by assuming a role there. AI Bridge previously authenticated a
Bedrock provider only with static keys or the gateway's own ambient AWS
identity, which is shared by every provider, with no way to assume a
role. These deployments had no clean path.

## How it works

When a provider is configured with a role ARN, the gateway uses its base
identity to assume that role via STS and signs Bedrock requests with the
temporary credentials it returns. The base identity is whatever the AWS
default credential chain resolves, IRSA, EKS Pod Identity, EC2 Instance
Profile, or static keys.

Credentials are resolved once when the provider is set up and are then
cached and rotated, so individual requests are served from the cache
rather than triggering a new STS call. A deployment that needs several
roles configures several providers, each pointing at its own role.

## Configuration

The role ARN is part of the Bedrock provider settings and is set through
the AI provider API. It is optional: a provider with no role ARN behaves
exactly as before.

## Scope and trade-offs

- This PR is backend only. The settings UI for the role ARN ships in a
follow-up.
- Configuration is not exposed through environment variables.
Environment-based provider configuration is being phased out in favor of
database-managed providers, so the role ARN is intentionally database
and API only.

Follow-up PR: https://github.com/coder/coder/pull/26578
2026-06-24 12:03:27 -04:00