Files
coder/coderd/workspaceupdates.go
Mathias Fredriksson 856a8684cb fix: prevent channel shutdown send races (#29658)
Workspace update subscriptions and VPN tunnels could close a channel
while another goroutine was still sending on it, panicking with `send on
closed channel`. VPN senders could also block forever once nothing read
the channel.

- `coderd`: `sub.Close` no longer closes the updates channel, so a
pubsub callback still running cannot send on a closed channel.
- `vpn`: after Stop, the tunnel no longer closes the shared send
channel. The writer exits after writing the Stop response, so Stop is
the final frame, and its exit is what ends the senders below.
- `vpn`: a speaker send context ends when the speaker is canceled or the
writer exits, for example on a write error. RPCs, RPC replies, updates
and logs wait on it, so they return instead of blocking on a channel
nothing reads. Before, an update holding the updater mutex could block a
Stop the tunnel had already read. The updater context derives from it,
so the updater also stops after Stop when Start never succeeded.
- `vpn`: RPC response channels are buffered, so delivering a response no
longer deadlocks against a caller canceled at the same moment. That
deadlock exists on main for a canceled caller context, and the send
context adds a cancellation at shutdown. A response received before EOF
or writer exit is returned instead of an error.

<details>
<summary>Decisions and regression evidence</summary>

- Nothing observes the subscription channel closing: its only reader,
`WorkspaceUpdates` in `tailnet/service.go`, also stops on its stream
context and calls `Close` itself.
- The tunnel does not cancel its speaker after Stop. Senders return once
the writer has finished the Stop response rather than when it is handed
over, and a request the manager sends after Stop stays parked until
`Tunnel.Close`, as on main.
- `updater.stop` is unchanged: it cancels after closing the conn, so
logs the conn emits while closing reach the manager (the tunnel is the
only log sink with `UseAsLogger` on macOS).
`TestTunnel_StopForwardsCloseLogs` guards that ordering.
- RPCs wait on the send context directly instead of relying on
`recvLoopDone`. The receive loop cannot exit while it is handing a
request to a busy `requestLoop`, and closing a blocking file descriptor
may not interrupt its read. `recvFromSerdes` still delivers requests
after the writer exits, so a Stop it has already read is not dropped.
When only the writer has exited, RPCs return `io.ErrUnexpectedEOF`, as
for EOF. Every RPC return removes its response channel, so RPCs that
fail after the writer exits do not accumulate entries.
- Against main's production code:
- `TestWorkspaceUpdatesClose/{QueryInFlight,CallbackAfterClose}` and
`TestTunnel_StopConcurrentSenders` panic with `send on closed channel`.
  - `TestSpeaker_ResponseDuringCancellation` deadlocks.
  - `TestSerdes_StopClosesAfterResponse` receives a frame after Stop.
- `TestTunnel_StopAfterWriterExits` and
`TestSpeaker_RPCAfterWriterExits` stay blocked after the writer exits.
- `TestSpeaker_ResponseBeforeEOF`,
`TestSpeaker_ResponseBeforeWriterExits` and
`TestTunnel_StopForwardsCloseLogs` pass on main. They guard ordering the
fix depends on: each fails when that ordering is changed or the matching
part of the fix is removed.
- The regression tests pass 50 runs with `-race`. The `vpn` and
`tailnet` race suites pass.

</details>

> This PR was created with the help of Coder Agents for @mafredri and
will be reviewed by a human.
2026-11-26 10:53:41 +02:00

332 lines
8.9 KiB
Go

package coderd
import (
"context"
"fmt"
"sync"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/pubsub"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/coderd/wspubsub"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/tailnet"
"github.com/coder/coder/v2/tailnet/proto"
)
type UpdatesQuerier interface {
// GetAuthorizedWorkspacesAndAgentsByOwnerID requires a context with an actor set
GetWorkspacesAndAgentsByOwnerID(ctx context.Context, ownerID uuid.UUID) ([]database.GetWorkspacesAndAgentsByOwnerIDRow, error)
GetWorkspaceByAgentID(ctx context.Context, agentID uuid.UUID) (database.Workspace, error)
}
type workspacesByID = map[uuid.UUID]ownedWorkspace
type ownedWorkspace struct {
WorkspaceName string
Status proto.Workspace_Status
Agents []database.AgentIDNamePair
}
// Equal does not compare agents
func (w ownedWorkspace) Equal(other ownedWorkspace) bool {
return w.WorkspaceName == other.WorkspaceName &&
w.Status == other.Status
}
type sub struct {
// ALways contains an actor
ctx context.Context
cancelFn context.CancelFunc
mu sync.RWMutex
userID uuid.UUID
ch chan *proto.WorkspaceUpdate
prev workspacesByID
db UpdatesQuerier
ps pubsub.Pubsub
logger slog.Logger
psCancelFn func()
}
func (s *sub) handleEvent(ctx context.Context, event wspubsub.WorkspaceEvent, err error) {
s.mu.Lock()
defer s.mu.Unlock()
switch event.Kind {
case wspubsub.WorkspaceEventKindStateChange:
case wspubsub.WorkspaceEventKindAgentConnectionUpdate:
case wspubsub.WorkspaceEventKindAgentTimeout:
case wspubsub.WorkspaceEventKindAgentLifecycleUpdate:
default:
if err == nil {
return
}
// Always attempt an update if the pubsub lost connection
s.logger.Warn(ctx, "failed to handle workspace event", slog.Error(err))
}
// Use context containing actor
rows, err := s.db.GetWorkspacesAndAgentsByOwnerID(s.ctx, s.userID)
if err != nil {
s.logger.Warn(ctx, "failed to get workspaces and agents by owner ID", slog.Error(err))
return
}
latest := convertRows(rows)
out, updated := produceUpdate(s.prev, latest)
if !updated {
return
}
s.prev = latest
select {
case <-s.ctx.Done():
return
case s.ch <- out:
}
}
func (s *sub) start(ctx context.Context) (err error) {
rows, err := s.db.GetWorkspacesAndAgentsByOwnerID(ctx, s.userID)
if err != nil {
return xerrors.Errorf("get workspaces and agents by owner ID: %w", err)
}
latest := convertRows(rows)
initUpdate, _ := produceUpdate(workspacesByID{}, latest)
s.ch <- initUpdate
s.prev = latest
cancel, err := s.ps.SubscribeWithErr(wspubsub.WorkspaceEventChannel(s.userID), wspubsub.HandleWorkspaceEvent(s.handleEvent))
if err != nil {
return xerrors.Errorf("subscribe to workspace event channel: %w", err)
}
s.psCancelFn = cancel
return nil
}
func (s *sub) Close() error {
s.cancelFn()
if s.psCancelFn != nil {
s.psCancelFn()
}
// Do not close ch: pubsub may still be running a callback that sends on
// it. Readers stop on their own context.
return nil
}
func (s *sub) Updates() <-chan *proto.WorkspaceUpdate {
return s.ch
}
var _ tailnet.Subscription = (*sub)(nil)
type updatesProvider struct {
ps pubsub.Pubsub
logger slog.Logger
db UpdatesQuerier
auth rbac.Authorizer
ctx context.Context
cancelFn func()
}
var _ tailnet.WorkspaceUpdatesProvider = (*updatesProvider)(nil)
func NewUpdatesProvider(
logger slog.Logger,
ps pubsub.Pubsub,
db UpdatesQuerier,
auth rbac.Authorizer,
) tailnet.WorkspaceUpdatesProvider {
ctx, cancel := context.WithCancel(context.Background())
out := &updatesProvider{
auth: auth,
db: db,
ps: ps,
logger: logger,
ctx: ctx,
cancelFn: cancel,
}
return out
}
func (u *updatesProvider) Close() error {
u.cancelFn()
return nil
}
// Subscribe subscribes to workspace updates for a user, for the workspaces
// that user is authorized to `ActionRead` on. The provided context must have
// a dbauthz actor set.
func (u *updatesProvider) Subscribe(ctx context.Context, userID uuid.UUID) (tailnet.Subscription, error) {
actor, ok := dbauthz.ActorFromContext(ctx)
if !ok {
return nil, xerrors.Errorf("actor not found in context")
}
ctx, cancel := context.WithCancel(u.ctx)
ctx = dbauthz.As(ctx, actor)
ch := make(chan *proto.WorkspaceUpdate, 1)
sub := &sub{
ctx: ctx,
cancelFn: cancel,
userID: userID,
ch: ch,
db: u.db,
ps: u.ps,
logger: u.logger.Named(fmt.Sprintf("workspace_updates_subscriber_%s", userID)),
prev: workspacesByID{},
}
err := sub.start(ctx)
if err != nil {
_ = sub.Close()
return nil, err
}
return sub, nil
}
func produceUpdate(oldWS, newWS workspacesByID) (out *proto.WorkspaceUpdate, updated bool) {
out = &proto.WorkspaceUpdate{
UpsertedWorkspaces: []*proto.Workspace{},
UpsertedAgents: []*proto.Agent{},
DeletedWorkspaces: []*proto.Workspace{},
DeletedAgents: []*proto.Agent{},
}
for wsID, newWorkspace := range newWS {
oldWorkspace, exists := oldWS[wsID]
// Upsert both workspace and agents if the workspace is new
if !exists {
out.UpsertedWorkspaces = append(out.UpsertedWorkspaces, &proto.Workspace{
Id: tailnet.UUIDToByteSlice(wsID),
Name: newWorkspace.WorkspaceName,
Status: newWorkspace.Status,
})
for _, agent := range newWorkspace.Agents {
out.UpsertedAgents = append(out.UpsertedAgents, &proto.Agent{
Id: tailnet.UUIDToByteSlice(agent.ID),
Name: agent.Name,
WorkspaceId: tailnet.UUIDToByteSlice(wsID),
})
}
updated = true
continue
}
// Upsert workspace if the workspace is updated
if !newWorkspace.Equal(oldWorkspace) {
out.UpsertedWorkspaces = append(out.UpsertedWorkspaces, &proto.Workspace{
Id: tailnet.UUIDToByteSlice(wsID),
Name: newWorkspace.WorkspaceName,
Status: newWorkspace.Status,
})
updated = true
}
add, remove := slice.SymmetricDifference(oldWorkspace.Agents, newWorkspace.Agents)
for _, agent := range add {
out.UpsertedAgents = append(out.UpsertedAgents, &proto.Agent{
Id: tailnet.UUIDToByteSlice(agent.ID),
Name: agent.Name,
WorkspaceId: tailnet.UUIDToByteSlice(wsID),
})
updated = true
}
for _, agent := range remove {
out.DeletedAgents = append(out.DeletedAgents, &proto.Agent{
Id: tailnet.UUIDToByteSlice(agent.ID),
Name: agent.Name,
WorkspaceId: tailnet.UUIDToByteSlice(wsID),
})
updated = true
}
}
// Delete workspace and agents if the workspace is deleted
for wsID, oldWorkspace := range oldWS {
if _, exists := newWS[wsID]; !exists {
out.DeletedWorkspaces = append(out.DeletedWorkspaces, &proto.Workspace{
Id: tailnet.UUIDToByteSlice(wsID),
Name: oldWorkspace.WorkspaceName,
Status: oldWorkspace.Status,
})
for _, agent := range oldWorkspace.Agents {
out.DeletedAgents = append(out.DeletedAgents, &proto.Agent{
Id: tailnet.UUIDToByteSlice(agent.ID),
Name: agent.Name,
WorkspaceId: tailnet.UUIDToByteSlice(wsID),
})
}
updated = true
}
}
return out, updated
}
func convertRows(rows []database.GetWorkspacesAndAgentsByOwnerIDRow) workspacesByID {
out := workspacesByID{}
for _, row := range rows {
agents := []database.AgentIDNamePair{}
for _, agent := range row.Agents {
agents = append(agents, database.AgentIDNamePair{
ID: agent.ID,
Name: agent.Name,
})
}
out[row.ID] = ownedWorkspace{
WorkspaceName: row.Name,
Status: tailnet.WorkspaceStatusToProto(codersdk.ConvertWorkspaceStatus(codersdk.ProvisionerJobStatus(row.JobStatus), codersdk.WorkspaceTransition(row.Transition))),
Agents: agents,
}
}
return out
}
// tunnelQuerier reads the workspace and template behind an agent so a tunnel
// request to it can be authorized.
type tunnelQuerier interface {
GetWorkspaceByAgentID(ctx context.Context, agentID uuid.UUID) (database.Workspace, error)
templateQuerier
}
type rbacAuthorizer struct {
sshPrep rbac.PreparedAuthorized
db tunnelQuerier
}
func (r *rbacAuthorizer) AuthorizeTunnel(ctx context.Context, agentID uuid.UUID) error {
ws, err := r.db.GetWorkspaceByAgentID(ctx, agentID)
if err != nil {
return xerrors.Errorf("get workspace by agent ID: %w", err)
}
// Authorizes against `ActionSSH`
if err := r.sshPrep.Authorize(ctx, ws.RBACObject()); err != nil {
return err
}
// The user-scoped tailnet endpoint spans templates, so unlike the
// deployment-wide setting this can only be refused per tunnel.
browserOnly, err := templateRefusesNonBrowserConnections(ctx, r.db, ws.TemplateID)
if err != nil {
return err
}
if browserOnly {
return tailnet.TunnelPolicyError{Message: browserOnlyTemplateMessage}
}
return nil
}
var _ tailnet.TunnelAuthorizer = (*rbacAuthorizer)(nil)