Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions coderd/apidoc/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions coderd/apidoc/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion coderd/database/dump.sql

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- The 'tunnel' enum value is intentionally not removed. Postgres cannot
-- drop an enum value in place; removing it would require recreating
-- connection_type and rewriting the connection_logs type column, which
-- takes an exclusive lock on the table and would have to DELETE all
-- tunnel rows (audit data) because they cannot exist in the old type.
-- Leaving the value in place is harmless: old code never queries for it
-- and renders unknown types without error. This matches the precedent
-- of other enum-value additions (e.g. 000517, 000531).
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TYPE connection_type ADD VALUE IF NOT EXISTS 'tunnel';
5 changes: 4 additions & 1 deletion coderd/database/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 27 additions & 6 deletions coderd/database/querier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3997,6 +3997,20 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
UserID: uuid.NullUUID{UUID: user3.ID, Valid: true},
})

// Tunnel events are point-in-time (no disconnect event is ever
// reported), so despite having a NULL disconnect_time they must be
// excluded from both status filters.
log5 := dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Time: now.Add(-30 * time.Minute),
OrganizationID: ws1.OrganizationID,
WorkspaceOwnerID: ws1.OwnerID,
WorkspaceID: ws1.ID,
WorkspaceName: ws1.Name,
Type: database.ConnectionTypeTunnel,
ConnectionStatus: database.ConnectionStatusConnected,
UserID: uuid.NullUUID{UUID: user1.ID, Valid: true},
})

testCases := []struct {
name string
params database.GetConnectionLogsOffsetParams
Expand All @@ -4006,7 +4020,7 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
name: "NoFilter",
params: database.GetConnectionLogsOffsetParams{},
expectedLogIDs: []uuid.UUID{
log1.ID, log2.ID, log3.ID, log4.ID,
log1.ID, log2.ID, log3.ID, log4.ID, log5.ID,
},
},
{
Expand All @@ -4021,14 +4035,14 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
params: database.GetConnectionLogsOffsetParams{
WorkspaceOwner: user1.Username,
},
expectedLogIDs: []uuid.UUID{log1.ID, log2.ID},
expectedLogIDs: []uuid.UUID{log1.ID, log2.ID, log5.ID},
},
{
name: "WorkspaceOwnerID",
params: database.GetConnectionLogsOffsetParams{
WorkspaceOwnerID: user1.ID,
},
expectedLogIDs: []uuid.UUID{log1.ID, log2.ID},
expectedLogIDs: []uuid.UUID{log1.ID, log2.ID, log5.ID},
},
{
name: "WorkspaceOwnerEmail",
Expand All @@ -4044,19 +4058,26 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
},
expectedLogIDs: []uuid.UUID{log2.ID, log4.ID},
},
{
name: "TypeTunnel",
params: database.GetConnectionLogsOffsetParams{
Type: string(database.ConnectionTypeTunnel),
},
expectedLogIDs: []uuid.UUID{log5.ID},
},
{
name: "UserID",
params: database.GetConnectionLogsOffsetParams{
UserID: user1.ID,
},
expectedLogIDs: []uuid.UUID{log1.ID},
expectedLogIDs: []uuid.UUID{log1.ID, log5.ID},
},
{
name: "Username",
params: database.GetConnectionLogsOffsetParams{
Username: user1.Username,
},
expectedLogIDs: []uuid.UUID{log1.ID},
expectedLogIDs: []uuid.UUID{log1.ID, log5.ID},
},
{
name: "UserEmail",
Expand All @@ -4070,7 +4091,7 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
params: database.GetConnectionLogsOffsetParams{
ConnectedAfter: now.Add(-90 * time.Minute), // 1.5 hours ago
},
expectedLogIDs: []uuid.UUID{log4.ID},
expectedLogIDs: []uuid.UUID{log4.ID, log5.ID},
},
{
name: "ConnectedBefore",
Expand Down
10 changes: 6 additions & 4 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions coderd/database/queries/connectionlogs.sql
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,9 @@ WHERE
WHEN @status :: text != '' THEN
((@status = 'ongoing' AND disconnect_time IS NULL) OR
(@status = 'completed' AND disconnect_time IS NOT NULL)) AND
-- Exclude web events, since we don't know their close time.
"type" NOT IN ('workspace_app', 'port_forwarding')
-- Exclude point-in-time events reported by coderd, since we
-- don't know their close time.
"type" NOT IN ('workspace_app', 'port_forwarding', 'tunnel')
ELSE true
END
-- Authorize Filter clause will be injected below in
Expand Down Expand Up @@ -230,8 +231,9 @@ SELECT COUNT(*) AS count FROM (
WHEN @status :: text != '' THEN
((@status = 'ongoing' AND disconnect_time IS NULL) OR
(@status = 'completed' AND disconnect_time IS NOT NULL)) AND
-- Exclude web events, since we don't know their close time.
"type" NOT IN ('workspace_app', 'port_forwarding')
-- Exclude point-in-time events reported by coderd, since we
-- don't know their close time.
"type" NOT IN ('workspace_app', 'port_forwarding', 'tunnel')
ELSE true
END
-- Authorize Filter clause will be injected below in
Expand Down
93 changes: 93 additions & 0 deletions coderd/workspaceagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -1367,6 +1367,9 @@ func (api *API) workspaceAgentClientCoordinate(rw http.ResponseWriter, r *http.R
})
return
}

api.logTunnelConnection(ctx, r, waws)

ctx, wsNetConn := codersdk.WebsocketNetConn(ctx, conn, websocket.MessageBinary)
defer wsNetConn.Close()

Expand All @@ -1386,6 +1389,96 @@ func (api *API) workspaceAgentClientCoordinate(rw http.ResponseWriter, r *http.R
}
}

// logTunnelConnection records a connection log entry attributing a
// tunnel to the authenticated user who opened it. Agent-reported rows
// cannot identify the user (see coderd/agentapi/connectionlog.go), and
// workspace-proxy-authenticated requests carry no API key and are
// skipped.
func (api *API) logTunnelConnection(ctx context.Context, r *http.Request, waws database.GetWorkspaceAgentAndWorkspaceByIDRow) {
apiKey, ok := httpmw.APIKeyOptional(r)

@Emyrk Emyrk Jul 28, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked the proxy path: the skip here is correct by design. Proxy-authenticated coordinates (RequireAPIKeyOrWorkspaceProxyAuth) are shared proxy↔agent tunnels carrying many users' traffic, and per-user attribution for proxied activity already happens at the app layer (the wsproxy's workspaceapps provider writes workspace_app/port_forwarding/terminal rows with user identity). Logging them as tunnel rows would just be unattributed noise.

That leaves Coder Desktop / the user-scoped tailnet API as the one real attribution gap — is that tracked as a follow-up?

Coder Agents on behalf of @Emyrk.

if !ok {
return
}
// Bounded so log backpressure cannot stall tunnel establishment.
writeCtx, writeCancel := context.WithTimeout(ctx, 3*time.Second)
defer writeCancel()
userAgent := r.UserAgent()
now := dbtime.Now()

// Clients re-dial automatically, so dedupe reconnects through the
// same audit session mechanism as workspace apps, keyed on
// (agent, user, IP, user agent). Status 101 and the empty slug
// keep tunnel sessions from ever colliding with app or
// port-forwarding sessions.
staleInterval := api.Options.WorkspaceAppAuditSessionTimeout
if staleInterval == 0 {
staleInterval = time.Hour
}
// nolint:gocritic // System context is needed to write audit sessions.
newSession, err := api.Database.UpsertWorkspaceAppAuditSession(dbauthz.AsSystemRestricted(writeCtx), database.UpsertWorkspaceAppAuditSessionParams{
Comment thread
Emyrk marked this conversation as resolved.
// Config.
StaleIntervalMS: staleInterval.Milliseconds(),

// Data.
ID: uuid.New(),
AgentID: waws.WorkspaceAgent.ID,
AppID: uuid.Nil, // Tunnels are not associated with an app.
UserID: apiKey.UserID,
Ip: r.RemoteAddr,
UserAgent: userAgent,
SlugOrPort: "",
StatusCode: http.StatusSwitchingProtocols,
StartedAt: now,
UpdatedAt: now,
})
if err != nil {
// Skip logging rather than risk spamming the connection log.
api.Logger.Error(ctx, "upsert tunnel audit session",
slog.F("workspace_id", waws.WorkspaceTable.ID),
slog.F("user_id", apiKey.UserID),
slog.Error(err),
)
return
}
if !newSession {
// Reconnection of an already-logged session.
return
}

connLogger := *api.ConnectionLogger.Load()
err = connLogger.Upsert(writeCtx, database.UpsertConnectionLogParams{
ID: uuid.New(),
Time: now,
OrganizationID: waws.WorkspaceTable.OrganizationID,
WorkspaceOwnerID: waws.WorkspaceTable.OwnerID,
WorkspaceID: waws.WorkspaceTable.ID,
WorkspaceName: waws.WorkspaceTable.Name,
AgentName: waws.WorkspaceAgent.Name,
Type: database.ConnectionTypeTunnel,
IP: database.ParseIP(r.RemoteAddr),
Code: sql.NullInt32{
Int32: http.StatusSwitchingProtocols,
Valid: true,
},
UserAgent: sql.NullString{String: userAgent, Valid: userAgent != ""},
UserID: uuid.NullUUID{UUID: apiKey.UserID, Valid: true},
// Left unset so each session gets its own row; reusing peerID
// would make resume_token reconnects upsert into a stale row.
ConnectionID: uuid.NullUUID{},
ConnectionStatus: database.ConnectionStatusConnected,
// N/A
SlugOrPort: sql.NullString{},
DisconnectReason: sql.NullString{},
})
if err != nil {
api.Logger.Error(ctx, "upsert tunnel connection log",
slog.F("workspace_id", waws.WorkspaceTable.ID),
slog.F("user_id", apiKey.UserID),
slog.Error(err),
)
}
}

// handleResumeToken accepts a resume_token query parameter to use the same peer ID
func (api *API) handleResumeToken(ctx context.Context, rw http.ResponseWriter, r *http.Request) (peerID uuid.UUID, err error) {
peerID = uuid.New()
Expand Down
Loading
Loading