chore: merge origin/main and renumber the MCP OAuth2 resource migration

Main added migration 000617 (connection_logs_method_app_name), so the MCP
server oauth2_resource migration moves to 000618. Generated files match a
fresh make gen on the merged tree.
This commit is contained in:
Michael Suchacz committed 2026-10-12 14:08:17 +00:00
commit 4b54ffb5f9
62 files changed
+1819 -737

No files matched your search

+1 -1
View File
@@ -1599,7 +1599,7 @@ jobs:
token: ${{ secrets.GITHUB_TOKEN }}
organization: coder
container: coder-preview
keep-younger-than: 7 # days
keep-younger-than: 30 # days
keep-tags: latest
keep-tags-regexes: ^pr
prune-tags-regexes: |
+9 -1
View File
@@ -87,7 +87,8 @@ endif
coderd/rbac/object_gen.go \
coderd/rbac/scopes_constants_gen.go \
codersdk/rbacresources_gen.go \
codersdk/apikey_scopes_gen.go
codersdk/apikey_scopes_gen.go \
codersdk/dbenums_gen.go
# atomic_write runs a command, captures stdout into a temp file, and
# atomically replaces $@. An optional second argument is a formatting
@@ -1099,6 +1100,7 @@ GEN_FILES := \
codersdk/rbacresources_gen.go \
coderd/rbac/scopes_constants_gen.go \
codersdk/apikey_scopes_gen.go \
codersdk/dbenums_gen.go \
docs/admin/integrations/prometheus.md \
docs/reference/cli/index.md \
docs/admin/security/audit-logs.md \
@@ -1201,6 +1203,7 @@ gen/mark-fresh:
codersdk/rbacresources_gen.go \
coderd/rbac/scopes_constants_gen.go \
codersdk/apikey_scopes_gen.go \
codersdk/dbenums_gen.go \
site/src/api/rbacresourcesGenerated.ts \
site/src/api/countriesGenerated.ts \
site/src/api/chatModelOptionsGenerated.json \
@@ -1398,6 +1401,11 @@ codersdk/rbacresources_gen.go: scripts/typegen/codersdk.gotmpl scripts/typegen/m
$(call atomic_write,_gen/bin/typegen rbac codersdk)
touch "$@"
# Reads coderd/database/models.go, which generate.sh writes with querier.go.
codersdk/dbenums_gen.go: scripts/typegen/dbenums.gotmpl scripts/typegen/main.go coderd/database/querier.go | _gen _gen/bin/typegen
$(call atomic_write,_gen/bin/typegen dbenums)
touch "$@"
# NOTE: depends on object_gen.go and scopes_constants_gen.go because
# the generator build compiles coderd/rbac which includes both.
codersdk/apikey_scopes_gen.go: scripts/apikeyscopesgen/main.go coderd/rbac/scopes_catalog.go coderd/rbac/scopes.go \
+1 -1
View File
@@ -85,7 +85,7 @@ func TestExpRpty(t *testing.T) {
stdout.ExpectMatch(ctx, tc.stdout)
}
<-cmdDone
assertConnLog(t, connLogger, r.Workspace, database.ConnectionTypeReconnectingPty, tc.id)
assertConnLog(t, connLogger, r.Workspace, database.ConnectionLogMethodReconnectingPTY, tc.id)
})
}
+5 -5
View File
@@ -131,7 +131,7 @@ func TestSSH(t *testing.T) {
// Shells on Mac, Windows, and Linux all exit shells with the "exit" command.
stdin.WriteLine("exit")
<-cmdDone
assertConnLog(t, connLogger, r.Workspace, database.ConnectionTypeSsh, tc.id)
assertConnLog(t, connLogger, r.Workspace, database.ConnectionLogMethodSSH, tc.id)
})
}
@@ -1884,7 +1884,7 @@ func TestSSH_Stdio(t *testing.T) {
_ = clientOutput.Close()
<-cmdDone
assertConnLog(t, connLogger, r.Workspace, database.ConnectionTypeSsh, tc.id)
assertConnLog(t, connLogger, r.Workspace, database.ConnectionLogMethodSSH, tc.id)
})
}
}
@@ -2319,7 +2319,7 @@ func TestSSH_CoderConnect(t *testing.T) {
_ = clientOutput.Close()
<-cmdDone
assertConnLog(t, connLogger, r.Workspace, database.ConnectionTypeSsh, tc.id)
assertConnLog(t, connLogger, r.Workspace, database.ConnectionLogMethodSSH, tc.id)
})
}
@@ -2762,7 +2762,7 @@ func TestSSH_Completion(t *testing.T) {
func assertConnLog(t *testing.T,
connLogger *connectionlog.FakeConnectionLogger,
workspace database.WorkspaceTable,
expectedType database.ConnectionType,
expectedMethod database.ConnectionLogMethod,
clientSessionID string,
) {
t.Helper()
@@ -2770,7 +2770,7 @@ func assertConnLog(t *testing.T,
var logs []database.UpsertConnectionLogParams
require.Eventually(t, func() bool {
for _, log := range connLogger.ConnectionLogs() {
if log.Type == expectedType &&
if log.ConnectionMethod == expectedMethod &&
log.WorkspaceID == workspace.ID {
logs = append(logs, log)
}
+4 -4
View File
@@ -14,6 +14,7 @@ import (
"github.com/coder/coder/v2/coderd/connectionlog"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/db2sdk"
"github.com/coder/coder/v2/coderd/database/sdk2db"
"github.com/coder/coder/v2/coderd/tracing"
)
@@ -41,7 +42,7 @@ func (a *ConnLogAPI) ReportConnection(ctx context.Context, req *agentproto.Repor
if err != nil {
return nil, err
}
connectionType, err := db2sdk.ConnectionLogConnectionTypeFromAgentProtoConnectionType(req.GetConnection().GetType())
method, appName, err := sdk2db.ConnectionLogFromAgentType(req.GetConnection().GetType())
if err != nil {
return nil, err
}
@@ -88,7 +89,8 @@ func (a *ConnLogAPI) ReportConnection(ctx context.Context, req *agentproto.Repor
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: a.AgentName,
Type: connectionType,
ConnectionMethod: method,
AppNameOrPort: sql.NullString{String: appName, Valid: appName != ""},
Code: code,
IP: logIP,
ConnectionID: uuid.NullUUID{
@@ -116,8 +118,6 @@ func (a *ConnLogAPI) ReportConnection(ctx context.Context, req *agentproto.Repor
},
// N/A
UserAgent: sql.NullString{},
// N/A
SlugOrPort: sql.NullString{},
})
if err != nil {
return nil, xerrors.Errorf("export connection log: %w", err)
+79 -24
View File
@@ -45,6 +45,8 @@ func TestConnectionLog(t *testing.T) {
id uuid.UUID
action *agentproto.Connection_Action
typ *agentproto.Connection_Type
method database.ConnectionLogMethod
appName string
time time.Time
ip string
status int32
@@ -56,25 +58,30 @@ func TestConnectionLog(t *testing.T) {
id: uuid.New(),
action: agentproto.Connection_CONNECT.Enum(),
typ: agentproto.Connection_SSH.Enum(),
method: database.ConnectionLogMethodSSH,
time: dbtime.Now(),
ip: "127.0.0.1",
status: 200,
clientSessionID: "0123456789abcdef0123456789abcdef",
},
{
name: "VS Code Connect",
id: uuid.New(),
action: agentproto.Connection_CONNECT.Enum(),
typ: agentproto.Connection_VSCODE.Enum(),
time: dbtime.Now(),
ip: "8.8.8.8",
name: "VS Code Connect",
id: uuid.New(),
action: agentproto.Connection_CONNECT.Enum(),
typ: agentproto.Connection_VSCODE.Enum(),
method: database.ConnectionLogMethodSSH,
appName: "vscode",
time: dbtime.Now(),
ip: "8.8.8.8",
},
{
name: "JetBrains Connect",
id: uuid.New(),
action: agentproto.Connection_CONNECT.Enum(),
typ: agentproto.Connection_JETBRAINS.Enum(),
time: dbtime.Now(),
name: "JetBrains Connect",
id: uuid.New(),
action: agentproto.Connection_CONNECT.Enum(),
typ: agentproto.Connection_JETBRAINS.Enum(),
method: database.ConnectionLogMethodSSH,
appName: "jetbrains",
time: dbtime.Now(),
// Sometimes, JetBrains clients report as localhost, see
// https://github.com/coder/coder/issues/20194
ip: "localhost",
@@ -84,6 +91,16 @@ func TestConnectionLog(t *testing.T) {
id: uuid.New(),
action: agentproto.Connection_CONNECT.Enum(),
typ: agentproto.Connection_RECONNECTING_PTY.Enum(),
method: database.ConnectionLogMethodReconnectingPTY,
time: dbtime.Now(),
},
{
// SSH handlers reported unfamiliar apps as unspecified.
name: "Unspecified Connect",
id: uuid.New(),
action: agentproto.Connection_CONNECT.Enum(),
typ: agentproto.Connection_TYPE_UNSPECIFIED.Enum(),
method: database.ConnectionLogMethodSSH,
time: dbtime.Now(),
},
{
@@ -91,6 +108,7 @@ func TestConnectionLog(t *testing.T) {
id: uuid.New(),
action: agentproto.Connection_DISCONNECT.Enum(),
typ: agentproto.Connection_SSH.Enum(),
method: database.ConnectionLogMethodSSH,
time: dbtime.Now(),
},
{
@@ -98,10 +116,20 @@ func TestConnectionLog(t *testing.T) {
id: uuid.New(),
action: agentproto.Connection_DISCONNECT.Enum(),
typ: agentproto.Connection_SSH.Enum(),
method: database.ConnectionLogMethodSSH,
time: dbtime.Now(),
status: 500,
reason: "because error says so",
},
{
name: "VS Code Disconnect",
id: uuid.New(),
action: agentproto.Connection_DISCONNECT.Enum(),
typ: agentproto.Connection_VSCODE.Enum(),
method: database.ConnectionLogMethodSSH,
appName: "vscode",
time: dbtime.Now(),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -119,7 +147,7 @@ func TestConnectionLog(t *testing.T) {
AgentName: agent.Name,
Workspace: &agentapi.CachedWorkspaceFields{},
}
api.ReportConnection(context.Background(), &agentproto.ReportConnectionRequest{
_, err := api.ReportConnection(context.Background(), &agentproto.ReportConnectionRequest{
Connection: &agentproto.Connection{
Id: tt.id[:],
Action: *tt.action,
@@ -131,14 +159,24 @@ func TestConnectionLog(t *testing.T) {
ClientSessionId: tt.clientSessionID,
},
})
require.NoError(t, err)
expectedIPRaw := tt.ip
if expectedIPRaw == "localhost" {
expectedIPRaw = "127.0.0.1"
}
expectedIP := database.ParseIP(expectedIPRaw)
// Only disconnects carry a status code.
var expectedCode sql.NullInt32
if *tt.action == agentproto.Connection_DISCONNECT {
expectedCode = sql.NullInt32{Int32: tt.status, Valid: true}
}
require.True(t, connLogger.Contains(t, database.UpsertConnectionLogParams{
logs := connLogger.ConnectionLogs()
require.Len(t, logs, 1)
require.Equal(t, database.UpsertConnectionLogParams{
// The ID is generated per report.
ID: logs[0].ID,
Time: dbtime.Time(tt.time).In(time.UTC),
OrganizationID: workspace.OrganizationID,
WorkspaceOwnerID: workspace.OwnerID,
@@ -151,12 +189,10 @@ func TestConnectionLog(t *testing.T) {
},
ConnectionStatus: agentProtoConnectionActionToConnectionLog(t, *tt.action),
Code: sql.NullInt32{
Int32: tt.status,
Valid: *tt.action == agentproto.Connection_DISCONNECT,
},
IP: expectedIP,
Type: agentProtoConnectionTypeToConnectionLog(t, *tt.typ),
Code: expectedCode,
IP: expectedIP,
ConnectionMethod: tt.method,
AppNameOrPort: sql.NullString{String: tt.appName, Valid: tt.appName != ""},
DisconnectReason: sql.NullString{
String: tt.reason,
Valid: tt.reason != "",
@@ -169,15 +205,34 @@ func TestConnectionLog(t *testing.T) {
String: tt.clientSessionID,
Valid: tt.clientSessionID != "",
},
}))
}, logs[0])
})
}
}
func agentProtoConnectionTypeToConnectionLog(t *testing.T, typ agentproto.Connection_Type) database.ConnectionType {
a, err := db2sdk.ConnectionLogConnectionTypeFromAgentProtoConnectionType(typ)
require.NoError(t, err)
return a
// An agent connection type this coderd does not know is rejected rather than
// logged with a guessed method.
func TestConnectionLogRejectsUnknownType(t *testing.T) {
t.Parallel()
connLogger := connectionlog.NewFake()
api := &agentapi.ConnLogAPI{
ConnectionLogger: asAtomicPointer[connectionlog.ConnectionLogger](connLogger),
Database: dbmock.NewMockStore(gomock.NewController(t)),
AgentID: uuid.New(),
Workspace: &agentapi.CachedWorkspaceFields{},
}
id := uuid.New()
_, err := api.ReportConnection(context.Background(), &agentproto.ReportConnectionRequest{
Connection: &agentproto.Connection{
Id: id[:],
Action: agentproto.Connection_CONNECT,
Type: agentproto.Connection_Type(1000),
Timestamp: timestamppb.New(dbtime.Now()),
},
})
require.Error(t, err)
require.Empty(t, connLogger.ConnectionLogs())
}
func agentProtoConnectionActionToConnectionLog(t *testing.T, action agentproto.Connection_Action) database.ConnectionStatus {
+32 -24
View File
@@ -22608,10 +22608,21 @@ const docTemplate = `{
"agent_name": {
"type": "string"
},
"app_display_name": {
"description": "AppDisplayName is the registry display name for AppName, or AppName\nitself when the app is unregistered.",
"type": "string"
},
"app_name": {
"description": "AppName is the name of the connecting application, when known. The\nclient reports it, so it is a normalized label and not a guarantee.\nWorkspace app slugs and forwarded ports are reported in WebInfo.",
"type": "string"
},
"connect_time": {
"type": "string",
"format": "date-time"
},
"connection_method": {
"$ref": "#/definitions/codersdk.ConnectionLogMethod"
},
"id": {
"type": "string",
"format": "uuid"
@@ -22623,7 +22634,7 @@ const docTemplate = `{
"$ref": "#/definitions/codersdk.MinimalOrganization"
},
"ssh_info": {
"description": "SSHInfo is only set when ` + "`" + `type` + "`" + ` is one of:\n- ` + "`" + `ConnectionTypeSSH` + "`" + `\n- ` + "`" + `ConnectionTypeReconnectingPTY` + "`" + `\n- ` + "`" + `ConnectionTypeVSCode` + "`" + `\n- ` + "`" + `ConnectionTypeJetBrains` + "`" + `",
"description": "SSHInfo is set for connections that agents report.",
"allOf": [
{
"$ref": "#/definitions/codersdk.ConnectionLogSSHInfo"
@@ -22631,10 +22642,11 @@ const docTemplate = `{
]
},
"type": {
"$ref": "#/definitions/codersdk.ConnectionType"
"description": "Deprecated: Use ConnectionMethod and AppName.",
"type": "string"
},
"web_info": {
"description": "WebInfo is only set when ` + "`" + `type` + "`" + ` is one of:\n- ` + "`" + `ConnectionTypePortForwarding` + "`" + `\n- ` + "`" + `ConnectionTypeWorkspaceApp` + "`" + `\n- ` + "`" + `ConnectionTypeTunnel` + "`" + `",
"description": "WebInfo is set for connections that coderd records.",
"allOf": [
{
"$ref": "#/definitions/codersdk.ConnectionLogWebInfo"
@@ -22657,6 +22669,23 @@ const docTemplate = `{
}
}
},
"codersdk.ConnectionLogMethod": {
"type": "string",
"enum": [
"ssh",
"reconnecting_pty",
"workspace_app",
"port_forwarding",
"tunnel"
],
"x-enum-varnames": [
"ConnectionLogMethodSSH",
"ConnectionLogMethodReconnectingPTY",
"ConnectionLogMethodWorkspaceApp",
"ConnectionLogMethodPortForwarding",
"ConnectionLogMethodTunnel"
]
},
"codersdk.ConnectionLogResponse": {
"type": "object",
"properties": {
@@ -22719,27 +22748,6 @@ const docTemplate = `{
}
}
},
"codersdk.ConnectionType": {
"type": "string",
"enum": [
"ssh",
"vscode",
"jetbrains",
"reconnecting_pty",
"workspace_app",
"port_forwarding",
"tunnel"
],
"x-enum-varnames": [
"ConnectionTypeSSH",
"ConnectionTypeVSCode",
"ConnectionTypeJetBrains",
"ConnectionTypeReconnectingPTY",
"ConnectionTypeWorkspaceApp",
"ConnectionTypePortForwarding",
"ConnectionTypeTunnel"
]
},
"codersdk.ConvertLoginRequest": {
"type": "object",
"required": [
+32 -24
View File
@@ -20502,10 +20502,21 @@
"agent_name": {
"type": "string"
},
"app_display_name": {
"description": "AppDisplayName is the registry display name for AppName, or AppName\nitself when the app is unregistered.",
"type": "string"
},
"app_name": {
"description": "AppName is the name of the connecting application, when known. The\nclient reports it, so it is a normalized label and not a guarantee.\nWorkspace app slugs and forwarded ports are reported in WebInfo.",
"type": "string"
},
"connect_time": {
"type": "string",
"format": "date-time"
},
"connection_method": {
"$ref": "#/definitions/codersdk.ConnectionLogMethod"
},
"id": {
"type": "string",
"format": "uuid"
@@ -20517,7 +20528,7 @@
"$ref": "#/definitions/codersdk.MinimalOrganization"
},
"ssh_info": {
"description": "SSHInfo is only set when `type` is one of:\n- `ConnectionTypeSSH`\n- `ConnectionTypeReconnectingPTY`\n- `ConnectionTypeVSCode`\n- `ConnectionTypeJetBrains`",
"description": "SSHInfo is set for connections that agents report.",
"allOf": [
{
"$ref": "#/definitions/codersdk.ConnectionLogSSHInfo"
@@ -20525,10 +20536,11 @@
]
},
"type": {
"$ref": "#/definitions/codersdk.ConnectionType"
"description": "Deprecated: Use ConnectionMethod and AppName.",
"type": "string"
},
"web_info": {
"description": "WebInfo is only set when `type` is one of:\n- `ConnectionTypePortForwarding`\n- `ConnectionTypeWorkspaceApp`\n- `ConnectionTypeTunnel`",
"description": "WebInfo is set for connections that coderd records.",
"allOf": [
{
"$ref": "#/definitions/codersdk.ConnectionLogWebInfo"
@@ -20551,6 +20563,23 @@
}
}
},
"codersdk.ConnectionLogMethod": {
"type": "string",
"enum": [
"ssh",
"reconnecting_pty",
"workspace_app",
"port_forwarding",
"tunnel"
],
"x-enum-varnames": [
"ConnectionLogMethodSSH",
"ConnectionLogMethodReconnectingPTY",
"ConnectionLogMethodWorkspaceApp",
"ConnectionLogMethodPortForwarding",
"ConnectionLogMethodTunnel"
]
},
"codersdk.ConnectionLogResponse": {
"type": "object",
"properties": {
@@ -20613,27 +20642,6 @@
}
}
},
"codersdk.ConnectionType": {
"type": "string",
"enum": [
"ssh",
"vscode",
"jetbrains",
"reconnecting_pty",
"workspace_app",
"port_forwarding",
"tunnel"
],
"x-enum-varnames": [
"ConnectionTypeSSH",
"ConnectionTypeVSCode",
"ConnectionTypeJetBrains",
"ConnectionTypeReconnectingPTY",
"ConnectionTypeWorkspaceApp",
"ConnectionTypePortForwarding",
"ConnectionTypeTunnel"
]
},
"codersdk.ConvertLoginRequest": {
"type": "object",
"required": ["password", "to_type"],
+4 -4
View File
@@ -82,8 +82,8 @@ func (m *FakeConnectionLogger) Contains(t testing.TB, expected database.UpsertCo
t.Logf("connection log %d: expected AgentName %s, got %s", idx+1, expected.AgentName, cl.AgentName)
continue
}
if expected.Type != "" && cl.Type != expected.Type {
t.Logf("connection log %d: expected Type %s, got %s", idx+1, expected.Type, cl.Type)
if expected.ConnectionMethod != "" && cl.ConnectionMethod != expected.ConnectionMethod {
t.Logf("connection log %d: expected ConnectionMethod %s, got %s", idx+1, expected.ConnectionMethod, cl.ConnectionMethod)
continue
}
if expected.Code.Valid && cl.Code.Int32 != expected.Code.Int32 {
@@ -102,8 +102,8 @@ func (m *FakeConnectionLogger) Contains(t testing.TB, expected database.UpsertCo
t.Logf("connection log %d: expected UserID %s, got %s", idx+1, expected.UserID.UUID, cl.UserID.UUID)
continue
}
if expected.SlugOrPort.Valid && cl.SlugOrPort.String != expected.SlugOrPort.String {
t.Logf("connection log %d: expected SlugOrPort %s, got %s", idx+1, expected.SlugOrPort.String, cl.SlugOrPort.String)
if expected.AppNameOrPort.Valid && cl.AppNameOrPort.String != expected.AppNameOrPort.String {
t.Logf("connection log %d: expected AppNameOrPort %s, got %s", idx+1, expected.AppNameOrPort.String, cl.AppNameOrPort.String)
continue
}
if expected.ConnectionID.Valid && cl.ConnectionID.UUID != expected.ConnectionID.UUID {
+9 -13
View File
@@ -1002,20 +1002,16 @@ func ChatRoleActions(role codersdk.ChatRole) []policy.Action {
return []policy.Action{}
}
func ConnectionLogConnectionTypeFromAgentProtoConnectionType(typ agentproto.Connection_Type) (database.ConnectionType, error) {
switch typ {
case agentproto.Connection_SSH:
return database.ConnectionTypeSsh, nil
case agentproto.Connection_JETBRAINS:
return database.ConnectionTypeJetbrains, nil
case agentproto.Connection_VSCODE:
return database.ConnectionTypeVscode, nil
case agentproto.Connection_RECONNECTING_PTY:
return database.ConnectionTypeReconnectingPty, nil
default:
// Also Connection_TYPE_UNSPECIFIED, no mapping.
return "", xerrors.Errorf("unknown agent connection type %q", typ)
// ConnectionLogType returns the deprecated ConnectionLog.Type. The legacy
// type search filter mirrors it, so change both together.
func ConnectionLogType(method database.ConnectionLogMethod, appNameOrPort string) string {
if method == database.ConnectionLogMethodSSH {
switch family := codersdk.AppNameFamily(appNameOrPort); family {
case codersdk.AppFamilyVSCode, codersdk.AppFamilyJetBrains:
return string(family)
}
}
return string(method)
}
func ConnectionLogStatusFromAgentProtoConnectionAction(action agentproto.Connection_Action) (database.ConnectionStatus, error) {
+27
View File
@@ -1243,3 +1243,30 @@ func TestChatQueuedMessage_MalformedContent(t *testing.T) {
require.Empty(t, queued.Content)
}
func TestConnectionLogType(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
method database.ConnectionLogMethod
appName string
want string
}{
{"VSCodeFamily", database.ConnectionLogMethodSSH, "cursor", "vscode"},
{"JetBrainsFamily", database.ConnectionLogMethodSSH, "goland", "jetbrains"},
{"Normalized", database.ConnectionLogMethodSSH, "Code-Server", "vscode"},
// Every other SSH app name, including an absent one, is plain SSH.
{"Absent", database.ConnectionLogMethodSSH, "", "ssh"},
{"SSHFamily", database.ConnectionLogMethodSSH, "zed", "ssh"},
{"Unregistered", database.ConnectionLogMethodSSH, "an_unregistered_ide", "ssh"},
// Other methods report themselves, whatever the app.
{"ReconnectingPTY", database.ConnectionLogMethodReconnectingPTY, "cursor", "reconnecting_pty"},
{"WorkspaceApp", database.ConnectionLogMethodWorkspaceApp, "vscode", "workspace_app"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
require.Equal(t, tc.want, db2sdk.ConnectionLogType(tc.method, tc.appName))
})
}
}
+6 -6
View File
@@ -490,7 +490,7 @@ func ConnectionLog(t testing.TB, db database.Store, seed database.UpsertConnecti
WorkspaceID: takeFirst(seed.WorkspaceID, uuid.New()),
WorkspaceName: takeFirst(seed.WorkspaceName, testutil.GetRandomName(t)),
AgentName: takeFirst(seed.AgentName, testutil.GetRandomName(t)),
Type: takeFirst(seed.Type, database.ConnectionTypeSsh),
ConnectionMethod: takeFirst(seed.ConnectionMethod, database.ConnectionLogMethodSSH),
Code: sql.NullInt32{
Int32: takeFirst(seed.Code.Int32, 0),
Valid: takeFirst(seed.Code.Valid, false),
@@ -510,9 +510,9 @@ func ConnectionLog(t testing.TB, db database.Store, seed database.UpsertConnecti
UUID: takeFirst(seed.UserID.UUID, uuid.Nil),
Valid: takeFirst(seed.UserID.Valid, false),
},
SlugOrPort: sql.NullString{
String: takeFirst(seed.SlugOrPort.String, ""),
Valid: takeFirst(seed.SlugOrPort.Valid, false),
AppNameOrPort: sql.NullString{
String: takeFirst(seed.AppNameOrPort.String, ""),
Valid: takeFirst(seed.AppNameOrPort.Valid, false),
},
ConnectionID: uuid.NullUUID{
UUID: takeFirst(seed.ConnectionID.UUID, uuid.Nil),
@@ -542,13 +542,13 @@ func ConnectionLog(t testing.TB, db database.Store, seed database.UpsertConnecti
WorkspaceID: []uuid.UUID{arg.WorkspaceID},
WorkspaceName: []string{arg.WorkspaceName},
AgentName: []string{arg.AgentName},
Type: []database.ConnectionType{arg.Type},
ConnectionMethod: []database.ConnectionLogMethod{arg.ConnectionMethod},
Code: []int32{arg.Code.Int32},
CodeValid: []bool{arg.Code.Valid},
Ip: []pqtype.Inet{arg.IP},
UserAgent: []string{arg.UserAgent.String},
UserID: []uuid.UUID{arg.UserID.UUID},
SlugOrPort: []string{arg.SlugOrPort.String},
AppNameOrPort: []string{arg.AppNameOrPort.String},
ConnectionID: []uuid.UUID{arg.ConnectionID.UUID},
DisconnectReason: []string{arg.DisconnectReason.String},
DisconnectTime: []time.Time{disconnectTime.Time},
+2 -2
View File
@@ -1339,7 +1339,7 @@ func TestDeleteOldConnectionLogs(t *testing.T) {
WorkspaceID: workspace.ID,
WorkspaceName: workspace.Name,
AgentName: "agent1",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionStatus: database.ConnectionStatusConnected,
})
@@ -1354,7 +1354,7 @@ func TestDeleteOldConnectionLogs(t *testing.T) {
WorkspaceID: workspace.ID,
WorkspaceName: workspace.Name,
AgentName: "agent2",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionStatus: database.ConnectionStatusConnected,
})
}
+11 -11
View File
@@ -399,21 +399,19 @@ CREATE TYPE chat_title_source AS ENUM (
COMMENT ON TYPE chat_title_source IS 'Where a chat title came from, in ascending rank. A title write applies only when its source ranks at or above the current source. fallback: derived from the first prompt, or the default title of a chat created without one. generated: written by automatic title generation. user: supplied by the caller at creation or by rename.';
CREATE TYPE connection_status AS ENUM (
'connected',
'disconnected'
);
CREATE TYPE connection_type AS ENUM (
CREATE TYPE connection_log_method AS ENUM (
'ssh',
'vscode',
'jetbrains',
'reconnecting_pty',
'workspace_app',
'port_forwarding',
'tunnel'
);
CREATE TYPE connection_status AS ENUM (
'connected',
'disconnected'
);
CREATE TYPE cors_behavior AS ENUM (
'simple',
'passthru'
@@ -2453,12 +2451,12 @@ CREATE TABLE connection_logs (
workspace_id uuid NOT NULL,
workspace_name text NOT NULL,
agent_name text NOT NULL,
type connection_type NOT NULL,
connection_method connection_log_method NOT NULL,
ip inet,
code integer,
user_agent text,
user_id uuid,
slug_or_port text,
app_name_or_port text,
connection_id uuid,
disconnect_time timestamp with time zone,
disconnect_reason text,
@@ -2466,13 +2464,15 @@ CREATE TABLE connection_logs (
CONSTRAINT connection_logs_client_session_id_check CHECK (((client_session_id IS NULL) OR (client_session_id ~ '^[0-9a-f]{32}$'::text)))
);
COMMENT ON COLUMN connection_logs.connection_method IS 'How the connection was established.';
COMMENT ON COLUMN connection_logs.code IS 'Either the HTTP status code of the web request, or the exit code of an SSH connection. For non-web connections, this is Null until we receive a disconnect event for the same connection_id.';
COMMENT ON COLUMN connection_logs.user_agent IS 'Null for SSH events. For web connections, this is the User-Agent header from the request.';
COMMENT ON COLUMN connection_logs.user_id IS 'Null for SSH events. For web connections, this is the ID of the user that made the request.';
COMMENT ON COLUMN connection_logs.slug_or_port IS 'Null for SSH events. For web connections, this is the slug of the app or the port number being forwarded.';
COMMENT ON COLUMN connection_logs.app_name_or_port IS 'Self-reported name of the connecting application for SSH and reconnecting PTY; destination slug or port for workspace apps and port forwarding. Null when absent.';
COMMENT ON COLUMN connection_logs.connection_id IS 'The SSH connection ID. Used to correlate connections and disconnections. As it originates from the agent, it is not guaranteed to be unique.';
@@ -0,0 +1,37 @@
CREATE TYPE connection_type AS ENUM (
'ssh', 'vscode', 'jetbrains', 'reconnecting_pty',
'workspace_app', 'port_forwarding', 'tunnel'
);
-- App names collapse to the historical SSH families on rollback.
ALTER TABLE connection_logs
ALTER COLUMN app_name_or_port TYPE text USING (
CASE
WHEN connection_method IN ('ssh', 'reconnecting_pty', 'tunnel') THEN NULL
ELSE app_name_or_port
END
),
ALTER COLUMN connection_method TYPE connection_type USING (
CASE
WHEN connection_method != 'ssh' THEN connection_method::text
-- Snapshot of the VS Code and JetBrains families in
-- codersdk/appname.go. Apps registered later roll back to ssh.
WHEN app_name_or_port IN (
'vscode', 'vscode_insiders', 'vscode_web', 'code_server', 'cursor',
'windsurf', 'positron', 'vscodium', 'codium', 'antigravity', 'trae',
'kiro', 'devin', 'code_oss', 'vscodium_insiders', 'devin_next', 'trae_cn'
) THEN 'vscode'
WHEN app_name_or_port IN (
'jetbrains', 'intellij', 'pycharm', 'goland', 'webstorm', 'phpstorm',
'rubymine', 'clion', 'rider', 'rustrover', 'datagrip', 'dataspell',
'mps', 'android_studio'
) THEN 'jetbrains'
ELSE 'ssh'
END
)::connection_type;
COMMENT ON COLUMN connection_logs.connection_method IS NULL;
COMMENT ON COLUMN connection_logs.app_name_or_port IS 'Null for SSH events. For web connections, this is the slug of the app or the port number being forwarded.';
ALTER TABLE connection_logs RENAME COLUMN app_name_or_port TO slug_or_port;
ALTER TABLE connection_logs RENAME COLUMN connection_method TO type;
DROP TYPE connection_log_method;
@@ -0,0 +1,26 @@
CREATE TYPE connection_log_method AS ENUM (
'ssh', 'reconnecting_pty', 'workspace_app', 'port_forwarding', 'tunnel'
);
-- Convert both columns in one rewrite under an ACCESS EXCLUSIVE lock.
ALTER TABLE connection_logs
ALTER COLUMN slug_or_port TYPE text USING (
CASE
WHEN type::text IN ('vscode', 'jetbrains') THEN type::text
WHEN type::text IN ('ssh', 'reconnecting_pty', 'tunnel') THEN NULL
ELSE NULLIF(slug_or_port, '')
END
),
ALTER COLUMN type TYPE connection_log_method USING (
CASE
WHEN type::text IN ('vscode', 'jetbrains') THEN 'ssh'
ELSE type::text
END
)::connection_log_method;
ALTER TABLE connection_logs RENAME COLUMN type TO connection_method;
ALTER TABLE connection_logs RENAME COLUMN slug_or_port TO app_name_or_port;
DROP TYPE connection_type;
COMMENT ON COLUMN connection_logs.connection_method IS 'How the connection was established.';
COMMENT ON COLUMN connection_logs.app_name_or_port IS 'Self-reported name of the connecting application for SSH and reconnecting PTY; destination slug or port for workspace apps and port forwarding. Null when absent.';
@@ -0,0 +1,150 @@
package migrations_test
import (
"database/sql"
"os"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbgen"
"github.com/coder/coder/v2/testutil"
)
const (
insertConnectionLog000616 = `INSERT INTO connection_logs (id, connect_time, organization_id,
workspace_owner_id, workspace_id, workspace_name, agent_name, type, slug_or_port)
VALUES ($1, now(), $2, $3, $4, $5, 'main', $6, $7)`
insertConnectionLog000617 = `INSERT INTO connection_logs (id, connect_time, organization_id,
workspace_owner_id, workspace_id, workspace_name, agent_name, connection_method, app_name_or_port)
VALUES ($1, now(), $2, $3, $4, $5, 'main', $6, $7)`
selectConnectionLog000616 = `SELECT type::text, slug_or_port FROM connection_logs WHERE id = $1`
selectConnectionLog000617 = `SELECT connection_method::text, app_name_or_port FROM connection_logs WHERE id = $1`
)
// A pending migration batch can add tunnel to the old enum and then replace
// that enum. Comparisons must not materialize its uncommitted new value.
func TestMigration000617ConnectionLogsMethodInSingleTxn(t *testing.T) {
t.Parallel()
if testing.Short() {
t.SkipNow()
}
sqlDB := testSQLDB(t)
ctx := testutil.Context(t, testutil.WaitSuperLong)
applyMigrationsInTxn(ctx, t, sqlDB, 1, 556)
orgID, ownerID, templateID, workspaceID := uuid.New(), uuid.New(), uuid.New(), uuid.New()
_, err := sqlDB.ExecContext(ctx, `
INSERT INTO organizations (id, name, description, display_name, created_at, updated_at, default_org_member_roles)
VALUES ($1, 'migration-org', '', '', now(), now(), '{}');
`, orgID)
require.NoError(t, err)
_, err = sqlDB.ExecContext(ctx, `
INSERT INTO users (id, email, username, hashed_password, created_at, updated_at) VALUES ($1, 'migration@example.com', 'migration-user', '', now(), now());
`, ownerID)
require.NoError(t, err)
_, err = sqlDB.ExecContext(ctx, `
INSERT INTO templates (id, created_at, updated_at, organization_id, name, provisioner, active_version_id, created_by)
VALUES ($1, now(), now(), $2, 'migration-template', 'echo', $3, $4);
`, templateID, orgID, uuid.New(), ownerID)
require.NoError(t, err)
_, err = sqlDB.ExecContext(ctx, `
INSERT INTO workspaces (id, created_at, updated_at, owner_id, organization_id, template_id, name)
VALUES ($1, now(), now(), $2, $3, $4, 'migration-workspace');
`, workspaceID, ownerID, orgID, templateID)
require.NoError(t, err)
id := uuid.New()
_, err = sqlDB.ExecContext(ctx, insertConnectionLog000616, id, orgID, ownerID, workspaceID, "migration-workspace", "vscode", nil)
require.NoError(t, err)
applyMigrationsInTxn(ctx, t, sqlDB, 557, 617)
var method string
var appName sql.NullString
require.NoError(t, sqlDB.QueryRowContext(ctx, selectConnectionLog000617, id).Scan(&method, &appName))
require.Equal(t, "ssh", method)
require.Equal(t, sql.NullString{String: "vscode", Valid: true}, appName)
}
// The up migration splits each connection type into a method and an app name,
// and the down migration folds app names back into types.
func TestMigration000617ConnectionLogsMethod(t *testing.T) {
t.Parallel()
if testing.Short() {
t.SkipNow()
}
sqlDB := testSQLDB(t)
stepTo(t, sqlDB, 616)
ctx := testutil.Context(t, testutil.WaitLong)
db := database.New(sqlDB)
org := dbgen.Organization(t, db, database.Organization{})
owner := dbgen.User(t, db, database.User{})
tpl := dbgen.Template(t, db, database.Template{OrganizationID: org.ID, CreatedBy: owner.ID})
ws := dbgen.Workspace(t, db, database.WorkspaceTable{OrganizationID: org.ID, OwnerID: owner.ID, TemplateID: tpl.ID})
// row is (type, slug_or_port) before 000617 and
// (connection_method, app_name_or_port) after it.
type row struct {
kind string
appNameOrPort sql.NullString
}
app := func(name string) sql.NullString { return sql.NullString{String: name, Valid: true} }
ids := map[row]uuid.UUID{}
insert := func(query string, r row) {
ids[r] = uuid.New()
_, err := sqlDB.ExecContext(ctx, query, ids[r], org.ID, owner.ID, ws.ID, ws.Name, r.kind, r.appNameOrPort)
require.NoError(t, err)
}
read := func(query string, r row) (got row) {
require.NoError(t, sqlDB.QueryRowContext(ctx, query, ids[r]).Scan(&got.kind, &got.appNameOrPort))
return got
}
migrate := func(file string) {
migration, err := os.ReadFile(file)
require.NoError(t, err)
_, err = sqlDB.ExecContext(ctx, string(migration))
require.NoError(t, err)
}
// Each released type and what the up migration turns it into.
converted := map[row]row{
{"ssh", sql.NullString{}}: {"ssh", sql.NullString{}},
{"vscode", sql.NullString{}}: {"ssh", app("vscode")},
{"jetbrains", sql.NullString{}}: {"ssh", app("jetbrains")},
{"reconnecting_pty", sql.NullString{}}: {"reconnecting_pty", sql.NullString{}},
{"workspace_app", app("code-server")}: {"workspace_app", app("code-server")},
{"port_forwarding", app("8080")}: {"port_forwarding", app("8080")},
{"tunnel", sql.NullString{}}: {"tunnel", sql.NullString{}},
}
for old := range converted {
insert(insertConnectionLog000616, old)
}
migrate("000617_connection_logs_method_app_name.up.sql")
for old, want := range converted {
require.Equal(t, want, read(selectConnectionLog000617, old), old.kind)
}
// App names only newer servers write. The down migration folds them into
// types with its snapshot of the app registry.
folded := map[row]row{
{"ssh", app("cursor")}: {"vscode", sql.NullString{}},
{"ssh", app("trae_cn")}: {"vscode", sql.NullString{}},
{"ssh", app("goland")}: {"jetbrains", sql.NullString{}},
{"ssh", app("zed")}: {"ssh", sql.NullString{}},
{"ssh", app("a_new_ide")}: {"ssh", sql.NullString{}},
{"reconnecting_pty", app("cursor")}: {"reconnecting_pty", sql.NullString{}},
}
for current := range folded {
insert(insertConnectionLog000617, current)
}
migrate("000617_connection_logs_method_app_name.down.sql")
for old := range converted {
require.Equal(t, old, read(selectConnectionLog000616, old), old.kind)
}
for current, want := range folded {
require.Equal(t, want, read(selectConnectionLog000616, current), current.kind+" "+current.appNameOrPort.String)
}
}
+17 -17
View File
@@ -1027,23 +1027,23 @@ func (r GetWorkspaceBuildAgentsByInstanceIDRow) RBACObject() rbac.Object {
// still used as the canonical connection log event type throughout
// the codebase.
type UpsertConnectionLogParams struct {
ID uuid.UUID `db:"id" json:"id"`
OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"`
WorkspaceOwnerID uuid.UUID `db:"workspace_owner_id" json:"workspace_owner_id"`
WorkspaceID uuid.UUID `db:"workspace_id" json:"workspace_id"`
WorkspaceName string `db:"workspace_name" json:"workspace_name"`
AgentName string `db:"agent_name" json:"agent_name"`
Type ConnectionType `db:"type" json:"type"`
Code sql.NullInt32 `db:"code" json:"code"`
IP pqtype.Inet `db:"ip" json:"ip"`
UserAgent sql.NullString `db:"user_agent" json:"user_agent"`
UserID uuid.NullUUID `db:"user_id" json:"user_id"`
SlugOrPort sql.NullString `db:"slug_or_port" json:"slug_or_port"`
ConnectionID uuid.NullUUID `db:"connection_id" json:"connection_id"`
DisconnectReason sql.NullString `db:"disconnect_reason" json:"disconnect_reason"`
ClientSessionID sql.NullString `db:"client_session_id" json:"client_session_id"`
Time time.Time `db:"time" json:"time"`
ConnectionStatus ConnectionStatus `db:"connection_status" json:"connection_status"`
ID uuid.UUID `db:"id" json:"id"`
OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"`
WorkspaceOwnerID uuid.UUID `db:"workspace_owner_id" json:"workspace_owner_id"`
WorkspaceID uuid.UUID `db:"workspace_id" json:"workspace_id"`
WorkspaceName string `db:"workspace_name" json:"workspace_name"`
AgentName string `db:"agent_name" json:"agent_name"`
ConnectionMethod ConnectionLogMethod `db:"connection_method" json:"connection_method"`
Code sql.NullInt32 `db:"code" json:"code"`
IP pqtype.Inet `db:"ip" json:"ip"`
UserAgent sql.NullString `db:"user_agent" json:"user_agent"`
UserID uuid.NullUUID `db:"user_id" json:"user_id"`
AppNameOrPort sql.NullString `db:"app_name_or_port" json:"app_name_or_port"`
ConnectionID uuid.NullUUID `db:"connection_id" json:"connection_id"`
DisconnectReason sql.NullString `db:"disconnect_reason" json:"disconnect_reason"`
ClientSessionID sql.NullString `db:"client_session_id" json:"client_session_id"`
Time time.Time `db:"time" json:"time"`
ConnectionStatus ConnectionStatus `db:"connection_status" json:"connection_status"`
}
func (r GetLatestWorkspaceBuildWithStatusByWorkspaceIDRow) RBACObject() rbac.Object {
+8 -4
View File
@@ -696,7 +696,9 @@ func (q *sqlQuerier) GetAuthorizedConnectionLogsOffset(ctx context.Context, arg
arg.WorkspaceOwner,
arg.WorkspaceOwnerID,
arg.WorkspaceOwnerEmail,
arg.Type,
arg.ConnectionMethod,
pq.Array(arg.AppNames),
pq.Array(arg.ExcludedAppNames),
arg.UserID,
arg.Username,
arg.UserEmail,
@@ -723,12 +725,12 @@ func (q *sqlQuerier) GetAuthorizedConnectionLogsOffset(ctx context.Context, arg
&i.ConnectionLog.WorkspaceID,
&i.ConnectionLog.WorkspaceName,
&i.ConnectionLog.AgentName,
&i.ConnectionLog.Type,
&i.ConnectionLog.ConnectionMethod,
&i.ConnectionLog.Ip,
&i.ConnectionLog.Code,
&i.ConnectionLog.UserAgent,
&i.ConnectionLog.UserID,
&i.ConnectionLog.SlugOrPort,
&i.ConnectionLog.AppNameOrPort,
&i.ConnectionLog.ConnectionID,
&i.ConnectionLog.DisconnectTime,
&i.ConnectionLog.DisconnectReason,
@@ -781,7 +783,9 @@ func (q *sqlQuerier) CountAuthorizedConnectionLogs(ctx context.Context, arg Coun
arg.WorkspaceOwner,
arg.WorkspaceOwnerID,
arg.WorkspaceOwnerEmail,
arg.Type,
arg.ConnectionMethod,
pq.Array(arg.AppNames),
pq.Array(arg.ExcludedAppNames),
arg.UserID,
arg.Username,
arg.UserEmail,
+79 -84
View File
@@ -2005,6 +2005,73 @@ func AllChatTitleSourceValues() []ChatTitleSource {
}
}
type ConnectionLogMethod string
const (
ConnectionLogMethodSSH ConnectionLogMethod = "ssh"
ConnectionLogMethodReconnectingPTY ConnectionLogMethod = "reconnecting_pty"
ConnectionLogMethodWorkspaceApp ConnectionLogMethod = "workspace_app"
ConnectionLogMethodPortForwarding ConnectionLogMethod = "port_forwarding"
ConnectionLogMethodTunnel ConnectionLogMethod = "tunnel"
)
func (e *ConnectionLogMethod) Scan(src interface{}) error {
switch s := src.(type) {
case []byte:
*e = ConnectionLogMethod(s)
case string:
*e = ConnectionLogMethod(s)
default:
return fmt.Errorf("unsupported scan type for ConnectionLogMethod: %T", src)
}
return nil
}
type NullConnectionLogMethod struct {
ConnectionLogMethod ConnectionLogMethod `json:"connection_log_method"`
Valid bool `json:"valid"` // Valid is true if ConnectionLogMethod is not NULL
}
// Scan implements the Scanner interface.
func (ns *NullConnectionLogMethod) Scan(value interface{}) error {
if value == nil {
ns.ConnectionLogMethod, ns.Valid = "", false
return nil
}
ns.Valid = true
return ns.ConnectionLogMethod.Scan(value)
}
// Value implements the driver Valuer interface.
func (ns NullConnectionLogMethod) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return string(ns.ConnectionLogMethod), nil
}
func (e ConnectionLogMethod) Valid() bool {
switch e {
case ConnectionLogMethodSSH,
ConnectionLogMethodReconnectingPTY,
ConnectionLogMethodWorkspaceApp,
ConnectionLogMethodPortForwarding,
ConnectionLogMethodTunnel:
return true
}
return false
}
func AllConnectionLogMethodValues() []ConnectionLogMethod {
return []ConnectionLogMethod{
ConnectionLogMethodSSH,
ConnectionLogMethodReconnectingPTY,
ConnectionLogMethodWorkspaceApp,
ConnectionLogMethodPortForwarding,
ConnectionLogMethodTunnel,
}
}
type ConnectionStatus string
const (
@@ -2063,79 +2130,6 @@ func AllConnectionStatusValues() []ConnectionStatus {
}
}
type ConnectionType string
const (
ConnectionTypeSsh ConnectionType = "ssh"
ConnectionTypeVscode ConnectionType = "vscode"
ConnectionTypeJetbrains ConnectionType = "jetbrains"
ConnectionTypeReconnectingPty ConnectionType = "reconnecting_pty"
ConnectionTypeWorkspaceApp ConnectionType = "workspace_app"
ConnectionTypePortForwarding ConnectionType = "port_forwarding"
ConnectionTypeTunnel ConnectionType = "tunnel"
)
func (e *ConnectionType) Scan(src interface{}) error {
switch s := src.(type) {
case []byte:
*e = ConnectionType(s)
case string:
*e = ConnectionType(s)
default:
return fmt.Errorf("unsupported scan type for ConnectionType: %T", src)
}
return nil
}
type NullConnectionType struct {
ConnectionType ConnectionType `json:"connection_type"`
Valid bool `json:"valid"` // Valid is true if ConnectionType is not NULL
}
// Scan implements the Scanner interface.
func (ns *NullConnectionType) Scan(value interface{}) error {
if value == nil {
ns.ConnectionType, ns.Valid = "", false
return nil
}
ns.Valid = true
return ns.ConnectionType.Scan(value)
}
// Value implements the driver Valuer interface.
func (ns NullConnectionType) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return string(ns.ConnectionType), nil
}
func (e ConnectionType) Valid() bool {
switch e {
case ConnectionTypeSsh,
ConnectionTypeVscode,
ConnectionTypeJetbrains,
ConnectionTypeReconnectingPty,
ConnectionTypeWorkspaceApp,
ConnectionTypePortForwarding,
ConnectionTypeTunnel:
return true
}
return false
}
func AllConnectionTypeValues() []ConnectionType {
return []ConnectionType{
ConnectionTypeSsh,
ConnectionTypeVscode,
ConnectionTypeJetbrains,
ConnectionTypeReconnectingPty,
ConnectionTypeWorkspaceApp,
ConnectionTypePortForwarding,
ConnectionTypeTunnel,
}
}
type CorsBehavior string
const (
@@ -5503,23 +5497,24 @@ type ChatUserModelOverride struct {
}
type ConnectionLog struct {
ID uuid.UUID `db:"id" json:"id"`
ConnectTime time.Time `db:"connect_time" json:"connect_time"`
OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"`
WorkspaceOwnerID uuid.UUID `db:"workspace_owner_id" json:"workspace_owner_id"`
WorkspaceID uuid.UUID `db:"workspace_id" json:"workspace_id"`
WorkspaceName string `db:"workspace_name" json:"workspace_name"`
AgentName string `db:"agent_name" json:"agent_name"`
Type ConnectionType `db:"type" json:"type"`
Ip pqtype.Inet `db:"ip" json:"ip"`
ID uuid.UUID `db:"id" json:"id"`
ConnectTime time.Time `db:"connect_time" json:"connect_time"`
OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"`
WorkspaceOwnerID uuid.UUID `db:"workspace_owner_id" json:"workspace_owner_id"`
WorkspaceID uuid.UUID `db:"workspace_id" json:"workspace_id"`
WorkspaceName string `db:"workspace_name" json:"workspace_name"`
AgentName string `db:"agent_name" json:"agent_name"`
// How the connection was established.
ConnectionMethod ConnectionLogMethod `db:"connection_method" json:"connection_method"`
Ip pqtype.Inet `db:"ip" json:"ip"`
// Either the HTTP status code of the web request, or the exit code of an SSH connection. For non-web connections, this is Null until we receive a disconnect event for the same connection_id.
Code sql.NullInt32 `db:"code" json:"code"`
// Null for SSH events. For web connections, this is the User-Agent header from the request.
UserAgent sql.NullString `db:"user_agent" json:"user_agent"`
// Null for SSH events. For web connections, this is the ID of the user that made the request.
UserID uuid.NullUUID `db:"user_id" json:"user_id"`
// Null for SSH events. For web connections, this is the slug of the app or the port number being forwarded.
SlugOrPort sql.NullString `db:"slug_or_port" json:"slug_or_port"`
// Self-reported name of the connecting application for SSH and reconnecting PTY; destination slug or port for workspace apps and port forwarding. Null when absent.
AppNameOrPort sql.NullString `db:"app_name_or_port" json:"app_name_or_port"`
// The SSH connection ID. Used to correlate connections and disconnections. As it originates from the agent, it is not guaranteed to be unique.
ConnectionID uuid.NullUUID `db:"connection_id" json:"connection_id"`
// The time the connection was closed. Null for web connections. For other connections, this is null until we receive a disconnect event for the same connection_id.
+161 -85
View File
@@ -4541,7 +4541,7 @@ func TestCountConnectionLogs(t *testing.T) {
OrganizationID: wsA.OrganizationID,
WorkspaceOwnerID: wsA.OwnerID,
WorkspaceID: wsA.ID,
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
})
}
for i := 0; i < 10; i++ {
@@ -4549,7 +4549,7 @@ func TestCountConnectionLogs(t *testing.T) {
OrganizationID: wsB.OrganizationID,
WorkspaceOwnerID: wsB.OwnerID,
WorkspaceID: wsB.ID,
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
})
}
@@ -4619,11 +4619,11 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
WorkspaceOwnerID: ws1.OwnerID,
WorkspaceID: ws1.ID,
WorkspaceName: ws1.Name,
Type: database.ConnectionTypeWorkspaceApp,
ConnectionMethod: database.ConnectionLogMethodWorkspaceApp,
ConnectionStatus: database.ConnectionStatusConnected,
UserID: uuid.NullUUID{UUID: user1.ID, Valid: true},
UserAgent: sql.NullString{String: "Mozilla/5.0", Valid: true},
SlugOrPort: sql.NullString{String: "code-server", Valid: true},
AppNameOrPort: sql.NullString{String: "code-server", Valid: true},
ConnectionID: uuid.NullUUID{UUID: log1ConnID, Valid: true},
})
@@ -4634,7 +4634,8 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
WorkspaceOwnerID: ws1.OwnerID,
WorkspaceID: ws1.ID,
WorkspaceName: ws1.Name,
Type: database.ConnectionTypeVscode,
ConnectionMethod: database.ConnectionLogMethodSSH,
AppNameOrPort: sql.NullString{String: "vscode", Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
ConnectionID: uuid.NullUUID{UUID: log2ConnID, Valid: true},
})
@@ -4658,7 +4659,7 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
WorkspaceOwnerID: ws2.OwnerID,
WorkspaceID: ws2.ID,
WorkspaceName: ws2.Name,
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionStatus: database.ConnectionStatusConnected,
UserID: uuid.NullUUID{UUID: user2.ID, Valid: true},
ConnectionID: uuid.NullUUID{UUID: log3ConnID, Valid: true},
@@ -4682,7 +4683,8 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
WorkspaceOwnerID: ws2.OwnerID,
WorkspaceID: ws2.ID,
WorkspaceName: ws2.Name,
Type: database.ConnectionTypeVscode,
ConnectionMethod: database.ConnectionLogMethodSSH,
AppNameOrPort: sql.NullString{String: "vscode", Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
UserID: uuid.NullUUID{UUID: user3.ID, Valid: true},
})
@@ -4696,11 +4698,31 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
WorkspaceOwnerID: ws1.OwnerID,
WorkspaceID: ws1.ID,
WorkspaceName: ws1.Name,
Type: database.ConnectionTypeTunnel,
ConnectionMethod: database.ConnectionLogMethodTunnel,
ConnectionStatus: database.ConnectionStatusConnected,
UserID: uuid.NullUUID{UUID: user1.ID, Valid: true},
})
agentLog := func(ago time.Duration, method database.ConnectionLogMethod, appName string) database.ConnectionLog {
return dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Time: now.Add(-ago),
OrganizationID: ws1.OrganizationID,
WorkspaceOwnerID: ws1.OwnerID,
WorkspaceID: ws1.ID,
WorkspaceName: ws1.Name,
ConnectionMethod: method,
AppNameOrPort: sql.NullString{String: appName, Valid: appName != ""},
ConnectionStatus: database.ConnectionStatusConnected,
ConnectionID: uuid.NullUUID{UUID: uuid.New(), Valid: true},
})
}
log6 := agentLog(15*time.Minute, database.ConnectionLogMethodSSH, "cursor")
log7 := agentLog(10*time.Minute, database.ConnectionLogMethodSSH, "an_unregistered_ide")
log8 := agentLog(5*time.Minute, database.ConnectionLogMethodReconnectingPTY, "")
log9 := agentLog(4*time.Minute, database.ConnectionLogMethodSSH, "goland")
// An app name reported over the web terminal.
log10 := agentLog(3*time.Minute, database.ConnectionLogMethodReconnectingPTY, "cursor")
testCases := []struct {
name string
params database.GetConnectionLogsOffsetParams
@@ -4710,7 +4732,7 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
name: "NoFilter",
params: database.GetConnectionLogsOffsetParams{},
expectedLogIDs: []uuid.UUID{
log1.ID, log2.ID, log3.ID, log4.ID, log5.ID,
log1.ID, log2.ID, log3.ID, log4.ID, log5.ID, log6.ID, log7.ID, log8.ID, log9.ID, log10.ID,
},
},
{
@@ -4725,14 +4747,14 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
params: database.GetConnectionLogsOffsetParams{
WorkspaceOwner: user1.Username,
},
expectedLogIDs: []uuid.UUID{log1.ID, log2.ID, log5.ID},
expectedLogIDs: []uuid.UUID{log1.ID, log2.ID, log5.ID, log6.ID, log7.ID, log8.ID, log9.ID, log10.ID},
},
{
name: "WorkspaceOwnerID",
params: database.GetConnectionLogsOffsetParams{
WorkspaceOwnerID: user1.ID,
},
expectedLogIDs: []uuid.UUID{log1.ID, log2.ID, log5.ID},
expectedLogIDs: []uuid.UUID{log1.ID, log2.ID, log5.ID, log6.ID, log7.ID, log8.ID, log9.ID, log10.ID},
},
{
name: "WorkspaceOwnerEmail",
@@ -4742,19 +4764,74 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
expectedLogIDs: []uuid.UUID{log3.ID, log4.ID},
},
{
name: "Type",
name: "MethodSSH",
params: database.GetConnectionLogsOffsetParams{
Type: string(database.ConnectionTypeVscode),
ConnectionMethod: string(database.ConnectionLogMethodSSH),
},
expectedLogIDs: []uuid.UUID{log2.ID, log4.ID},
expectedLogIDs: []uuid.UUID{log2.ID, log3.ID, log4.ID, log6.ID, log7.ID, log9.ID},
},
{
name: "TypeTunnel",
name: "MethodReconnectingPTY",
params: database.GetConnectionLogsOffsetParams{
Type: string(database.ConnectionTypeTunnel),
ConnectionMethod: string(database.ConnectionLogMethodReconnectingPTY),
},
expectedLogIDs: []uuid.UUID{log8.ID, log10.ID},
},
{
name: "MethodWorkspaceApp",
params: database.GetConnectionLogsOffsetParams{
ConnectionMethod: string(database.ConnectionLogMethodWorkspaceApp),
},
expectedLogIDs: []uuid.UUID{log1.ID},
},
{
name: "MethodTunnel",
params: database.GetConnectionLogsOffsetParams{
ConnectionMethod: string(database.ConnectionLogMethodTunnel),
},
expectedLogIDs: []uuid.UUID{log5.ID},
},
{
// Matches the app name over any agent method.
name: "AppNames",
params: database.GetConnectionLogsOffsetParams{
AppNames: []string{"vscode", "cursor"},
},
expectedLogIDs: []uuid.UUID{log2.ID, log4.ID, log6.ID, log10.ID},
},
{
// A workspace app slug is a destination, not the connecting app.
name: "AppNamesDoNotMatchDestination",
params: database.GetConnectionLogsOffsetParams{
AppNames: []string{"code-server"},
},
expectedLogIDs: []uuid.UUID{},
},
{
// An empty list, unlike nil, filters out every row.
name: "EmptyAppNames",
params: database.GetConnectionLogsOffsetParams{
AppNames: []string{},
},
expectedLogIDs: []uuid.UUID{},
},
{
name: "MethodAndAppNames",
params: database.GetConnectionLogsOffsetParams{
ConnectionMethod: string(database.ConnectionLogMethodSSH),
AppNames: []string{"cursor"},
},
expectedLogIDs: []uuid.UUID{log6.ID},
},
{
// An absent or unregistered app name is never excluded.
name: "MethodAndExcludedAppNames",
params: database.GetConnectionLogsOffsetParams{
ConnectionMethod: string(database.ConnectionLogMethodSSH),
ExcludedAppNames: []string{"vscode", "cursor", "goland"},
},
expectedLogIDs: []uuid.UUID{log3.ID, log7.ID},
},
{
name: "UserID",
params: database.GetConnectionLogsOffsetParams{
@@ -4781,7 +4858,7 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
params: database.GetConnectionLogsOffsetParams{
ConnectedAfter: now.Add(-90 * time.Minute), // 1.5 hours ago
},
expectedLogIDs: []uuid.UUID{log4.ID, log5.ID},
expectedLogIDs: []uuid.UUID{log4.ID, log5.ID, log6.ID, log7.ID, log8.ID, log9.ID, log10.ID},
},
{
name: "ConnectedBefore",
@@ -4809,7 +4886,8 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
params: database.GetConnectionLogsOffsetParams{
Status: string(codersdk.ConnectionLogStatusOngoing),
},
expectedLogIDs: []uuid.UUID{log4.ID},
// Web and tunnel events have no lifecycle, so they are excluded.
expectedLogIDs: []uuid.UUID{log4.ID, log6.ID, log7.ID, log8.ID, log9.ID, log10.ID},
},
{
name: "StatusCompleted",
@@ -4819,10 +4897,10 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
expectedLogIDs: []uuid.UUID{log2.ID, log3.ID},
},
{
name: "OrganizationAndTypeAndStatus",
name: "OrganizationAndAppNamesAndStatus",
params: database.GetConnectionLogsOffsetParams{
OrganizationID: orgA.Org.ID,
Type: string(database.ConnectionTypeVscode),
AppNames: []string{"vscode", "cursor"},
Status: string(codersdk.ConnectionLogStatusCompleted),
},
expectedLogIDs: []uuid.UUID{log2.ID},
@@ -4838,7 +4916,9 @@ func TestConnectionLogsOffsetFilters(t *testing.T) {
count, err := db.CountConnectionLogs(ctx, database.CountConnectionLogsParams{
OrganizationID: tc.params.OrganizationID,
WorkspaceOwner: tc.params.WorkspaceOwner,
Type: tc.params.Type,
ConnectionMethod: tc.params.ConnectionMethod,
AppNames: tc.params.AppNames,
ExcludedAppNames: tc.params.ExcludedAppNames,
UserID: tc.params.UserID,
Username: tc.params.Username,
UserEmail: tc.params.UserEmail,
@@ -4920,13 +5000,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{0},
CodeValid: []bool{false},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
@@ -4959,13 +5039,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{0},
CodeValid: []bool{false},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
@@ -4983,13 +5063,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{1},
CodeValid: []bool{true},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{"test disconnect"},
DisconnectTime: []time.Time{disconnectTime},
@@ -5025,13 +5105,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{0},
CodeValid: []bool{false},
Ip: []pqtype.Inet{ip},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
@@ -5085,13 +5165,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{0},
CodeValid: []bool{true},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{"bye"},
DisconnectTime: []time.Time{disconnectTime},
@@ -5108,13 +5188,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{0},
CodeValid: []bool{false},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
@@ -5146,13 +5226,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{code},
CodeValid: []bool{true},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{reason},
DisconnectTime: []time.Time{disconnectTime},
@@ -5177,49 +5257,45 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
"code should not be overwritten")
})
t.Run("ClientSessionIDIsWriteOnce", func(t *testing.T) {
// A later report for the same connection, such as its disconnect, cannot
// change how the connection was established or who opened it.
t.Run("ConnectionOriginIsWriteOnce", func(t *testing.T) {
t.Parallel()
db, _ := dbtestutil.NewDB(t)
ctx := context.Background()
ws := createWorkspace(t, db)
connID := uuid.New()
connectTime := dbtime.Now()
mkParams := func(id string) database.BatchUpsertConnectionLogsParams {
return database.BatchUpsertConnectionLogsParams{
ID: []uuid.UUID{uuid.New()},
ConnectTime: []time.Time{connectTime},
OrganizationID: []uuid.UUID{ws.OrganizationID},
WorkspaceOwnerID: []uuid.UUID{ws.OwnerID},
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
Code: []int32{0},
CodeValid: []bool{true},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
ClientSessionID: []string{id},
}
report := func(seed database.UpsertConnectionLogParams) database.ConnectionLog {
seed.OrganizationID = ws.OrganizationID
seed.WorkspaceOwnerID = ws.OwnerID
seed.WorkspaceID = ws.ID
seed.WorkspaceName = ws.Name
seed.AgentName = "agent"
seed.ConnectionID = uuid.NullUUID{UUID: connID, Valid: true}
return dbgen.ConnectionLog(t, db, seed)
}
err := db.BatchUpsertConnectionLogs(ctx, mkParams("0123456789abcdef0123456789abcdef"))
require.NoError(t, err)
report(database.UpsertConnectionLogParams{
ConnectionMethod: database.ConnectionLogMethodSSH,
AppNameOrPort: sql.NullString{String: "cursor", Valid: true},
ClientSessionID: sql.NullString{String: "0123456789abcdef0123456789abcdef", Valid: true},
})
disconnectTime := dbtime.Now().Add(time.Second)
report(database.UpsertConnectionLogParams{
Time: disconnectTime,
ConnectionMethod: database.ConnectionLogMethodReconnectingPTY,
AppNameOrPort: sql.NullString{String: "vscode", Valid: true},
ClientSessionID: sql.NullString{String: "fedcba9876543210fedcba9876543210", Valid: true},
ConnectionStatus: database.ConnectionStatusDisconnected,
DisconnectReason: sql.NullString{String: "bye", Valid: true},
})
// An overlapping report with no app name does not clear it either.
row := report(database.UpsertConnectionLogParams{})
err = db.BatchUpsertConnectionLogs(ctx, mkParams(""))
require.NoError(t, err)
rows, err := db.GetConnectionLogsOffset(ctx, database.GetConnectionLogsOffsetParams{LimitOpt: 10})
require.NoError(t, err)
require.Len(t, rows, 1)
row := rows[0].ConnectionLog
require.Equal(t, "0123456789abcdef0123456789abcdef", row.ClientSessionID.String,
"client_session_id should not be overwritten")
require.Equal(t, database.ConnectionLogMethodSSH, row.ConnectionMethod)
require.Equal(t, sql.NullString{String: "cursor", Valid: true}, row.AppNameOrPort)
require.Equal(t, sql.NullString{String: "0123456789abcdef0123456789abcdef", Valid: true}, row.ClientSessionID)
require.True(t, disconnectTime.Equal(row.DisconnectTime.Time))
require.Equal(t, "bye", row.DisconnectReason.String)
})
t.Run("NullConnectionIDEvents", func(t *testing.T) {
t.Parallel()
@@ -5239,13 +5315,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodWorkspaceApp},
Code: []int32{200},
CodeValid: []bool{true},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{"Mozilla/5.0"},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{"web-terminal"},
AppNameOrPort: []string{"web-terminal"},
ConnectionID: []uuid.UUID{uuid.Nil},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
@@ -5274,13 +5350,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{42},
CodeValid: []bool{true},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{uuid.New()},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
@@ -5306,13 +5382,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{0},
CodeValid: []bool{true},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{"normal"},
DisconnectTime: []time.Time{now},
@@ -5344,13 +5420,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodSSH},
Code: []int32{99},
CodeValid: []bool{false},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{""},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{""},
AppNameOrPort: []string{""},
ConnectionID: []uuid.UUID{connID},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
@@ -5383,13 +5459,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: []uuid.UUID{ws.ID},
WorkspaceName: []string{ws.Name},
AgentName: []string{"agent"},
Type: []database.ConnectionType{database.ConnectionTypeSsh},
ConnectionMethod: []database.ConnectionLogMethod{database.ConnectionLogMethodWorkspaceApp},
Code: []int32{200},
CodeValid: []bool{true},
Ip: []pqtype.Inet{defaultIP},
UserAgent: []string{"Mozilla/5.0"},
UserID: []uuid.UUID{uuid.Nil},
SlugOrPort: []string{"web-terminal"},
AppNameOrPort: []string{"web-terminal"},
ConnectionID: []uuid.UUID{uuid.Nil},
DisconnectReason: []string{""},
DisconnectTime: []time.Time{zeroTime},
@@ -5419,7 +5495,7 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
wsIDs := make([]uuid.UUID, n)
wsNames := make([]string, n)
agentNames := make([]string, n)
types := make([]database.ConnectionType, n)
methods := make([]database.ConnectionLogMethod, n)
codes := make([]int32, n)
codeValids := make([]bool, n)
ips := make([]pqtype.Inet, n)
@@ -5439,7 +5515,7 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
wsIDs[i] = ws.ID
wsNames[i] = ws.Name
agentNames[i] = "agent"
types[i] = database.ConnectionTypeSsh
methods[i] = database.ConnectionLogMethodSSH
codes[i] = 0
codeValids[i] = false
ips[i] = defaultIP
@@ -5460,13 +5536,13 @@ func TestBatchUpsertConnectionLogs(t *testing.T) {
WorkspaceID: wsIDs,
WorkspaceName: wsNames,
AgentName: agentNames,
Type: types,
ConnectionMethod: methods,
Code: codes,
CodeValid: codeValids,
Ip: ips,
UserAgent: userAgents,
UserID: userIDs,
SlugOrPort: slugOrPorts,
AppNameOrPort: slugOrPorts,
ConnectionID: connIDs,
DisconnectReason: disconnectReasons,
DisconnectTime: disconnectTimes,
+113 -77
View File
@@ -15262,9 +15262,9 @@ func (q *sqlQuerier) UpsertChatHeartbeat(ctx context.Context, arg UpsertChatHear
const batchUpsertConnectionLogs = `-- name: BatchUpsertConnectionLogs :exec
INSERT INTO connection_logs (
id, connect_time, organization_id, workspace_owner_id, workspace_id,
workspace_name, agent_name, type, code, ip, user_agent, user_id,
slug_or_port, connection_id, disconnect_reason, disconnect_time,
client_session_id
workspace_name, agent_name, connection_method, code, ip, user_agent, user_id,
app_name_or_port, connection_id, disconnect_reason, disconnect_time,
client_session_id
)
SELECT
u.id,
@@ -15274,14 +15274,14 @@ SELECT
u.workspace_id,
u.workspace_name,
u.agent_name,
u.type,
u.connection_method,
-- Use the validity flag to distinguish "no code" (NULL) from a
-- legitimate zero exit code.
CASE WHEN u.code_valid THEN u.code ELSE NULL END,
u.ip,
NULLIF(u.user_agent, ''),
NULLIF(u.user_id, '00000000-0000-0000-0000-000000000000'::uuid),
NULLIF(u.slug_or_port, ''),
NULLIF(u.app_name_or_port, ''),
NULLIF(u.connection_id, '00000000-0000-0000-0000-000000000000'::uuid),
NULLIF(u.disconnect_reason, ''),
NULLIF(u.disconnect_time, '0001-01-01 00:00:00Z'::timestamptz),
@@ -15295,13 +15295,13 @@ FROM (
unnest($5::uuid[]) AS workspace_id,
unnest($6::text[]) AS workspace_name,
unnest($7::text[]) AS agent_name,
unnest($8::connection_type[]) AS type,
unnest($8::connection_log_method[]) AS connection_method,
unnest($9::int4[]) AS code,
unnest($10::bool[]) AS code_valid,
unnest($11::inet[]) AS ip,
unnest($12::text[]) AS user_agent,
unnest($13::uuid[]) AS user_id,
unnest($14::text[]) AS slug_or_port,
unnest($14::text[]) AS app_name_or_port,
unnest($15::uuid[]) AS connection_id,
unnest($16::text[]) AS disconnect_reason,
unnest($17::timestamptz[]) AS disconnect_time,
@@ -15337,24 +15337,24 @@ DO UPDATE SET
`
type BatchUpsertConnectionLogsParams struct {
ID []uuid.UUID `db:"id" json:"id"`
ConnectTime []time.Time `db:"connect_time" json:"connect_time"`
OrganizationID []uuid.UUID `db:"organization_id" json:"organization_id"`
WorkspaceOwnerID []uuid.UUID `db:"workspace_owner_id" json:"workspace_owner_id"`
WorkspaceID []uuid.UUID `db:"workspace_id" json:"workspace_id"`
WorkspaceName []string `db:"workspace_name" json:"workspace_name"`
AgentName []string `db:"agent_name" json:"agent_name"`
Type []ConnectionType `db:"type" json:"type"`
Code []int32 `db:"code" json:"code"`
CodeValid []bool `db:"code_valid" json:"code_valid"`
Ip []pqtype.Inet `db:"ip" json:"ip"`
UserAgent []string `db:"user_agent" json:"user_agent"`
UserID []uuid.UUID `db:"user_id" json:"user_id"`
SlugOrPort []string `db:"slug_or_port" json:"slug_or_port"`
ConnectionID []uuid.UUID `db:"connection_id" json:"connection_id"`
DisconnectReason []string `db:"disconnect_reason" json:"disconnect_reason"`
DisconnectTime []time.Time `db:"disconnect_time" json:"disconnect_time"`
ClientSessionID []string `db:"client_session_id" json:"client_session_id"`
ID []uuid.UUID `db:"id" json:"id"`
ConnectTime []time.Time `db:"connect_time" json:"connect_time"`
OrganizationID []uuid.UUID `db:"organization_id" json:"organization_id"`
WorkspaceOwnerID []uuid.UUID `db:"workspace_owner_id" json:"workspace_owner_id"`
WorkspaceID []uuid.UUID `db:"workspace_id" json:"workspace_id"`
WorkspaceName []string `db:"workspace_name" json:"workspace_name"`
AgentName []string `db:"agent_name" json:"agent_name"`
ConnectionMethod []ConnectionLogMethod `db:"connection_method" json:"connection_method"`
Code []int32 `db:"code" json:"code"`
CodeValid []bool `db:"code_valid" json:"code_valid"`
Ip []pqtype.Inet `db:"ip" json:"ip"`
UserAgent []string `db:"user_agent" json:"user_agent"`
UserID []uuid.UUID `db:"user_id" json:"user_id"`
AppNameOrPort []string `db:"app_name_or_port" json:"app_name_or_port"`
ConnectionID []uuid.UUID `db:"connection_id" json:"connection_id"`
DisconnectReason []string `db:"disconnect_reason" json:"disconnect_reason"`
DisconnectTime []time.Time `db:"disconnect_time" json:"disconnect_time"`
ClientSessionID []string `db:"client_session_id" json:"client_session_id"`
}
func (q *sqlQuerier) BatchUpsertConnectionLogs(ctx context.Context, arg BatchUpsertConnectionLogsParams) error {
@@ -15366,13 +15366,13 @@ func (q *sqlQuerier) BatchUpsertConnectionLogs(ctx context.Context, arg BatchUps
pq.Array(arg.WorkspaceID),
pq.Array(arg.WorkspaceName),
pq.Array(arg.AgentName),
pq.Array(arg.Type),
pq.Array(arg.ConnectionMethod),
pq.Array(arg.Code),
pq.Array(arg.CodeValid),
pq.Array(arg.Ip),
pq.Array(arg.UserAgent),
pq.Array(arg.UserID),
pq.Array(arg.SlugOrPort),
pq.Array(arg.AppNameOrPort),
pq.Array(arg.ConnectionID),
pq.Array(arg.DisconnectReason),
pq.Array(arg.DisconnectTime),
@@ -15423,72 +15423,86 @@ SELECT COUNT(*) AS count FROM (
)
ELSE true
END
-- Filter by type
-- Filter by connection_method
AND CASE
WHEN $5 :: text != '' THEN
type = $5 :: connection_type
connection_method = $5 :: connection_log_method
ELSE true
END
-- Filter by client app. NULL skips this filter, and an empty list matches
-- nothing. Other methods store a destination in app_name_or_port.
AND CASE
WHEN $6 :: text[] IS NOT NULL THEN
connection_method IN ('ssh', 'reconnecting_pty') AND app_name_or_port = ANY($6 :: text[])
ELSE true
END
-- Only the legacy type:ssh filter excludes apps. Remove this with that
-- filter and ConnectionLog.Type.
AND CASE
WHEN cardinality($7 :: text[]) > 0 THEN
connection_method IN ('ssh', 'reconnecting_pty') AND (app_name_or_port IS NULL OR app_name_or_port != ALL($7 :: text[]))
ELSE true
END
-- Filter by user_id
AND CASE
WHEN $6 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
user_id = $6
WHEN $8 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
user_id = $8
ELSE true
END
-- Filter by username
AND CASE
WHEN $7 :: text != '' THEN
WHEN $9 :: text != '' THEN
user_id = (
SELECT id FROM users
WHERE lower(username) = lower($7) AND deleted = false
WHERE lower(username) = lower($9) AND deleted = false
)
ELSE true
END
-- Filter by user_email
AND CASE
WHEN $8 :: text != '' THEN
users.email = $8
WHEN $10 :: text != '' THEN
users.email = $10
ELSE true
END
-- Filter by connected_after
AND CASE
WHEN $9 :: timestamp with time zone != '0001-01-01 00:00:00Z' THEN
connect_time >= $9
WHEN $11 :: timestamp with time zone != '0001-01-01 00:00:00Z' THEN
connect_time >= $11
ELSE true
END
-- Filter by connected_before
AND CASE
WHEN $10 :: timestamp with time zone != '0001-01-01 00:00:00Z' THEN
connect_time <= $10
WHEN $12 :: timestamp with time zone != '0001-01-01 00:00:00Z' THEN
connect_time <= $12
ELSE true
END
-- Filter by workspace_id
AND CASE
WHEN $11 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
connection_logs.workspace_id = $11
WHEN $13 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
connection_logs.workspace_id = $13
ELSE true
END
-- Filter by connection_id
AND CASE
WHEN $12 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
connection_logs.connection_id = $12
WHEN $14 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
connection_logs.connection_id = $14
ELSE true
END
-- Filter by whether the session has a disconnect_time
AND CASE
WHEN $13 :: text != '' THEN
(($13 = 'ongoing' AND disconnect_time IS NULL) OR
($13 = 'completed' AND disconnect_time IS NOT NULL)) AND
WHEN $15 :: text != '' THEN
(($15 = 'ongoing' AND disconnect_time IS NULL) OR
($15 = 'completed' AND disconnect_time IS NOT NULL)) AND
-- Exclude point-in-time events reported by coderd, since we
-- don't know their close time.
"type" NOT IN ('workspace_app', 'port_forwarding', 'tunnel')
connection_method IN ('ssh', 'reconnecting_pty')
ELSE true
END
-- Authorize Filter clause will be injected below in
-- CountAuthorizedConnectionLogs
-- @authorize_filter
-- NOTE: See the CountAuditLogs LIMIT note.
LIMIT NULLIF($14::int, 0) + 1
LIMIT NULLIF($16::int, 0) + 1
) AS limited_count
`
@@ -15497,7 +15511,9 @@ type CountConnectionLogsParams struct {
WorkspaceOwner string `db:"workspace_owner" json:"workspace_owner"`
WorkspaceOwnerID uuid.UUID `db:"workspace_owner_id" json:"workspace_owner_id"`
WorkspaceOwnerEmail string `db:"workspace_owner_email" json:"workspace_owner_email"`
Type string `db:"type" json:"type"`
ConnectionMethod string `db:"connection_method" json:"connection_method"`
AppNames []string `db:"app_names" json:"app_names"`
ExcludedAppNames []string `db:"excluded_app_names" json:"excluded_app_names"`
UserID uuid.UUID `db:"user_id" json:"user_id"`
Username string `db:"username" json:"username"`
UserEmail string `db:"user_email" json:"user_email"`
@@ -15515,7 +15531,9 @@ func (q *sqlQuerier) CountConnectionLogs(ctx context.Context, arg CountConnectio
arg.WorkspaceOwner,
arg.WorkspaceOwnerID,
arg.WorkspaceOwnerEmail,
arg.Type,
arg.ConnectionMethod,
pq.Array(arg.AppNames),
pq.Array(arg.ExcludedAppNames),
arg.UserID,
arg.Username,
arg.UserEmail,
@@ -15559,7 +15577,7 @@ func (q *sqlQuerier) DeleteOldConnectionLogs(ctx context.Context, arg DeleteOldC
const getConnectionLogsOffset = `-- name: GetConnectionLogsOffset :many
SELECT
connection_logs.id, connection_logs.connect_time, connection_logs.organization_id, connection_logs.workspace_owner_id, connection_logs.workspace_id, connection_logs.workspace_name, connection_logs.agent_name, connection_logs.type, connection_logs.ip, connection_logs.code, connection_logs.user_agent, connection_logs.user_id, connection_logs.slug_or_port, connection_logs.connection_id, connection_logs.disconnect_time, connection_logs.disconnect_reason, connection_logs.client_session_id,
connection_logs.id, connection_logs.connect_time, connection_logs.organization_id, connection_logs.workspace_owner_id, connection_logs.workspace_id, connection_logs.workspace_name, connection_logs.agent_name, connection_logs.connection_method, connection_logs.ip, connection_logs.code, connection_logs.user_agent, connection_logs.user_id, connection_logs.app_name_or_port, connection_logs.connection_id, connection_logs.disconnect_time, connection_logs.disconnect_reason, connection_logs.client_session_id,
-- sqlc.embed(users) would be nice but it does not seem to play well with
-- left joins. This user metadata is necessary for parity with the audit logs
-- API.
@@ -15618,65 +15636,79 @@ WHERE
)
ELSE true
END
-- Filter by type
-- Filter by connection_method
AND CASE
WHEN $5 :: text != '' THEN
type = $5 :: connection_type
connection_method = $5 :: connection_log_method
ELSE true
END
-- Filter by client app. NULL skips this filter, and an empty list matches
-- nothing. Other methods store a destination in app_name_or_port.
AND CASE
WHEN $6 :: text[] IS NOT NULL THEN
connection_method IN ('ssh', 'reconnecting_pty') AND app_name_or_port = ANY($6 :: text[])
ELSE true
END
-- Only the legacy type:ssh filter excludes apps. Remove this with that
-- filter and ConnectionLog.Type.
AND CASE
WHEN cardinality($7 :: text[]) > 0 THEN
connection_method IN ('ssh', 'reconnecting_pty') AND (app_name_or_port IS NULL OR app_name_or_port != ALL($7 :: text[]))
ELSE true
END
-- Filter by user_id
AND CASE
WHEN $6 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
user_id = $6
WHEN $8 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
user_id = $8
ELSE true
END
-- Filter by username
AND CASE
WHEN $7 :: text != '' THEN
WHEN $9 :: text != '' THEN
user_id = (
SELECT id FROM users
WHERE lower(username) = lower($7) AND deleted = false
WHERE lower(username) = lower($9) AND deleted = false
)
ELSE true
END
-- Filter by user_email
AND CASE
WHEN $8 :: text != '' THEN
users.email = $8
WHEN $10 :: text != '' THEN
users.email = $10
ELSE true
END
-- Filter by connected_after
AND CASE
WHEN $9 :: timestamp with time zone != '0001-01-01 00:00:00Z' THEN
connect_time >= $9
WHEN $11 :: timestamp with time zone != '0001-01-01 00:00:00Z' THEN
connect_time >= $11
ELSE true
END
-- Filter by connected_before
AND CASE
WHEN $10 :: timestamp with time zone != '0001-01-01 00:00:00Z' THEN
connect_time <= $10
WHEN $12 :: timestamp with time zone != '0001-01-01 00:00:00Z' THEN
connect_time <= $12
ELSE true
END
-- Filter by workspace_id
AND CASE
WHEN $11 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
connection_logs.workspace_id = $11
WHEN $13 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
connection_logs.workspace_id = $13
ELSE true
END
-- Filter by connection_id
AND CASE
WHEN $12 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
connection_logs.connection_id = $12
WHEN $14 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN
connection_logs.connection_id = $14
ELSE true
END
-- Filter by whether the session has a disconnect_time
AND CASE
WHEN $13 :: text != '' THEN
(($13 = 'ongoing' AND disconnect_time IS NULL) OR
($13 = 'completed' AND disconnect_time IS NOT NULL)) AND
WHEN $15 :: text != '' THEN
(($15 = 'ongoing' AND disconnect_time IS NULL) OR
($15 = 'completed' AND disconnect_time IS NOT NULL)) AND
-- Exclude point-in-time events reported by coderd, since we
-- don't know their close time.
"type" NOT IN ('workspace_app', 'port_forwarding', 'tunnel')
connection_method IN ('ssh', 'reconnecting_pty')
ELSE true
END
-- Authorize Filter clause will be injected below in
@@ -15688,9 +15720,9 @@ LIMIT
-- a limit of 0 means "no limit". The connection log table is unbounded
-- in size, and is expected to be quite large. Implement a default
-- limit of 100 to prevent accidental excessively large queries.
COALESCE(NULLIF($15 :: int, 0), 100)
COALESCE(NULLIF($17 :: int, 0), 100)
OFFSET
$14
$16
`
type GetConnectionLogsOffsetParams struct {
@@ -15698,7 +15730,9 @@ type GetConnectionLogsOffsetParams struct {
WorkspaceOwner string `db:"workspace_owner" json:"workspace_owner"`
WorkspaceOwnerID uuid.UUID `db:"workspace_owner_id" json:"workspace_owner_id"`
WorkspaceOwnerEmail string `db:"workspace_owner_email" json:"workspace_owner_email"`
Type string `db:"type" json:"type"`
ConnectionMethod string `db:"connection_method" json:"connection_method"`
AppNames []string `db:"app_names" json:"app_names"`
ExcludedAppNames []string `db:"excluded_app_names" json:"excluded_app_names"`
UserID uuid.UUID `db:"user_id" json:"user_id"`
Username string `db:"username" json:"username"`
UserEmail string `db:"user_email" json:"user_email"`
@@ -15737,7 +15771,9 @@ func (q *sqlQuerier) GetConnectionLogsOffset(ctx context.Context, arg GetConnect
arg.WorkspaceOwner,
arg.WorkspaceOwnerID,
arg.WorkspaceOwnerEmail,
arg.Type,
arg.ConnectionMethod,
pq.Array(arg.AppNames),
pq.Array(arg.ExcludedAppNames),
arg.UserID,
arg.Username,
arg.UserEmail,
@@ -15764,12 +15800,12 @@ func (q *sqlQuerier) GetConnectionLogsOffset(ctx context.Context, arg GetConnect
&i.ConnectionLog.WorkspaceID,
&i.ConnectionLog.WorkspaceName,
&i.ConnectionLog.AgentName,
&i.ConnectionLog.Type,
&i.ConnectionLog.ConnectionMethod,
&i.ConnectionLog.Ip,
&i.ConnectionLog.Code,
&i.ConnectionLog.UserAgent,
&i.ConnectionLog.UserID,
&i.ConnectionLog.SlugOrPort,
&i.ConnectionLog.AppNameOrPort,
&i.ConnectionLog.ConnectionID,
&i.ConnectionLog.DisconnectTime,
&i.ConnectionLog.DisconnectReason,
+43 -15
View File
@@ -59,10 +59,24 @@ WHERE
)
ELSE true
END
-- Filter by type
-- Filter by connection_method
AND CASE
WHEN @type :: text != '' THEN
type = @type :: connection_type
WHEN @connection_method :: text != '' THEN
connection_method = @connection_method :: connection_log_method
ELSE true
END
-- Filter by client app. NULL skips this filter, and an empty list matches
-- nothing. Other methods store a destination in app_name_or_port.
AND CASE
WHEN @app_names :: text[] IS NOT NULL THEN
connection_method IN ('ssh', 'reconnecting_pty') AND app_name_or_port = ANY(@app_names :: text[])
ELSE true
END
-- Only the legacy type:ssh filter excludes apps. Remove this with that
-- filter and ConnectionLog.Type.
AND CASE
WHEN cardinality(@excluded_app_names :: text[]) > 0 THEN
connection_method IN ('ssh', 'reconnecting_pty') AND (app_name_or_port IS NULL OR app_name_or_port != ALL(@excluded_app_names :: text[]))
ELSE true
END
-- Filter by user_id
@@ -117,7 +131,7 @@ WHERE
(@status = 'completed' AND disconnect_time IS NOT NULL)) AND
-- Exclude point-in-time events reported by coderd, since we
-- don't know their close time.
"type" NOT IN ('workspace_app', 'port_forwarding', 'tunnel')
connection_method IN ('ssh', 'reconnecting_pty')
ELSE true
END
-- Authorize Filter clause will be injected below in
@@ -175,10 +189,24 @@ SELECT COUNT(*) AS count FROM (
)
ELSE true
END
-- Filter by type
-- Filter by connection_method
AND CASE
WHEN @type :: text != '' THEN
type = @type :: connection_type
WHEN @connection_method :: text != '' THEN
connection_method = @connection_method :: connection_log_method
ELSE true
END
-- Filter by client app. NULL skips this filter, and an empty list matches
-- nothing. Other methods store a destination in app_name_or_port.
AND CASE
WHEN @app_names :: text[] IS NOT NULL THEN
connection_method IN ('ssh', 'reconnecting_pty') AND app_name_or_port = ANY(@app_names :: text[])
ELSE true
END
-- Only the legacy type:ssh filter excludes apps. Remove this with that
-- filter and ConnectionLog.Type.
AND CASE
WHEN cardinality(@excluded_app_names :: text[]) > 0 THEN
connection_method IN ('ssh', 'reconnecting_pty') AND (app_name_or_port IS NULL OR app_name_or_port != ALL(@excluded_app_names :: text[]))
ELSE true
END
-- Filter by user_id
@@ -233,7 +261,7 @@ SELECT COUNT(*) AS count FROM (
(@status = 'completed' AND disconnect_time IS NOT NULL)) AND
-- Exclude point-in-time events reported by coderd, since we
-- don't know their close time.
"type" NOT IN ('workspace_app', 'port_forwarding', 'tunnel')
connection_method IN ('ssh', 'reconnecting_pty')
ELSE true
END
-- Authorize Filter clause will be injected below in
@@ -258,9 +286,9 @@ WHERE connection_logs.id = old_logs.id;
-- name: BatchUpsertConnectionLogs :exec
INSERT INTO connection_logs (
id, connect_time, organization_id, workspace_owner_id, workspace_id,
workspace_name, agent_name, type, code, ip, user_agent, user_id,
slug_or_port, connection_id, disconnect_reason, disconnect_time,
client_session_id
workspace_name, agent_name, connection_method, code, ip, user_agent, user_id,
app_name_or_port, connection_id, disconnect_reason, disconnect_time,
client_session_id
)
SELECT
u.id,
@@ -270,14 +298,14 @@ SELECT
u.workspace_id,
u.workspace_name,
u.agent_name,
u.type,
u.connection_method,
-- Use the validity flag to distinguish "no code" (NULL) from a
-- legitimate zero exit code.
CASE WHEN u.code_valid THEN u.code ELSE NULL END,
u.ip,
NULLIF(u.user_agent, ''),
NULLIF(u.user_id, '00000000-0000-0000-0000-000000000000'::uuid),
NULLIF(u.slug_or_port, ''),
NULLIF(u.app_name_or_port, ''),
NULLIF(u.connection_id, '00000000-0000-0000-0000-000000000000'::uuid),
NULLIF(u.disconnect_reason, ''),
NULLIF(u.disconnect_time, '0001-01-01 00:00:00Z'::timestamptz),
@@ -291,13 +319,13 @@ FROM (
unnest(sqlc.arg('workspace_id')::uuid[]) AS workspace_id,
unnest(sqlc.arg('workspace_name')::text[]) AS workspace_name,
unnest(sqlc.arg('agent_name')::text[]) AS agent_name,
unnest(sqlc.arg('type')::connection_type[]) AS type,
unnest(sqlc.arg('connection_method')::connection_log_method[]) AS connection_method,
unnest(sqlc.arg('code')::int4[]) AS code,
unnest(sqlc.arg('code_valid')::bool[]) AS code_valid,
unnest(sqlc.arg('ip')::inet[]) AS ip,
unnest(sqlc.arg('user_agent')::text[]) AS user_agent,
unnest(sqlc.arg('user_id')::uuid[]) AS user_id,
unnest(sqlc.arg('slug_or_port')::text[]) AS slug_or_port,
unnest(sqlc.arg('app_name_or_port')::text[]) AS app_name_or_port,
unnest(sqlc.arg('connection_id')::uuid[]) AS connection_id,
unnest(sqlc.arg('disconnect_reason')::text[]) AS disconnect_reason,
unnest(sqlc.arg('disconnect_time')::timestamptz[]) AS disconnect_time,
+21
View File
@@ -2,6 +2,9 @@
package sdk2db
import (
"golang.org/x/xerrors"
agentproto "github.com/coder/coder/v2/agent/proto"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
@@ -14,3 +17,21 @@ func ProvisionerDaemonStatus(status codersdk.ProvisionerDaemonStatus) database.P
func ProvisionerDaemonStatuses(params []codersdk.ProvisionerDaemonStatus) []database.ProvisionerDaemonStatus {
return slice.List(params, ProvisionerDaemonStatus)
}
// ConnectionLogFromAgentType recovers the method and app name from legacy
// reports.
// An unspecified legacy type was used by SSH handlers for unfamiliar apps.
func ConnectionLogFromAgentType(typ agentproto.Connection_Type) (database.ConnectionLogMethod, string, error) {
switch typ {
case agentproto.Connection_SSH, agentproto.Connection_TYPE_UNSPECIFIED:
return database.ConnectionLogMethodSSH, "", nil
case agentproto.Connection_JETBRAINS:
return database.ConnectionLogMethodSSH, "jetbrains", nil
case agentproto.Connection_VSCODE:
return database.ConnectionLogMethodSSH, "vscode", nil
case agentproto.Connection_RECONNECTING_PTY:
return database.ConnectionLogMethodReconnectingPTY, "", nil
default:
return "", "", xerrors.Errorf("unsupported agent connection type %d", typ)
}
}
+28
View File
@@ -3,6 +3,9 @@ package sdk2db_test
import (
"testing"
"github.com/stretchr/testify/require"
agentproto "github.com/coder/coder/v2/agent/proto"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/sdk2db"
"github.com/coder/coder/v2/codersdk"
@@ -34,3 +37,28 @@ func TestProvisionerDaemonStatus(t *testing.T) {
})
}
}
func TestConnectionLogFromAgentType(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
typ agentproto.Connection_Type
method database.ConnectionLogMethod
appName string
}{
{agentproto.Connection_SSH, database.ConnectionLogMethodSSH, ""},
// SSH handlers reported unfamiliar apps as unspecified.
{agentproto.Connection_TYPE_UNSPECIFIED, database.ConnectionLogMethodSSH, ""},
{agentproto.Connection_VSCODE, database.ConnectionLogMethodSSH, "vscode"},
{agentproto.Connection_JETBRAINS, database.ConnectionLogMethodSSH, "jetbrains"},
{agentproto.Connection_RECONNECTING_PTY, database.ConnectionLogMethodReconnectingPTY, ""},
} {
method, appName, err := sdk2db.ConnectionLogFromAgentType(tc.typ)
require.NoError(t, err, tc.typ)
require.Equal(t, tc.method, method, tc.typ)
require.Equal(t, tc.appName, appName, tc.typ)
}
_, _, err := sdk2db.ConnectionLogFromAgentType(agentproto.Connection_Type(1000))
require.Error(t, err)
}
+2
View File
@@ -199,6 +199,8 @@ sql:
type: "NullDecimal"
package: "decimal"
rename:
connection_log_method_ssh: ConnectionLogMethodSSH
connection_log_method_reconnecting_pty: ConnectionLogMethodReconnectingPTY
ai_provider_id: AIProviderID
chat: ChatTable
chats_expanded: Chat
+59 -10
View File
@@ -104,7 +104,6 @@ func ConnectionLogs(ctx context.Context, db database.Store, query string, apiKey
OrganizationID: parseOrganization(ctx, db, parser, values, "organization"),
WorkspaceOwner: parser.String(values, "", "workspace_owner"),
WorkspaceOwnerEmail: parser.String(values, "", "workspace_owner_email"),
Type: string(httpapi.ParseCustom(parser, values, "", "type", httpapi.ParseEnum[database.ConnectionType])),
Username: parser.String(values, "", "username"),
UserEmail: parser.String(values, "", "user_email"),
ConnectedAfter: parser.Time3339Nano(values, time.Time{}, "connected_after"),
@@ -112,6 +111,25 @@ func ConnectionLogs(ctx context.Context, db database.Store, query string, apiKey
WorkspaceID: parser.UUID(values, uuid.Nil, "workspace_id"),
ConnectionID: parser.UUID(values, uuid.Nil, "connection_id"),
Status: string(httpapi.ParseCustom(parser, values, "", "status", httpapi.ParseEnum[codersdk.ConnectionLogStatus])),
ConnectionMethod: string(httpapi.ParseCustom(parser, values, "", "method", httpapi.ParseEnum[codersdk.ConnectionLogMethod])),
}
apps := parser.Strings(values, nil, "app")
typ := httpapi.ParseCustom(parser, values, "", "type", httpapi.ParseEnum[codersdk.ConnectionType])
switch {
case typ != "" && (filter.ConnectionMethod != "" || len(apps) > 0):
parser.Errors = append(parser.Errors, codersdk.ValidationError{
Field: "type",
Detail: "type cannot be combined with method or app",
})
case typ != "":
applyConnectionTypeFilter(&filter, typ)
case len(apps) > 0:
// Repeated app terms match any of the apps.
for i, app := range apps {
apps[i] = codersdk.NormalizeAppName(app)
}
slices.Sort(apps)
filter.AppNames = slices.Compact(apps)
}
if filter.Username == "me" {
@@ -131,20 +149,51 @@ func ConnectionLogs(ctx context.Context, db database.Store, query string, apiKey
WorkspaceOwner: filter.WorkspaceOwner,
WorkspaceOwnerID: filter.WorkspaceOwnerID,
WorkspaceOwnerEmail: filter.WorkspaceOwnerEmail,
Type: filter.Type,
UserID: filter.UserID,
Username: filter.Username,
UserEmail: filter.UserEmail,
ConnectedAfter: filter.ConnectedAfter,
ConnectedBefore: filter.ConnectedBefore,
WorkspaceID: filter.WorkspaceID,
ConnectionID: filter.ConnectionID,
Status: filter.Status,
ConnectionMethod: filter.ConnectionMethod,
AppNames: filter.AppNames,
ExcludedAppNames: filter.ExcludedAppNames,
UserID: filter.UserID,
Username: filter.Username,
UserEmail: filter.UserEmail,
ConnectedAfter: filter.ConnectedAfter,
ConnectedBefore: filter.ConnectedBefore,
WorkspaceID: filter.WorkspaceID,
ConnectionID: filter.ConnectionID,
Status: filter.Status,
}
parser.ErrorExcessParams(values)
return filter, countFilter, parser.Errors
}
// applyConnectionTypeFilter translates the legacy type filter. It mirrors
// db2sdk.ConnectionLogType so a row matches the type it is returned with.
// Remove it, ExcludedAppNames, and ConnectionLog.Type together.
func applyConnectionTypeFilter(filter *database.GetConnectionLogsOffsetParams, typ codersdk.ConnectionType) {
switch typ {
case codersdk.ConnectionTypeVSCode, codersdk.ConnectionTypeJetBrains:
filter.ConnectionMethod = string(database.ConnectionLogMethodSSH)
filter.AppNames = appsInFamily(codersdk.AppFamilyName(typ))
case codersdk.ConnectionTypeSSH:
// Plain SSH also matches absent and unregistered apps.
filter.ConnectionMethod = string(database.ConnectionLogMethodSSH)
filter.ExcludedAppNames = slices.Concat(appsInFamily(codersdk.AppFamilyVSCode), appsInFamily(codersdk.AppFamilyJetBrains))
default:
filter.ConnectionMethod = string(typ)
}
}
func appsInFamily(family codersdk.AppFamilyName) []string {
var apps []string
for appName, appFamily := range codersdk.SessionCountAppFamilies() {
if appFamily == family {
apps = append(apps, appName)
}
}
slices.Sort(apps)
return apps
}
func Users(query string) (database.GetUsersParams, []codersdk.ValidationError) {
// Always lowercase for all searches.
query = strings.ToLower(query)
+77 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
"slices"
"strings"
"testing"
"time"
@@ -669,7 +670,7 @@ func TestSearchConnectionLogs(t *testing.T) {
OrganizationID: orgID,
WorkspaceOwner: "testowner",
WorkspaceOwnerEmail: "owner@example.com",
Type: string(database.ConnectionTypePortForwarding),
ConnectionMethod: string(database.ConnectionLogMethodPortForwarding),
Username: "testuser",
UserEmail: "test@example.com",
ConnectedAfter: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
@@ -682,6 +683,81 @@ func TestSearchConnectionLogs(t *testing.T) {
require.Equal(t, expected, values)
})
// type: is the legacy filter. No query has an organization term, so no
// database is needed.
t.Run("Type", func(t *testing.T) {
t.Parallel()
parse := func(q string) database.GetConnectionLogsOffsetParams {
values, count, errs := searchquery.ConnectionLogs(context.Background(), nil, q, database.APIKey{})
require.Len(t, errs, 0, q)
require.Equal(t, values.ConnectionMethod, count.ConnectionMethod, q)
require.Equal(t, values.AppNames, count.AppNames, q)
require.Equal(t, values.ExcludedAppNames, count.ExcludedAppNames, q)
return values
}
// The families grow, so check membership rather than the list.
vscode := parse("type:vscode")
require.Equal(t, string(database.ConnectionLogMethodSSH), vscode.ConnectionMethod)
require.Contains(t, vscode.AppNames, "cursor")
require.NotContains(t, vscode.AppNames, "goland")
require.Empty(t, vscode.ExcludedAppNames)
jetbrains := parse("type:jetbrains")
require.Contains(t, jetbrains.AppNames, "goland")
require.NotContains(t, jetbrains.AppNames, "cursor")
// Plain SSH also matches absent and unregistered apps.
ssh := parse("type:ssh")
require.Equal(t, string(database.ConnectionLogMethodSSH), ssh.ConnectionMethod)
require.Empty(t, ssh.AppNames)
require.ElementsMatch(t, slices.Concat(vscode.AppNames, jetbrains.AppNames), ssh.ExcludedAppNames)
pty := parse("type:reconnecting_pty")
require.Equal(t, string(database.ConnectionLogMethodReconnectingPTY), pty.ConnectionMethod)
require.Empty(t, pty.AppNames)
require.Empty(t, pty.ExcludedAppNames)
// An app is not a type, and type cannot be combined with its replacements.
for _, q := range []string{"type:cursor", "type:unknown", "type:ssh method:ssh", "type:vscode app:cursor"} {
_, _, errs := searchquery.ConnectionLogs(context.Background(), nil, q, database.APIKey{})
require.Len(t, errs, 1, q)
}
})
t.Run("Method", func(t *testing.T) {
t.Parallel()
values, count, errs := searchquery.ConnectionLogs(context.Background(), nil, "method:reconnecting_pty", database.APIKey{})
require.Len(t, errs, 0)
require.Equal(t, string(database.ConnectionLogMethodReconnectingPTY), values.ConnectionMethod)
require.Equal(t, values.ConnectionMethod, count.ConnectionMethod)
// A legacy type is not a method.
for _, q := range []string{"method:vscode", "method:unknown"} {
_, _, errs = searchquery.ConnectionLogs(context.Background(), nil, q, database.APIKey{})
require.Len(t, errs, 1, q)
}
})
// app: matches the normalized name of the connecting application.
t.Run("App", func(t *testing.T) {
t.Parallel()
values, count, errs := searchquery.ConnectionLogs(context.Background(), nil, "app:Code-Server", database.APIKey{})
require.Len(t, errs, 0)
require.Equal(t, []string{"code_server"}, values.AppNames)
require.Equal(t, values.AppNames, count.AppNames)
// Repeated app terms match any of them.
values, count, errs = searchquery.ConnectionLogs(context.Background(), nil, "app:vscode app:Cursor app:cursor method:ssh", database.APIKey{})
require.Len(t, errs, 0)
require.Equal(t, []string{"cursor", "vscode"}, values.AppNames)
require.Equal(t, values.AppNames, count.AppNames)
require.Equal(t, string(database.ConnectionLogMethodSSH), values.ConnectionMethod)
})
t.Run("Me", func(t *testing.T) {
t.Parallel()
+2 -2
View File
@@ -1501,12 +1501,12 @@ func (api *API) logTunnelConnection(agentID uuid.UUID, statusCode int32, userID
WorkspaceID: waws.WorkspaceTable.ID,
WorkspaceName: waws.WorkspaceTable.Name,
AgentName: waws.WorkspaceAgent.Name,
Type: database.ConnectionTypeTunnel,
ConnectionMethod: database.ConnectionLogMethodTunnel,
IP: database.ParseIP(ip),
Code: sql.NullInt32{Int32: statusCode, Valid: true},
UserAgent: sql.NullString{String: userAgent, Valid: userAgent != ""},
UserID: uuid.NullUUID{UUID: userID, Valid: userID != uuid.Nil},
SlugOrPort: sql.NullString{},
AppNameOrPort: sql.NullString{},
ConnectionID: uuid.NullUUID{},
DisconnectReason: sql.NullString{},
ConnectionStatus: database.ConnectionStatusConnected,
+3 -3
View File
@@ -953,7 +953,7 @@ func TestWorkspaceAgentClientCoordinate_ConnectionLog(t *testing.T) {
WorkspaceID: r.Workspace.ID,
WorkspaceName: r.Workspace.Name,
AgentName: resources[0].Agents[0].Name,
Type: database.ConnectionTypeTunnel,
ConnectionMethod: database.ConnectionLogMethodTunnel,
Code: sql.NullInt32{
Int32: http.StatusSwitchingProtocols,
Valid: true,
@@ -3137,7 +3137,7 @@ func TestUserTailnetConnectionLog(t *testing.T) {
return connLogger.Contains(t, database.UpsertConnectionLogParams{
WorkspaceID: allowedWorkspace.ID,
AgentName: allowedSDKWorkspace.LatestBuild.Resources[0].Agents[0].Name,
Type: database.ConnectionTypeTunnel,
ConnectionMethod: database.ConnectionLogMethodTunnel,
Code: sql.NullInt32{Int32: http.StatusSwitchingProtocols, Valid: true},
UserID: uuid.NullUUID{UUID: memberUser.ID, Valid: true},
UserAgent: sql.NullString{},
@@ -3154,7 +3154,7 @@ func TestUserTailnetConnectionLog(t *testing.T) {
return connLogger.Contains(t, database.UpsertConnectionLogParams{
WorkspaceID: deniedWorkspace.ID,
AgentName: deniedSDKWorkspace.LatestBuild.Resources[0].Agents[0].Name,
Type: database.ConnectionTypeTunnel,
ConnectionMethod: database.ConnectionLogMethodTunnel,
Code: sql.NullInt32{Int32: http.StatusForbidden, Valid: true},
UserID: uuid.NullUUID{UUID: memberUser.ID, Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
+6 -6
View File
@@ -452,18 +452,18 @@ func (p *DBTokenProvider) connLogInitRequest(w http.ResponseWriter, r *http.Requ
}
var (
connType database.ConnectionType
method database.ConnectionLogMethod
slugOrPort = aReq.dbReq.AppSlugOrPort
)
switch {
case aReq.dbReq.AccessMethod == AccessMethodTerminal:
connType = database.ConnectionTypeWorkspaceApp
method = database.ConnectionLogMethodWorkspaceApp
slugOrPort = "terminal"
case aReq.dbReq.App.ID == uuid.Nil:
connType = database.ConnectionTypePortForwarding
method = database.ConnectionLogMethodPortForwarding
default:
connType = database.ConnectionTypeWorkspaceApp
method = database.ConnectionLogMethodWorkspaceApp
}
// An empty slug_or_port is reserved for tunnel sessions (see
@@ -542,7 +542,7 @@ func (p *DBTokenProvider) connLogInitRequest(w http.ResponseWriter, r *http.Requ
WorkspaceID: aReq.dbReq.Workspace.ID,
WorkspaceName: aReq.dbReq.Workspace.Name,
AgentName: aReq.dbReq.Agent.Name,
Type: connType,
ConnectionMethod: method,
Code: sql.NullInt32{
Int32: statusCode,
Valid: true,
@@ -553,7 +553,7 @@ func (p *DBTokenProvider) connLogInitRequest(w http.ResponseWriter, r *http.Requ
UUID: userID,
Valid: userID != uuid.Nil,
},
SlugOrPort: sql.NullString{Valid: slugOrPort != "", String: slugOrPort},
AppNameOrPort: sql.NullString{Valid: slugOrPort != "", String: slugOrPort},
ConnectionStatus: database.ConnectionStatusConnected,
// N/A
+20 -20
View File
@@ -310,7 +310,7 @@ func Test_ResolveRequest(t *testing.T) {
require.Equal(t, codersdk.SignedAppTokenCookie, cookie.Name)
require.Equal(t, req.BasePath, cookie.Path)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
var parsedToken workspaceapps.SignedToken
@@ -390,7 +390,7 @@ func Test_ResolveRequest(t *testing.T) {
require.NotNil(t, token)
require.Zero(t, w.StatusCode)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionTypeWorkspaceApp, secondUser.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionLogMethodWorkspaceApp, secondUser.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
}
})
@@ -430,7 +430,7 @@ func Test_ResolveRequest(t *testing.T) {
require.NotZero(t, rw.Code)
require.NotEqual(t, http.StatusOK, rw.Code)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionTypeWorkspaceApp, uuid.Nil)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionLogMethodWorkspaceApp, uuid.Nil)
require.Len(t, connLogger.ConnectionLogs(), 1)
} else {
if !assert.True(t, ok) {
@@ -444,7 +444,7 @@ func Test_ResolveRequest(t *testing.T) {
t.Fatalf("expected 200 (or unset) response code, got %d", rw.Code)
}
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionTypeWorkspaceApp, uuid.Nil)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionLogMethodWorkspaceApp, uuid.Nil)
require.Len(t, connLogger.ConnectionLogs(), 1)
}
_ = w.Body.Close()
@@ -569,7 +569,7 @@ func Test_ResolveRequest(t *testing.T) {
require.Equal(t, token.AgentNameOrID, c.agent)
require.Equal(t, token.WorkspaceID, workspace.ID)
require.Equal(t, token.AgentID, agentID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, token.AppSlugOrPort, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, token.AppSlugOrPort, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
} else {
require.Nil(t, token)
@@ -655,7 +655,7 @@ func Test_ResolveRequest(t *testing.T) {
require.NoError(t, err)
require.Equal(t, appNameOwner, parsedToken.AppSlugOrPort)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, appNameOwner, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, appNameOwner, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
})
@@ -728,7 +728,7 @@ func Test_ResolveRequest(t *testing.T) {
require.True(t, ok)
require.Equal(t, req.AppSlugOrPort, token.AppSlugOrPort)
require.Equal(t, "http://127.0.0.1:9090", token.AppURL)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, "9090", database.ConnectionTypePortForwarding, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, "9090", database.ConnectionLogMethodPortForwarding, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
})
@@ -801,7 +801,7 @@ func Test_ResolveRequest(t *testing.T) {
})
require.True(t, ok)
require.Equal(t, req.AppSlugOrPort, token.AppSlugOrPort)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, appNameEndsInS, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, appNameEndsInS, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
})
@@ -838,7 +838,7 @@ func Test_ResolveRequest(t *testing.T) {
require.Equal(t, req.AgentNameOrID, token.AgentNameOrID)
require.Empty(t, token.AppSlugOrPort)
require.Empty(t, token.AppURL)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, "terminal", database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, "terminal", database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
})
@@ -872,7 +872,7 @@ func Test_ResolveRequest(t *testing.T) {
})
require.False(t, ok)
require.Nil(t, token)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, appNameOwner, database.ConnectionTypeWorkspaceApp, secondUser.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, appNameOwner, database.ConnectionLogMethodWorkspaceApp, secondUser.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
})
@@ -990,7 +990,7 @@ func Test_ResolveRequest(t *testing.T) {
require.Equal(t, http.StatusSeeOther, w.StatusCode)
// Note that we don't capture the owner UUID here because the apiKey
// check/authorization exits early.
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, appNameOwner, database.ConnectionTypeWorkspaceApp, uuid.Nil)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, appNameOwner, database.ConnectionLogMethodWorkspaceApp, uuid.Nil)
require.Len(t, connLogger.ConnectionLogs(), 1)
loc, err := w.Location()
@@ -1052,7 +1052,7 @@ func Test_ResolveRequest(t *testing.T) {
w := rw.Result()
defer w.Body.Close()
require.Equal(t, http.StatusNotFound, w.StatusCode)
assertConnLogContains(t, rw, r, connLogger, workspace, agentNameUnhealthy, appNameAgentUnhealthy, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentNameUnhealthy, appNameAgentUnhealthy, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
body, err := io.ReadAll(w.Body)
@@ -1111,7 +1111,7 @@ func Test_ResolveRequest(t *testing.T) {
})
require.True(t, ok, "ResolveRequest failed, should pass even though app is initializing")
require.NotNil(t, token)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, token.AppSlugOrPort, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, token.AppSlugOrPort, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
})
@@ -1169,7 +1169,7 @@ func Test_ResolveRequest(t *testing.T) {
})
require.True(t, ok, "ResolveRequest failed, should pass even though app is unhealthy")
require.NotNil(t, token)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, token.AppSlugOrPort, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, token.AppSlugOrPort, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
})
@@ -1206,7 +1206,7 @@ func Test_ResolveRequest(t *testing.T) {
AppRequest: req,
})
require.True(t, ok)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 1)
// Second request, no audit log because the session is active.
@@ -1242,7 +1242,7 @@ func Test_ResolveRequest(t *testing.T) {
AppRequest: req,
})
require.True(t, ok)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 2, "two connection logs, session timed out")
// Fourth request, new IP produces new audit log.
@@ -1261,7 +1261,7 @@ func Test_ResolveRequest(t *testing.T) {
AppRequest: req,
})
require.True(t, ok)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionTypeWorkspaceApp, me.ID)
assertConnLogContains(t, rw, r, connLogger, workspace, agentName, app, database.ConnectionLogMethodWorkspaceApp, me.ID)
require.Len(t, connLogger.ConnectionLogs(), 3, "three connection logs, new IP")
}
})
@@ -1303,7 +1303,7 @@ func signedTokenProviderWithConnLogger(t testing.TB, provider workspaceapps.Sign
return &shallowCopy
}
func assertConnLogContains(t *testing.T, rr *httptest.ResponseRecorder, r *http.Request, connLogger *connectionlog.FakeConnectionLogger, workspace codersdk.Workspace, agentName string, slugOrPort string, typ database.ConnectionType, userID uuid.UUID) {
func assertConnLogContains(t *testing.T, rr *httptest.ResponseRecorder, r *http.Request, connLogger *connectionlog.FakeConnectionLogger, workspace codersdk.Workspace, agentName string, slugOrPort string, method database.ConnectionLogMethod, userID uuid.UUID) {
t.Helper()
resp := rr.Result()
@@ -1315,7 +1315,7 @@ func assertConnLogContains(t *testing.T, rr *httptest.ResponseRecorder, r *http.
WorkspaceID: workspace.ID,
WorkspaceName: workspace.Name,
AgentName: agentName,
Type: typ,
ConnectionMethod: method,
IP: database.ParseIP(r.RemoteAddr),
UserAgent: sql.NullString{Valid: r.UserAgent() != "", String: r.UserAgent()},
Code: sql.NullInt32{
@@ -1326,6 +1326,6 @@ func assertConnLogContains(t *testing.T, rr *httptest.ResponseRecorder, r *http.
UUID: userID,
Valid: true,
},
SlugOrPort: sql.NullString{Valid: slugOrPort != "", String: slugOrPort},
AppNameOrPort: sql.NullString{Valid: slugOrPort != "", String: slugOrPort},
}))
}
+24 -2
View File
@@ -71,6 +71,7 @@ type Store interface {
UpsertChatDiffStatusReference(
ctx context.Context, arg database.UpsertChatDiffStatusReferenceParams,
) (database.ChatDiffStatus, error)
GetChatByID(ctx context.Context, id uuid.UUID) (database.Chat, error)
GetChatsByWorkspaceIDs(
ctx context.Context, ids []uuid.UUID,
) ([]database.Chat, error)
@@ -291,7 +292,8 @@ type MarkStaleParams struct {
WorkspaceID uuid.UUID
Branch string
Origin string
// ChatID, when set, targets a single chat.
// ChatID, when set, targets a single chat. Subagent chats are
// resolved to their root chat, which owns the git refs and PRs.
ChatID uuid.UUID
}
@@ -314,7 +316,14 @@ func (w *Worker) MarkStale(ctx context.Context, p MarkStaleParams) {
// chatd via the agent (trusted data flow), but differs from
// the broadcast path which filters by workspace.
if p.ChatID != uuid.Nil {
w.markStaleSingle(ctx, p.ChatID, p.Branch, p.Origin)
chat, err := w.store.GetChatByID(ctx, p.ChatID)
if err != nil {
w.logger.Warn(ctx, "get chat for git ref storage",
slog.F("chat_id", p.ChatID),
slog.Error(err))
return
}
w.markStaleSingle(ctx, rootChatID(chat), p.Branch, p.Origin)
return
}
@@ -359,6 +368,19 @@ func (w *Worker) MarkStale(ctx context.Context, p MarkStaleParams) {
}
}
// rootChatID returns the ID of the root chat in chat's subagent tree.
// Git refs and PRs belong to the root chat so that work done by
// subagents shows up on the chat the user interacts with.
func rootChatID(chat database.Chat) uuid.UUID {
if chat.RootChatID.Valid {
return chat.RootChatID.UUID
}
if chat.ParentChatID.Valid {
return chat.ParentChatID.UUID
}
return chat.ID
}
// originCredentials matches the user and password in an HTTP(S) remote
// such as "https://<token>@github.com/o/r.git". SSH remotes keep their
// user: it is not a secret, and GitHub needs "git@" to parse them.
+74 -1
View File
@@ -851,6 +851,8 @@ func TestWorker_MarkStale_StripsOriginCredentials(t *testing.T) {
ctrl := gomock.NewController(t)
store := dbmock.NewMockStore(ctrl)
chatID := uuid.New()
store.EXPECT().GetChatByID(gomock.Any(), chatID).Return(database.Chat{ID: chatID}, nil)
var stored string
store.EXPECT().UpsertChatDiffStatusReference(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, arg database.UpsertChatDiffStatusReferenceParams) (database.ChatDiffStatus, error) {
stored = arg.GitRemoteOrigin
@@ -865,7 +867,7 @@ func TestWorker_MarkStale_StripsOriginCredentials(t *testing.T) {
WorkspaceID: uuid.New(),
Branch: "main",
Origin: tc.origin,
ChatID: uuid.New(),
ChatID: chatID,
})
require.Equal(t, tc.want, stored)
@@ -888,6 +890,7 @@ func TestWorker_MarkStale_WithChatID(t *testing.T) {
// GetChatsByWorkspaceIDs should NOT be called when a specific chat ID is provided.
store.EXPECT().GetChatsByWorkspaceIDs(gomock.Any(), gomock.Any()).Times(0)
store.EXPECT().GetChatByID(gomock.Any(), targetChat).Return(database.Chat{ID: targetChat}, nil)
store.EXPECT().UpsertChatDiffStatusReference(gomock.Any(), gomock.Any()).DoAndReturn(func(_ context.Context, arg database.UpsertChatDiffStatusReferenceParams) (database.ChatDiffStatus, error) {
mu.Lock()
upsertRefCalls = append(upsertRefCalls, arg)
@@ -929,6 +932,76 @@ func TestWorker_MarkStale_WithChatID(t *testing.T) {
assert.Equal(t, targetChat, publishedIDs[0])
}
func TestWorker_MarkStale_SubagentChatID_UsesRootChat(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, _ := dbtestutil.NewDB(t)
user := dbgen.User(t, db, database.User{})
org := dbgen.Organization(t, db, database.Organization{})
_ = dbgen.ChatProvider(t, db, database.ChatProvider{})
modelCfg := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{
Model: "test-model",
ContextLimit: 100000,
})
root := dbgen.Chat(t, db, database.Chat{
OrganizationID: org.ID,
OwnerID: user.ID,
LastModelConfigID: modelCfg.ID,
Title: "root",
})
child := dbgen.Chat(t, db, database.Chat{
OrganizationID: org.ID,
OwnerID: user.ID,
LastModelConfigID: modelCfg.ID,
Title: "child",
ParentChatID: uuid.NullUUID{UUID: root.ID, Valid: true},
RootChatID: uuid.NullUUID{UUID: root.ID, Valid: true},
})
grandchild := dbgen.Chat(t, db, database.Chat{
OrganizationID: org.ID,
OwnerID: user.ID,
LastModelConfigID: modelCfg.ID,
Title: "grandchild",
ParentChatID: uuid.NullUUID{UUID: child.ID, Valid: true},
RootChatID: uuid.NullUUID{UUID: root.ID, Valid: true},
})
var publishedIDs []uuid.UUID
pub := func(_ context.Context, chatID uuid.UUID, _ codersdk.DiffStatusRef) error {
publishedIDs = append(publishedIDs, chatID)
return nil
}
mClock := quartz.NewMock(t)
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
worker := gitsync.NewWorker(db, newTestRefresher(t, mClock), pub, mClock, logger)
worker.MarkStale(ctx, gitsync.MarkStaleParams{
WorkspaceID: uuid.New(),
Branch: "child-branch",
Origin: "https://github.com/o/r",
ChatID: child.ID,
})
worker.MarkStale(ctx, gitsync.MarkStaleParams{
WorkspaceID: uuid.New(),
Branch: "grandchild-branch",
Origin: "https://github.com/o/r",
ChatID: grandchild.ID,
})
statuses, err := db.GetChatDiffStatusesByChatIDs(ctx, []uuid.UUID{root.ID, child.ID, grandchild.ID})
require.NoError(t, err)
require.Len(t, statuses, 2)
branches := make([]string, 0, len(statuses))
for _, status := range statuses {
assert.Equal(t, root.ID, status.ChatID)
branches = append(branches, status.GitBranch)
}
assert.ElementsMatch(t, []string{"child-branch", "grandchild-branch"}, branches)
assert.Equal(t, []uuid.UUID{root.ID, root.ID}, publishedIDs)
}
func TestWorker_MarkStale_NilChatID_Broadcasts(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
+7
View File
@@ -163,6 +163,13 @@ func AppNameFamily(appName string) AppFamilyName {
return AppFamilyUnknown
}
// AppDisplayName returns the registry name of appName, or the normalized name
// if unregistered.
func AppDisplayName(appName string) string {
appName = NormalizeAppName(appName)
return cmp.Or(sessionApps[appName].displayName, appName)
}
// NormalizeAppName prepares a client-supplied app name for storage and
// lookup: it strips control characters, then trims, truncates, lowercases,
// and folds hyphens to underscores. Empty becomes AppFamilyUnknown.
+26 -11
View File
@@ -20,23 +20,27 @@ type ConnectionLog struct {
WorkspaceName string `json:"workspace_name"`
AgentName string `json:"agent_name"`
IP *netip.Addr `json:"ip,omitempty"`
Type ConnectionType `json:"type"`
// Deprecated: Use ConnectionMethod and AppName.
Type string `json:"type"`
ConnectionMethod ConnectionLogMethod `json:"connection_method"`
// AppName is the name of the connecting application, when known. The
// client reports it, so it is a normalized label and not a guarantee.
// Workspace app slugs and forwarded ports are reported in WebInfo.
AppName string `json:"app_name,omitempty"`
// AppDisplayName is the registry display name for AppName, or AppName
// itself when the app is unregistered.
AppDisplayName string `json:"app_display_name,omitempty"`
// WebInfo is only set when `type` is one of:
// - `ConnectionTypePortForwarding`
// - `ConnectionTypeWorkspaceApp`
// - `ConnectionTypeTunnel`
// WebInfo is set for connections that coderd records.
WebInfo *ConnectionLogWebInfo `json:"web_info,omitempty"`
// SSHInfo is only set when `type` is one of:
// - `ConnectionTypeSSH`
// - `ConnectionTypeReconnectingPTY`
// - `ConnectionTypeVSCode`
// - `ConnectionTypeJetBrains`
// SSHInfo is set for connections that agents report.
SSHInfo *ConnectionLogSSHInfo `json:"ssh_info,omitempty"`
}
// ConnectionType is the type of connection that the agent is receiving.
// ConnectionType is a connection method with SSH split by app family. It backs
// the legacy `type` filter. Remove it when that filter and ConnectionLog.Type
// are removed.
type ConnectionType string
const (
@@ -51,6 +55,17 @@ const (
ConnectionTypeTunnel ConnectionType = "tunnel"
)
func (t ConnectionType) Valid() bool {
switch t {
case ConnectionTypeSSH, ConnectionTypeVSCode, ConnectionTypeJetBrains,
ConnectionTypeReconnectingPTY, ConnectionTypeWorkspaceApp,
ConnectionTypePortForwarding, ConnectionTypeTunnel:
return true
default:
return false
}
}
// ConnectionLogStatus is the status of a connection log entry.
// It's the argument to the `status` filter when fetching connection logs.
type ConnectionLogStatus string
+20
View File
@@ -0,0 +1,20 @@
package codersdk_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/codersdk"
)
// An absent app is omitted rather than sent empty.
func TestConnectionLogJSON(t *testing.T) {
t.Parallel()
raw, err := json.Marshal(codersdk.ConnectionLog{ConnectionMethod: codersdk.ConnectionLogMethodSSH})
require.NoError(t, err)
require.NotContains(t, string(raw), `"app_name"`)
require.NotContains(t, string(raw), `"app_display_name"`)
}
+21
View File
@@ -0,0 +1,21 @@
// Code generated by typegen/main.go. DO NOT EDIT.
package codersdk
// ConnectionLogMethod mirrors database.ConnectionLogMethod.
type ConnectionLogMethod string
const (
ConnectionLogMethodSSH ConnectionLogMethod = "ssh"
ConnectionLogMethodReconnectingPTY ConnectionLogMethod = "reconnecting_pty"
ConnectionLogMethodWorkspaceApp ConnectionLogMethod = "workspace_app"
ConnectionLogMethodPortForwarding ConnectionLogMethod = "port_forwarding"
ConnectionLogMethodTunnel ConnectionLogMethod = "tunnel"
)
func (e ConnectionLogMethod) Valid() bool {
switch e {
case ConnectionLogMethodSSH, ConnectionLogMethodReconnectingPTY, ConnectionLogMethodWorkspaceApp, ConnectionLogMethodPortForwarding, ConnectionLogMethodTunnel:
return true
}
return false
}
+73 -23
View File
@@ -55,9 +55,16 @@ You can filter connection logs by the following parameters:
connected to.
- `workspace_owner` - The username of the owner of the workspace being connected
to.
- `type` - The type of the connection, such as SSH, VS Code, or workspace app.
For more connection types, refer to the
[CoderSDK documentation](https://pkg.go.dev/github.com/coder/coder/v2/codersdk#ConnectionType).
- `method` - How the connection was established, such as `ssh`, `reconnecting_pty`, or `workspace_app`.
For every method, refer to the [`codersdk.ConnectionLogMethod` schema](../../reference/api/schemas.md#codersdkconnectionlogmethod).
For example, `method:ssh` matches every SSH connection, whichever app made it.
- `app` - The name of the application that made an SSH or reconnecting PTY connection, such as `cursor`.
Repeat the filter to match any of several apps, for example `app:vscode app:cursor`.
Some clients report only `vscode` or `jetbrains` instead of their own name, so `app:vscode` and `app:jetbrains` can also include other VS Code-based editors and JetBrains IDEs.
Coder lowercases the value and replaces hyphens with underscores before it matches.
Workspace app slugs and forwarded ports don't match this filter.
- `type` - Deprecated and will be removed in a future release.
Use `method` and `app` instead, as described in [Replace the type filter](#replace-the-type-filter).
- `username`: The name of the user who initiated the connection.
Results do not include agent-reported SSH or IDE sessions.
- `user_email`: The email of the user who initiated the connection.
@@ -69,8 +76,20 @@ You can filter connection logs by the following parameters:
- `workspace_id`: The ID of the workspace being connected to.
- `connection_id`: The ID of the connection.
- `status`: The status of the connection, either `ongoing` or `completed`.
Some events are neither ongoing nor completed, such as the opening of a
workspace app.
Only SSH and reconnecting PTY connections have a status.
A connection is `completed` after Coder receives its disconnect event, and `ongoing` until then.
Workspace app, port forwarding, and tunnel events never match a `status` filter.
### Replace the type filter
If you have saved searches or scripts that use the `type` filter, replace it with `method` and `app`:
| `type` filter | Replacement |
|--------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------|
| `type:ssh` | `method:ssh`, which also matches SSH connections from VS Code and JetBrains apps |
| `type:vscode` | `method:ssh` with an `app` filter for each VS Code-based app, for example `app:vscode app:cursor` |
| `type:jetbrains` | `method:ssh app:jetbrains`, plus an `app` filter for any JetBrains IDE that reports its own name |
| `type:reconnecting_pty`, `type:workspace_app`, `type:port_forwarding`, `type:tunnel` | `method` with the same value, for example `method:workspace_app` |
<a id="capturingexporting-connection-logs"></a>
@@ -86,49 +105,80 @@ Visit the
[`get-connection-logs` endpoint documentation](../../reference/api/enterprise.md#get-connection-logs)
for details.
Each connection log in the response describes the connection with these fields:
- `connection_method`: How the connection was established, with the same values as the `method` filter.
- `app_name`: The name of the application that made an SSH or reconnecting PTY connection, such as `vscode`.
The client reports this name, so treat it as a label rather than a verified identity.
The response omits this field when the app isn't known, and for workspace app, port forwarding, and tunnel connections.
- `web_info.slug_or_port`: The workspace app slug or forwarded port, for workspace app and port forwarding connections.
- `type`: Deprecated.
Use `connection_method` and `app_name` instead.
It will be removed in a future release.
If you read `type`, map its values to the new fields as follows:
| `type` | `connection_method` | `app_name` |
|----------------------------------------------|---------------------|---------------------------------------------------------------|
| `ssh` | `ssh` | Omitted, or an app outside the VS Code and JetBrains families |
| `vscode` | `ssh` | An app in the VS Code family, such as `vscode` |
| `jetbrains` | `ssh` | An app in the JetBrains family, such as `jetbrains` |
| `reconnecting_pty` | `reconnecting_pty` | Omitted unless the app is known |
| `workspace_app`, `port_forwarding`, `tunnel` | Same as `type` | Omitted |
The `type` field keeps the same values, but the API schema describes it as a string rather than an enum.
### Service Logs
Connection events are also dispatched as service logs and can be captured and
categorized using any log management tool such as [Splunk](https://splunk.com).
Example of a [JSON formatted](../../reference/cli/server/index.md#--log-json)
connection log entry, when an SSH connection is made:
Each `connection_log` entry describes the connection with these fields:
- `ConnectionMethod`: How the connection was established, with the same values as the API `connection_method` field.
- `AppNameOrPort`: The name of the connecting application for SSH and reconnecting PTY connections, or the workspace app slug or forwarded port for workspace app and port forwarding connections.
The value is an empty string when there is nothing to report.
If your log pipeline reads the `Type` or `SlugOrPort` fields, update it to read `ConnectionMethod` and `AppNameOrPort`, because entries no longer include the old fields.
For SSH connections from a VS Code or JetBrains family app, `ConnectionMethod` is `ssh` and `AppNameOrPort` holds the app name, such as `vscode`.
Every other former `Type` value matches `ConnectionMethod` directly.
Example of a [JSON formatted](../../reference/cli/server/index.md#--log-json) connection log entry, when VS Code connects over SSH:
```json
{
"ts": "2025-07-03T05:09:41.929840747Z",
"ts": "2026-10-07T11:34:37.428786242Z",
"level": "INFO",
"msg": "connection_log",
"caller": "/home/coder/coder/enterprise/audit/backends/slog.go:38",
"caller": "/home/coder/coder/enterprise/audit/backends/slog.go:36",
"func": "github.com/coder/coder/v2/enterprise/audit/backends.(*SlogExporter).ExportStruct",
"logger_names": ["coderd"],
"fields": {
"request_id": "916ad077-e120-4861-8640-f449d56d2bae",
"ID": "ca5dfc63-dc43-463a-bb3e-38526866fd4b",
"OrganizationID": "1a2bb67e-0117-4168-92e0-58138989a7f5",
"WorkspaceOwnerID": "fe8f4bab-3128-41f1-8fec-1cc0755affe5",
"WorkspaceID": "05567e23-31e2-4c00-bd05-4d499d437347",
"ID": "2e3b3337-77ab-4677-b39f-ba98df4e8ae4",
"OrganizationID": "8654721b-2d93-4559-afdb-bdbdc2acbdc2",
"WorkspaceOwnerID": "1a7edc8c-b712-4a1f-9d8f-7727127912e2",
"WorkspaceID": "59d3e101-2d07-40c8-9bcd-d5fff4cc5266",
"WorkspaceName": "dev",
"AgentName": "main",
"Type": "ssh",
"ConnectionMethod": "ssh",
"Code": null,
"Ip": "fd7a:115c:a1e0:4b86:9046:80e:6c70:33b7",
"IP": "fd7a:115c:a1e0:4b86:9046:80e:6c70:33b7",
"UserAgent": "",
"UserID": null,
"SlugOrPort": "",
"ConnectionID": "7a6fafdc-e3d0-43cb-a1b7-1f19802d7908",
"AppNameOrPort": "vscode",
"ConnectionID": "875ee185-cdf7-4cd1-98d7-d8a415e42a26",
"DisconnectReason": "",
"Time": "2025-07-10T10:14:38.942776145Z",
"ClientSessionID": "",
"Time": "2026-10-07T11:34:37.428771813Z",
"ConnectionStatus": "connected"
}
}
```
Example of a [human readable](../../reference/cli/server/index.md#--log-human)
connection log entry, when `code-server` is opened:
Example of a [human readable](../../reference/cli/server/index.md#--log-human) connection log entry, when a user opens `code-server`:
```console
[API] 2025-07-03 06:57:16.157 [info] coderd: connection_log request_id=de3f6004-6cc1-4880-a296-d7c6ca1abf75 ID=f0249951-d454-48f6-9504-e73340fa07b7 Time="2025-07-03T06:57:16.144719Z" OrganizationID=0665a54f-0b77-4a58-94aa-59646fa38a74 WorkspaceOwnerID=6dea5f8c-ecec-4cf0-a5bd-bc2c63af2efa WorkspaceID=3c0b37c8-e58c-4980-b9a1-2732410480a5 WorkspaceName=dev AgentName=main Type=workspace_app Code=200 Ip=127.0.0.1 UserAgent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36" UserID=6dea5f8c-ecec-4cf0-a5bd-bc2c63af2efa SlugOrPort=code-server ConnectionID=<nil> DisconnectReason="" ConnectionStatus=connected
```txt
2026-10-07 11:34:37.428 [info] coderd: connection_log ID=909a0310-a14c-4761-89d3-9779a328f14f OrganizationID=dc39157d-b298-415d-8fc7-590e9055f244 WorkspaceOwnerID=17f1cc14-ac7a-4703-976e-73ea4547dceb WorkspaceID=f2e648d4-95bc-4df3-a5c2-ee5be991da29 WorkspaceName=dev AgentName=main ConnectionMethod=workspace_app Code=200 IP=127.0.0.1 UserAgent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36" UserID=17f1cc14-ac7a-4703-976e-73ea4547dceb AppNameOrPort=code-server ConnectionID=<nil> DisconnectReason="" ClientSessionID="" Time="2026-10-07 11:34:37.428773435 +0000 UTC" ConnectionStatus=connected
```
## Data Retention
+4 -1
View File
@@ -487,7 +487,10 @@ curl -X GET http://coder-server:8080/api/v2/connectionlog?limit=0 \
"connection_logs": [
{
"agent_name": "string",
"app_display_name": "string",
"app_name": "string",
"connect_time": "2019-08-24T14:15:22Z",
"connection_method": "ssh",
"id": "497f6eca-6276-4993-bfeb-53cbbbba6f08",
"ip": "string",
"organization": {
@@ -502,7 +505,7 @@ curl -X GET http://coder-server:8080/api/v2/connectionlog?limit=0 \
"disconnect_time": "2019-08-24T14:15:22Z",
"exit_code": 0
},
"type": "ssh",
"type": "string",
"web_info": {
"slug_or_port": "string",
"status_code": 0,
+39 -30
View File
@@ -5834,7 +5834,10 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
```json
{
"agent_name": "string",
"app_display_name": "string",
"app_name": "string",
"connect_time": "2019-08-24T14:15:22Z",
"connection_method": "ssh",
"id": "497f6eca-6276-4993-bfeb-53cbbbba6f08",
"ip": "string",
"organization": {
@@ -5849,7 +5852,7 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
"disconnect_time": "2019-08-24T14:15:22Z",
"exit_code": 0
},
"type": "ssh",
"type": "string",
"web_info": {
"slug_or_port": "string",
"status_code": 0,
@@ -5889,20 +5892,37 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
### Properties
| Name | Type | Required | Restrictions | Description |
|----------------------------|----------------------------------------------------------------|----------|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
| `agent_name` | string | false | | |
| `connect_time` | string | false | | |
| `id` | string | false | | |
| `ip` | string | false | | |
| `organization` | [codersdk.MinimalOrganization](#codersdkminimalorganization) | false | | |
| `ssh_info` | [codersdk.ConnectionLogSSHInfo](#codersdkconnectionlogsshinfo) | false | | Ssh info is only set when `type` is one of: - `ConnectionTypeSSH` - `ConnectionTypeReconnectingPTY` - `ConnectionTypeVSCode` - `ConnectionTypeJetBrains` |
| `type` | [codersdk.ConnectionType](#codersdkconnectiontype) | false | | |
| `web_info` | [codersdk.ConnectionLogWebInfo](#codersdkconnectionlogwebinfo) | false | | Web info is only set when `type` is one of: - `ConnectionTypePortForwarding` - `ConnectionTypeWorkspaceApp` - `ConnectionTypeTunnel` |
| `workspace_id` | string | false | | |
| `workspace_name` | string | false | | |
| `workspace_owner_id` | string | false | | |
| `workspace_owner_username` | string | false | | |
| Name | Type | Required | Restrictions | Description |
|----------------------------|----------------------------------------------------------------|----------|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `agent_name` | string | false | | |
| `app_display_name` | string | false | | App display name is the registry display name for AppName, or AppName itself when the app is unregistered. |
| `app_name` | string | false | | App name is the name of the connecting application, when known. The client reports it, so it is a normalized label and not a guarantee. Workspace app slugs and forwarded ports are reported in WebInfo. |
| `connect_time` | string | false | | |
| `connection_method` | [codersdk.ConnectionLogMethod](#codersdkconnectionlogmethod) | false | | |
| `id` | string | false | | |
| `ip` | string | false | | |
| `organization` | [codersdk.MinimalOrganization](#codersdkminimalorganization) | false | | |
| `ssh_info` | [codersdk.ConnectionLogSSHInfo](#codersdkconnectionlogsshinfo) | false | | Ssh info is set for connections that agents report. |
| `type` | string | false | | Deprecated: Use ConnectionMethod and AppName. |
| `web_info` | [codersdk.ConnectionLogWebInfo](#codersdkconnectionlogwebinfo) | false | | Web info is set for connections that coderd records. |
| `workspace_id` | string | false | | |
| `workspace_name` | string | false | | |
| `workspace_owner_id` | string | false | | |
| `workspace_owner_username` | string | false | | |
## codersdk.ConnectionLogMethod
```json
"ssh"
```
### Properties
#### Enumerated Values
| Value(s) |
|-------------------------------------------------------------------------|
| `port_forwarding`, `reconnecting_pty`, `ssh`, `tunnel`, `workspace_app` |
## codersdk.ConnectionLogResponse
@@ -5911,7 +5931,10 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
"connection_logs": [
{
"agent_name": "string",
"app_display_name": "string",
"app_name": "string",
"connect_time": "2019-08-24T14:15:22Z",
"connection_method": "ssh",
"id": "497f6eca-6276-4993-bfeb-53cbbbba6f08",
"ip": "string",
"organization": {
@@ -5926,7 +5949,7 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
"disconnect_time": "2019-08-24T14:15:22Z",
"exit_code": 0
},
"type": "ssh",
"type": "string",
"web_info": {
"slug_or_port": "string",
"status_code": 0,
@@ -6040,20 +6063,6 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
| `user` | [codersdk.User](#codersdkuser) | false | | User is omitted if the connection event was unauthenticated. |
| `user_agent` | string | false | | |
## codersdk.ConnectionType
```json
"ssh"
```
### Properties
#### Enumerated Values
| Value(s) |
|------------------------------------------------------------------------------------------------|
| `jetbrains`, `port_forwarding`, `reconnecting_pty`, `ssh`, `tunnel`, `vscode`, `workspace_app` |
## codersdk.ConvertLoginRequest
```json
+21 -14
View File
@@ -132,20 +132,13 @@ func convertConnectionLog(dblog database.GetConnectionLogsOffsetRow) codersdk.Co
sshInfo *codersdk.ConnectionLogSSHInfo
)
switch dblog.ConnectionLog.Type {
case database.ConnectionTypeWorkspaceApp,
database.ConnectionTypePortForwarding,
database.ConnectionTypeTunnel:
webInfo = &codersdk.ConnectionLogWebInfo{
UserAgent: dblog.ConnectionLog.UserAgent.String,
User: user,
SlugOrPort: dblog.ConnectionLog.SlugOrPort.String,
StatusCode: dblog.ConnectionLog.Code.Int32,
var appName, appDisplayName string
switch dblog.ConnectionLog.ConnectionMethod {
case database.ConnectionLogMethodSSH, database.ConnectionLogMethodReconnectingPTY:
appName = dblog.ConnectionLog.AppNameOrPort.String
if appName != "" {
appDisplayName = codersdk.AppDisplayName(appName)
}
case database.ConnectionTypeSsh,
database.ConnectionTypeReconnectingPty,
database.ConnectionTypeJetbrains,
database.ConnectionTypeVscode:
sshInfo = &codersdk.ConnectionLogSSHInfo{
ConnectionID: dblog.ConnectionLog.ConnectionID.UUID,
DisconnectReason: dblog.ConnectionLog.DisconnectReason.String,
@@ -156,6 +149,17 @@ func convertConnectionLog(dblog database.GetConnectionLogsOffsetRow) codersdk.Co
if dblog.ConnectionLog.Code.Valid {
sshInfo.ExitCode = &dblog.ConnectionLog.Code.Int32
}
case database.ConnectionLogMethodWorkspaceApp,
database.ConnectionLogMethodPortForwarding,
database.ConnectionLogMethodTunnel:
webInfo = &codersdk.ConnectionLogWebInfo{
UserAgent: dblog.ConnectionLog.UserAgent.String,
User: user,
SlugOrPort: dblog.ConnectionLog.AppNameOrPort.String,
StatusCode: dblog.ConnectionLog.Code.Int32,
}
default:
panic("developer error: unknown connection log method " + string(dblog.ConnectionLog.ConnectionMethod))
}
return codersdk.ConnectionLog{
@@ -172,7 +176,10 @@ func convertConnectionLog(dblog database.GetConnectionLogsOffsetRow) codersdk.Co
WorkspaceID: dblog.ConnectionLog.WorkspaceID,
WorkspaceName: dblog.ConnectionLog.WorkspaceName,
AgentName: dblog.ConnectionLog.AgentName,
Type: codersdk.ConnectionType(dblog.ConnectionLog.Type),
Type: db2sdk.ConnectionLogType(dblog.ConnectionLog.ConnectionMethod, dblog.ConnectionLog.AppNameOrPort.String),
ConnectionMethod: codersdk.ConnectionLogMethod(dblog.ConnectionLog.ConnectionMethod),
AppName: appName,
AppDisplayName: appDisplayName,
IP: ip,
WebInfo: webInfo,
SSHInfo: sshInfo,
@@ -383,13 +383,13 @@ func (b *DBBatcher) buildParams() database.BatchUpsertConnectionLogsParams {
workspaceID = make([]uuid.UUID, 0, count)
workspaceName = make([]string, 0, count)
agentName = make([]string, 0, count)
connType = make([]database.ConnectionType, 0, count)
methods = make([]database.ConnectionLogMethod, 0, count)
code = make([]int32, 0, count)
codeValid = make([]bool, 0, count)
ip = make([]pqtype.Inet, 0, count)
userAgent = make([]string, 0, count)
userID = make([]uuid.UUID, 0, count)
slugOrPort = make([]string, 0, count)
appNameOrPort = make([]string, 0, count)
connectionID = make([]uuid.UUID, 0, count)
disconnectReason = make([]string, 0, count)
disconnectTime = make([]time.Time, 0, count)
@@ -404,13 +404,13 @@ func (b *DBBatcher) buildParams() database.BatchUpsertConnectionLogsParams {
workspaceID = append(workspaceID, e.WorkspaceID)
workspaceName = append(workspaceName, e.WorkspaceName)
agentName = append(agentName, e.AgentName)
connType = append(connType, e.Type)
methods = append(methods, e.ConnectionMethod)
code = append(code, e.Code.Int32)
codeValid = append(codeValid, e.Code.Valid)
ip = append(ip, e.IP)
userAgent = append(userAgent, e.UserAgent.String)
userID = append(userID, e.UserID.UUID)
slugOrPort = append(slugOrPort, e.SlugOrPort.String)
appNameOrPort = append(appNameOrPort, e.AppNameOrPort.String)
connectionID = append(connectionID, e.ConnectionID.UUID)
disconnectReason = append(disconnectReason, e.DisconnectReason.String)
disconnectTime = append(disconnectTime, e.disconnectTime)
@@ -432,13 +432,13 @@ func (b *DBBatcher) buildParams() database.BatchUpsertConnectionLogsParams {
WorkspaceID: workspaceID,
WorkspaceName: workspaceName,
AgentName: agentName,
Type: connType,
ConnectionMethod: methods,
Code: code,
CodeValid: codeValid,
Ip: ip,
UserAgent: userAgent,
UserID: userID,
SlugOrPort: slugOrPort,
AppNameOrPort: appNameOrPort,
ConnectionID: connectionID,
DisconnectReason: disconnectReason,
DisconnectTime: disconnectTime,
@@ -495,7 +495,7 @@ func fakeConnectEvent(workspaceID uuid.UUID, agentName string, connectionID uuid
WorkspaceID: workspaceID,
WorkspaceName: "test-workspace",
AgentName: agentName,
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionID: uuid.NullUUID{UUID: connectionID, Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
}
@@ -510,7 +510,7 @@ func fakeDisconnectEvent(workspaceID uuid.UUID, agentName string, connectionID u
WorkspaceID: workspaceID,
WorkspaceName: "test-workspace",
AgentName: agentName,
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionID: uuid.NullUUID{UUID: connectionID, Valid: true},
ConnectionStatus: database.ConnectionStatusDisconnected,
Code: sql.NullInt32{Int32: 0, Valid: true},
@@ -527,7 +527,7 @@ func fakeNullConnIDEvent() database.UpsertConnectionLogParams {
WorkspaceID: uuid.New(),
WorkspaceName: "test-workspace",
AgentName: "test-agent",
Type: database.ConnectionTypeWorkspaceApp,
ConnectionMethod: database.ConnectionLogMethodWorkspaceApp,
ConnectionID: uuid.NullUUID{},
ConnectionStatus: database.ConnectionStatusConnected,
}
@@ -79,7 +79,7 @@ func TestDBBackendIntegration(t *testing.T) {
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: "main",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionID: uuid.NullUUID{UUID: connID, Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
IP: testIP(),
@@ -126,7 +126,8 @@ func TestDBBackendIntegration(t *testing.T) {
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: "main",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
AppNameOrPort: sql.NullString{String: "cursor", Valid: true},
ConnectionID: uuid.NullUUID{UUID: connID, Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
IP: testIP(),
@@ -150,7 +151,8 @@ func TestDBBackendIntegration(t *testing.T) {
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: "main",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
AppNameOrPort: sql.NullString{String: "cursor", Valid: true},
ConnectionID: uuid.NullUUID{UUID: connID, Valid: true},
ConnectionStatus: database.ConnectionStatusDisconnected,
Code: sql.NullInt32{Int32: 0, Valid: true},
@@ -165,8 +167,11 @@ func TestDBBackendIntegration(t *testing.T) {
})
require.NoError(t, err)
require.Len(t, rows, 1, "connect+disconnect should produce one row")
require.True(t, rows[0].ConnectionLog.DisconnectTime.Valid)
require.Equal(t, "client left", rows[0].ConnectionLog.DisconnectReason.String)
row := rows[0].ConnectionLog
require.True(t, row.DisconnectTime.Valid)
require.Equal(t, "client left", row.DisconnectReason.String)
require.Equal(t, database.ConnectionLogMethodSSH, row.ConnectionMethod)
require.Equal(t, sql.NullString{String: "cursor", Valid: true}, row.AppNameOrPort)
})
t.Run("ConnectAndDisconnectSameBatch", func(t *testing.T) {
@@ -199,7 +204,7 @@ func TestDBBackendIntegration(t *testing.T) {
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: "main",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionID: uuid.NullUUID{UUID: connID, Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
IP: testIP(),
@@ -214,7 +219,7 @@ func TestDBBackendIntegration(t *testing.T) {
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: "main",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionID: uuid.NullUUID{UUID: connID, Valid: true},
ConnectionStatus: database.ConnectionStatusDisconnected,
Code: sql.NullInt32{Int32: 0, Valid: true},
@@ -234,6 +239,8 @@ func TestDBBackendIntegration(t *testing.T) {
require.Len(t, rows, 1)
require.True(t, rows[0].ConnectionLog.DisconnectTime.Valid)
require.Equal(t, "done", rows[0].ConnectionLog.DisconnectReason.String)
require.Equal(t, database.ConnectionLogMethodSSH, rows[0].ConnectionLog.ConnectionMethod)
require.False(t, rows[0].ConnectionLog.AppNameOrPort.Valid, "an absent app is stored as NULL")
})
t.Run("MultipleIndependentConnections", func(t *testing.T) {
@@ -263,7 +270,7 @@ func TestDBBackendIntegration(t *testing.T) {
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: "main",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionID: uuid.NullUUID{UUID: uuid.New(), Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
IP: testIP(),
@@ -308,7 +315,7 @@ func TestDBBackendIntegration(t *testing.T) {
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: "main",
Type: database.ConnectionTypeWorkspaceApp,
ConnectionMethod: database.ConnectionLogMethodWorkspaceApp,
ConnectionID: uuid.NullUUID{},
ConnectionStatus: database.ConnectionStatusConnected,
IP: testIP(),
@@ -351,7 +358,7 @@ func TestDBBackendIntegration(t *testing.T) {
WorkspaceID: ws.ID,
WorkspaceName: ws.Name,
AgentName: "main",
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
ConnectionID: uuid.NullUUID{UUID: uuid.New(), Valid: true},
ConnectionStatus: database.ConnectionStatusConnected,
IP: testIP(),
@@ -0,0 +1,26 @@
package coderd
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/database"
)
// convertConnectionLog panics on a method it does not handle, so every method
// must convert with exactly one of WebInfo and SSHInfo.
func TestConvertConnectionLogHandlesEveryMethod(t *testing.T) {
t.Parallel()
for _, method := range database.AllConnectionLogMethodValues() {
t.Run(string(method), func(t *testing.T) {
t.Parallel()
log := convertConnectionLog(database.GetConnectionLogsOffsetRow{
ConnectionLog: database.ConnectionLog{ConnectionMethod: method},
})
require.NotEqual(t, log.WebInfo == nil, log.SSHInfo == nil)
})
}
}
+73 -11
View File
@@ -56,7 +56,7 @@ func TestConnectionLogs(t *testing.T) {
ws := createWorkspace(t, db)
_ = dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
WorkspaceID: ws.ID,
OrganizationID: ws.OrganizationID,
WorkspaceOwnerID: ws.OwnerID,
@@ -67,7 +67,63 @@ func TestConnectionLogs(t *testing.T) {
require.Len(t, logs.ConnectionLogs, 1)
require.EqualValues(t, 1, logs.Count)
require.Equal(t, codersdk.ConnectionTypeSSH, logs.ConnectionLogs[0].Type)
require.Equal(t, string(codersdk.ConnectionTypeSSH), logs.ConnectionLogs[0].Type)
require.Equal(t, codersdk.ConnectionLogMethodSSH, logs.ConnectionLogs[0].ConnectionMethod)
require.Empty(t, logs.ConnectionLogs[0].AppName)
require.Empty(t, logs.ConnectionLogs[0].AppDisplayName, "no display name is made up for a missing app")
})
// The filter semantics are covered by the database tests. This checks that
// method, app and type queries reach them.
t.Run("Filters", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
client, db, _ := coderdenttest.NewWithDatabase(t, &coderdenttest.Options{
ConnectionLogging: true,
LicenseOptions: &coderdenttest.LicenseOptions{
Features: license.Features{
codersdk.FeatureAuditLog: 1,
codersdk.FeatureConnectionLog: 1,
},
},
})
ws := createWorkspace(t, db)
insert := func(method database.ConnectionLogMethod, appNameOrPort string) uuid.UUID {
return dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
ConnectionMethod: method,
AppNameOrPort: sql.NullString{String: appNameOrPort, Valid: appNameOrPort != ""},
WorkspaceID: ws.ID,
OrganizationID: ws.OrganizationID,
WorkspaceOwnerID: ws.OwnerID,
}).ID
}
sshCursor := insert(database.ConnectionLogMethodSSH, "cursor")
ptyCursor := insert(database.ConnectionLogMethodReconnectingPTY, "cursor")
_ = insert(database.ConnectionLogMethodSSH, "")
// A workspace app slugged like an IDE is still a workspace app.
_ = insert(database.ConnectionLogMethodWorkspaceApp, "cursor")
query := func(q string) []uuid.UUID {
logs, err := client.ConnectionLogs(ctx, codersdk.ConnectionLogsRequest{SearchQuery: q})
require.NoError(t, err, q)
require.EqualValues(t, len(logs.ConnectionLogs), logs.Count, "count must match the listed logs for %q", q)
var ids []uuid.UUID
for _, l := range logs.ConnectionLogs {
ids = append(ids, l.ID)
}
return ids
}
require.ElementsMatch(t, []uuid.UUID{sshCursor}, query("type:vscode"))
require.ElementsMatch(t, []uuid.UUID{sshCursor, ptyCursor}, query("app:cursor"))
require.ElementsMatch(t, []uuid.UUID{ptyCursor}, query("method:reconnecting_pty app:cursor"))
_, err := client.ConnectionLogs(ctx, codersdk.ConnectionLogsRequest{SearchQuery: "method:vscode"})
var sdkErr *codersdk.Error
require.ErrorAs(t, err, &sdkErr)
require.Equal(t, http.StatusBadRequest, sdkErr.StatusCode())
})
t.Run("Empty", func(t *testing.T) {
@@ -107,13 +163,13 @@ func TestConnectionLogs(t *testing.T) {
org := dbgen.Organization(t, db, database.Organization{})
ws := createWorkspace(t, db)
_ = dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
WorkspaceID: ws.ID,
OrganizationID: org.ID,
WorkspaceOwnerID: ws.OwnerID,
})
_ = dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
WorkspaceID: ws.ID,
OrganizationID: ws.OrganizationID,
WorkspaceOwnerID: ws.OwnerID,
@@ -158,14 +214,14 @@ func TestConnectionLogs(t *testing.T) {
ws := createWorkspace(t, db)
clog := dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Time: now.Add(-time.Hour),
Type: database.ConnectionTypeWorkspaceApp,
ConnectionMethod: database.ConnectionLogMethodWorkspaceApp,
WorkspaceID: ws.ID,
OrganizationID: ws.OrganizationID,
WorkspaceOwnerID: ws.OwnerID,
ConnectionID: uuid.NullUUID{UUID: connID, Valid: true},
UserAgent: sql.NullString{String: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36", Valid: true},
UserID: uuid.NullUUID{UUID: ws.OwnerID, Valid: true},
SlugOrPort: sql.NullString{String: "code-server", Valid: true},
AppNameOrPort: sql.NullString{String: "code-server", Valid: true},
})
logs, err := client.ConnectionLogs(ctx, codersdk.ConnectionLogsRequest{})
@@ -174,7 +230,9 @@ func TestConnectionLogs(t *testing.T) {
require.Len(t, logs.ConnectionLogs, 1)
require.EqualValues(t, 1, logs.Count)
require.NotNil(t, logs.ConnectionLogs[0].WebInfo)
require.Equal(t, clog.SlugOrPort.String, logs.ConnectionLogs[0].WebInfo.SlugOrPort)
require.Equal(t, clog.AppNameOrPort.String, logs.ConnectionLogs[0].WebInfo.SlugOrPort)
require.Empty(t, logs.ConnectionLogs[0].AppName, "a destination is not a client app")
require.Empty(t, logs.ConnectionLogs[0].AppDisplayName)
require.Equal(t, clog.UserAgent.String, logs.ConnectionLogs[0].WebInfo.UserAgent)
require.Equal(t, ws.OwnerID, logs.ConnectionLogs[0].WebInfo.User.ID)
})
@@ -199,7 +257,7 @@ func TestConnectionLogs(t *testing.T) {
// user's identity; they must surface it via WebInfo.
clog := dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Time: now.Add(-time.Hour),
Type: database.ConnectionTypeTunnel,
ConnectionMethod: database.ConnectionLogMethodTunnel,
WorkspaceID: ws.ID,
OrganizationID: ws.OrganizationID,
WorkspaceOwnerID: ws.OwnerID,
@@ -240,7 +298,8 @@ func TestConnectionLogs(t *testing.T) {
ws := createWorkspace(t, db)
clog := dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Time: now.Add(-time.Hour),
Type: database.ConnectionTypeSsh,
ConnectionMethod: database.ConnectionLogMethodSSH,
AppNameOrPort: sql.NullString{String: "cursor", Valid: true},
WorkspaceID: ws.ID,
OrganizationID: ws.OrganizationID,
WorkspaceOwnerID: ws.OwnerID,
@@ -261,7 +320,7 @@ func TestConnectionLogs(t *testing.T) {
updatedClog := dbgen.ConnectionLog(t, db, database.UpsertConnectionLogParams{
Time: now,
OrganizationID: clog.OrganizationID,
Type: clog.Type,
ConnectionMethod: clog.ConnectionMethod,
WorkspaceID: clog.WorkspaceID,
WorkspaceOwnerID: clog.WorkspaceOwnerID,
WorkspaceName: clog.WorkspaceName,
@@ -290,7 +349,10 @@ func TestConnectionLogs(t *testing.T) {
require.EqualValues(t, 1, logs.Count)
require.NotNil(t, logs.ConnectionLogs[0].SSHInfo)
require.Nil(t, logs.ConnectionLogs[0].WebInfo)
require.Equal(t, codersdk.ConnectionTypeSSH, logs.ConnectionLogs[0].Type)
require.Equal(t, string(codersdk.ConnectionTypeVSCode), logs.ConnectionLogs[0].Type)
require.Equal(t, codersdk.ConnectionLogMethodSSH, logs.ConnectionLogs[0].ConnectionMethod)
require.Equal(t, "cursor", logs.ConnectionLogs[0].AppName)
require.Equal(t, "Cursor", logs.ConnectionLogs[0].AppDisplayName)
require.Equal(t, clog.ConnectionID.UUID, logs.ConnectionLogs[0].SSHInfo.ConnectionID)
require.True(t, logs.ConnectionLogs[0].SSHInfo.DisconnectTime.Equal(now))
require.Equal(t, updatedClog.DisconnectReason.String, logs.ConnectionLogs[0].SSHInfo.DisconnectReason)
+20
View File
@@ -0,0 +1,20 @@
// Code generated by typegen/main.go. DO NOT EDIT.
package codersdk
{{ range $enum := . }}
// {{ $enum.Name }} mirrors database.{{ $enum.Name }}.
type {{ $enum.Name }} string
const (
{{- range $enum.Values }}
{{ .Enum }} {{ $enum.Name }} = "{{ .Value }}"
{{- end }}
)
func (e {{ $enum.Name }}) Valid() bool {
switch e {
case {{ range $i, $v := $enum.Values }}{{ if $i }}, {{ end }}{{ $v.Enum }}{{ end }}:
return true
}
return false
}
{{ end -}}
+72 -48
View File
@@ -39,11 +39,20 @@ var scopenamesTemplate string
//go:embed countries.tstmpl
var countriesTemplate string
//go:embed dbenums.gotmpl
var dbEnumsTemplate string
// databaseEnums lists the database enums codersdk mirrors under the same name.
var databaseEnums = []string{
"ConnectionLogMethod",
}
func usage() {
_, _ = fmt.Println("Usage: typegen <type> [template]")
_, _ = fmt.Println("Types:")
_, _ = fmt.Println(" rbac <object|codersdk|typescript> - Generate RBAC related files")
_, _ = fmt.Println(" countries - Generate countries TypeScript")
_, _ = fmt.Println(" dbenums - Generate codersdk mirrors of database enums")
}
// main will generate a file based on the type and template specified.
@@ -74,6 +83,8 @@ func main() {
out, err = generateRBAC(flag.Args()[1])
case "countries":
out, err = generateCountries()
case "dbenums":
out, err = generateDatabaseEnums()
default:
_, _ = fmt.Fprintf(os.Stderr, "%q is not a valid type\n", flag.Args()[0])
usage()
@@ -129,6 +140,36 @@ func generateCountries() ([]byte, error) {
return out.Bytes(), nil
}
type databaseEnum struct {
Name string
Values []EnumValue
}
func generateDatabaseEnums() ([]byte, error) {
f, err := parser.ParseFile(token.NewFileSet(), "./coderd/database/models.go", nil, 0)
if err != nil {
return nil, xerrors.Errorf("parsing models.go: %w", err)
}
enums := make([]databaseEnum, 0, len(databaseEnums))
for _, name := range databaseEnums {
values := enumValues(f, name)
if len(values) == 0 {
return nil, xerrors.Errorf("enum %s not found in models.go", name)
}
enums = append(enums, databaseEnum{Name: name, Values: values})
}
tmpl, err := template.New("dbenums.gotmpl").Parse(dbEnumsTemplate)
if err != nil {
return nil, xerrors.Errorf("parse template: %w", err)
}
var out bytes.Buffer
if err := tmpl.Execute(&out, enums); err != nil {
return nil, xerrors.Errorf("execute template: %w", err)
}
return format.Source(out.Bytes())
}
func pascalCaseName[T ~string](name T) string {
names := strings.Split(string(name), "_")
for i := range names {
@@ -149,51 +190,37 @@ func (p Definition) FunctionName() string {
return p.Type
}
// fileActions is required because we cannot get the variable name of the enum
// at runtime. So parse the package to get it. This is purely to ensure enum
// names are consistent, which is a bit annoying, but not too bad.
func fileActions(file *ast.File) map[string]string {
// actions is a map from the enum value -> enum name
actions := make(map[string]string)
// Find the action consts
fileDeclLoop:
// enumValues returns the constants of the named string type in file, in
// source order. Constant names are not available at runtime, so parse them.
func enumValues(file *ast.File, typeName string) []EnumValue {
var values []EnumValue
for _, decl := range file.Decls {
switch typedDecl := decl.(type) {
case *ast.GenDecl:
if len(typedDecl.Specs) == 0 {
continue
}
// This is the right on, loop over all idents, pull the actions
for _, spec := range typedDecl.Specs {
vSpec, ok := spec.(*ast.ValueSpec)
if !ok {
continue fileDeclLoop
}
typeIdent, ok := vSpec.Type.(*ast.Ident)
if !ok {
continue fileDeclLoop
}
if typeIdent.Name != "Action" || len(vSpec.Values) != 1 || len(vSpec.Names) != 1 {
continue fileDeclLoop
}
literal, ok := vSpec.Values[0].(*ast.BasicLit)
if !ok {
continue fileDeclLoop
}
actions[strings.Trim(literal.Value, `"`)] = vSpec.Names[0].Name
}
default:
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.CONST {
continue
}
for _, spec := range genDecl.Specs {
vSpec, ok := spec.(*ast.ValueSpec)
if !ok || len(vSpec.Names) != 1 || len(vSpec.Values) != 1 {
continue
}
if typeIdent, ok := vSpec.Type.(*ast.Ident); !ok || typeIdent.Name != typeName {
continue
}
literal, ok := vSpec.Values[0].(*ast.BasicLit)
if !ok || literal.Kind != token.STRING {
continue
}
values = append(values, EnumValue{
Enum: vSpec.Names[0].Name,
Value: strings.Trim(literal.Value, `"`),
})
}
}
return actions
return values
}
type ActionDetails struct {
type EnumValue struct {
Enum string
Value string
}
@@ -206,17 +233,14 @@ func generateRbacObjects(templateSource string) ([]byte, error) {
if err != nil {
return nil, xerrors.Errorf("parsing policy.go: %w", err)
}
actionMap := fileActions(f)
actionList := make([]ActionDetails, 0)
for value, enum := range actionMap {
actionList = append(actionList, ActionDetails{
Enum: enum,
Value: value,
})
actionList := enumValues(f, "Action")
actionMap := make(map[string]string, len(actionList))
for _, action := range actionList {
actionMap[action.Value] = action.Enum
}
// Sorting actions for auto gen consistency.
slices.SortFunc(actionList, func(a, b ActionDetails) int {
slices.SortFunc(actionList, func(a, b EnumValue) int {
return strings.Compare(a.Enum, b.Enum)
})
@@ -225,7 +249,7 @@ func generateRbacObjects(templateSource string) ([]byte, error) {
tpl, err := template.New("object.gotmpl").Funcs(template.FuncMap{
"capitalize": utilstrings.Capitalize,
"pascalCaseName": pascalCaseName[string],
"actionsList": func() []ActionDetails {
"actionsList": func() []EnumValue {
return actionList
},
"actionsOf": func(d Definition) []string {
+34 -10
View File
@@ -3980,24 +3980,48 @@ export interface ConnectionLog {
readonly workspace_name: string;
readonly agent_name: string;
readonly ip?: string;
readonly type: ConnectionType;
/**
* WebInfo is only set when `type` is one of:
* - `ConnectionTypePortForwarding`
* - `ConnectionTypeWorkspaceApp`
* - `ConnectionTypeTunnel`
* @deprecated Use ConnectionMethod and AppName.
*/
readonly type: string;
readonly connection_method: ConnectionLogMethod;
/**
* AppName is the name of the connecting application, when known. The
* client reports it, so it is a normalized label and not a guarantee.
* Workspace app slugs and forwarded ports are reported in WebInfo.
*/
readonly app_name?: string;
/**
* AppDisplayName is the registry display name for AppName, or AppName
* itself when the app is unregistered.
*/
readonly app_display_name?: string;
/**
* WebInfo is set for connections that coderd records.
*/
readonly web_info?: ConnectionLogWebInfo;
/**
* SSHInfo is only set when `type` is one of:
* - `ConnectionTypeSSH`
* - `ConnectionTypeReconnectingPTY`
* - `ConnectionTypeVSCode`
* - `ConnectionTypeJetBrains`
* SSHInfo is set for connections that agents report.
*/
readonly ssh_info?: ConnectionLogSSHInfo;
}
// From codersdk/dbenums_gen.go
export type ConnectionLogMethod =
| "port_forwarding"
| "reconnecting_pty"
| "ssh"
| "tunnel"
| "workspace_app";
export const ConnectionLogMethods: ConnectionLogMethod[] = [
"port_forwarding",
"reconnecting_pty",
"ssh",
"tunnel",
"workspace_app",
];
// From codersdk/connectionlog.go
export interface ConnectionLogResponse {
readonly connection_logs: readonly ConnectionLog[];
@@ -1,10 +1,11 @@
import capitalize from "lodash/capitalize";
import {
type ConnectionLogMethod,
ConnectionLogMethods,
type ConnectionLogStatus,
ConnectionLogStatuses,
type ConnectionType,
ConnectionTypes,
} from "#/api/typesGenerated";
import { Alert } from "#/components/Alert/Alert";
import {
Filter,
MenuSkeleton,
@@ -27,12 +28,12 @@ import {
type OrganizationsFilterMenu,
OrganizationsMenu,
} from "#/modules/tableFiltering/options";
import { connectionTypeToFriendlyName } from "#/utils/connection";
import { docs } from "#/utils/docs";
import { connectionLogMethodLabels } from "./connectionLogMethodLabels";
type ConnectionLogFilterValues = {
status?: ConnectionLogStatus;
type?: ConnectionType;
method?: ConnectionLogMethod;
workspace_owner?: string;
organization?: string;
};
@@ -42,7 +43,7 @@ const buildConnectionLogFilterQuery = (
): string => {
const parts: string[] = [];
if (v.status) parts.push(`status:${v.status}`);
if (v.type) parts.push(`type:${v.type}`);
if (v.method) parts.push(`method:${v.method}`);
if (v.workspace_owner) parts.push(`workspace_owner:${v.workspace_owner}`);
if (v.organization) parts.push(`organization:${v.organization}`);
return parts.join(" ");
@@ -50,7 +51,7 @@ const buildConnectionLogFilterQuery = (
const CONNECTION_LOG_PRESET_FILTERS = [
{
query: buildConnectionLogFilterQuery({ status: "ongoing", type: "ssh" }),
query: buildConnectionLogFilterQuery({ status: "ongoing", method: "ssh" }),
name: "Active SSH connections",
},
] satisfies { name: string; query: string }[];
@@ -61,7 +62,7 @@ type ConnectionLogFilterProps = {
menus: {
user: UserFilterMenu;
status: StatusFilterMenu;
type: TypeFilterMenu;
method: MethodFilterMenu;
// The organization menu is only provided in a multi-org setup.
organization?: OrganizationsFilterMenu;
};
@@ -74,33 +75,46 @@ export const ConnectionLogFilter: React.FC<ConnectionLogFilterProps> = ({
}) => {
const width = menus.organization ? DEFAULT_USER_FILTER_WIDTH : undefined;
return (
<Filter
learnMoreLink={docs(
"/admin/monitoring/connection-logs#how-to-filter-connection-logs",
<>
{/* Saved links and bookmarks can still carry the deprecated filter. */}
{filter.values.type && (
<Alert severity="warning" className="mb-4">
The <code>type</code> filter is deprecated and will be removed in a
future release. Use <code>method</code> and <code>app</code> instead.
</Alert>
)}
presets={CONNECTION_LOG_PRESET_FILTERS}
isLoading={menus.user.isInitializing}
filter={filter}
error={error}
options={
<>
<UserMenu placeholder="All owners" menu={menus.user} width={width} />
<StatusMenu menu={menus.status} width={width} />
<TypeMenu menu={menus.type} width={width} />
{menus.organization && (
<OrganizationsMenu menu={menus.organization} width={width} />
)}
</>
}
optionsSkeleton={
<>
<MenuSkeleton />
<MenuSkeleton />
<MenuSkeleton />
{menus.organization && <MenuSkeleton />}
</>
}
/>
<Filter
learnMoreLink={docs(
"/admin/monitoring/connection-logs#how-to-filter-connection-logs",
)}
presets={CONNECTION_LOG_PRESET_FILTERS}
isLoading={menus.user.isInitializing}
filter={filter}
error={error}
options={
<>
<UserMenu
placeholder="All owners"
menu={menus.user}
width={width}
/>
<StatusMenu menu={menus.status} width={width} />
<MethodMenu menu={menus.method} width={width} />
{menus.organization && (
<OrganizationsMenu menu={menus.organization} width={width} />
)}
</>
}
optionsSkeleton={
<>
<MenuSkeleton />
<MenuSkeleton />
<MenuSkeleton />
{menus.organization && <MenuSkeleton />}
</>
}
/>
</>
);
};
@@ -144,39 +158,38 @@ const StatusMenu: React.FC<StatusMenuProps> = ({ menu, width }) => {
);
};
export const useTypeFilterMenu = ({
export const useMethodFilterMenu = ({
value,
onChange,
}: Pick<UseFilterMenuOptions, "value" | "onChange">) => {
const typeOptions: SelectFilterOption[] = ConnectionTypes.map((type) => {
const label: string = connectionTypeToFriendlyName(type);
return {
value: type,
label,
};
});
const methodOptions: SelectFilterOption[] = ConnectionLogMethods.map(
(method) => ({
value: method,
label: connectionLogMethodLabels[method],
}),
);
return useFilterMenu({
onChange,
value,
id: "connection_type",
id: "connection_method",
getSelectedOption: async () =>
typeOptions.find((option) => option.value === value) ?? null,
getOptions: async () => typeOptions,
methodOptions.find((option) => option.value === value) ?? null,
getOptions: async () => methodOptions,
});
};
type TypeFilterMenu = ReturnType<typeof useTypeFilterMenu>;
type MethodFilterMenu = ReturnType<typeof useMethodFilterMenu>;
type TypeMenuProps = {
menu: TypeFilterMenu;
type MethodMenuProps = {
menu: MethodFilterMenu;
width?: number;
};
const TypeMenu: React.FC<TypeMenuProps> = ({ menu, width }) => {
const MethodMenu: React.FC<MethodMenuProps> = ({ menu, width }) => {
return (
<SelectFilter
label="Filter by connection type"
placeholder="All types"
label="Filter by connection method"
placeholder="All methods"
options={menu.searchOptions}
onSelect={menu.selectOption}
selectedOption={menu.selectedOption ?? undefined}
@@ -99,7 +99,7 @@ describe("ConnectionLogPage", () => {
count_cap: 0,
});
const query = "type:ssh status:ongoing";
const query = "method:ssh status:ongoing";
await renderPage({ filter: query });
expect(getConnectionLogsSpy).toHaveBeenCalledWith({
@@ -109,6 +109,62 @@ describe("ConnectionLogPage", () => {
});
});
it("sends the selected method to the API", async () => {
const getConnectionLogsSpy = vi
.spyOn(API, "getConnectionLogs")
.mockResolvedValue({
connection_logs: [MockConnectedSSHConnectionLog],
count: 1,
count_cap: 0,
});
await renderPage();
const user = userEvent.setup();
await user.click(
screen.getByRole("button", { name: "Filter by connection method" }),
);
await user.click(
await screen.findByRole("option", { name: "Web Terminal" }),
);
await waitFor(() =>
expect(getConnectionLogsSpy).toHaveBeenLastCalledWith({
limit: DEFAULT_RECORDS_PER_PAGE,
offset: 0,
q: "method:reconnecting_pty",
}),
);
});
it("replaces a deprecated type filter when a method is selected", async () => {
const getConnectionLogsSpy = vi
.spyOn(API, "getConnectionLogs")
.mockResolvedValue({
connection_logs: [MockConnectedSSHConnectionLog],
count: 1,
count_cap: 0,
});
await renderPage({ filter: "status:ongoing type:ssh" });
expect(screen.getByRole("alert")).toHaveTextContent(
"The type filter is deprecated",
);
const user = userEvent.setup();
await user.click(
screen.getByRole("button", { name: "Filter by connection method" }),
);
await user.click(await screen.findByRole("option", { name: "SSH" }));
await waitFor(() =>
expect(getConnectionLogsSpy).toHaveBeenLastCalledWith({
limit: DEFAULT_RECORDS_PER_PAGE,
offset: 0,
q: "status:ongoing method:ssh",
}),
);
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("resets page to 1 when filter is changed", async () => {
await renderPage({ page: 2 });
@@ -116,7 +172,7 @@ describe("ConnectionLogPage", () => {
getConnectionLogsSpy.mockClear();
const filterField = screen.getByLabelText("Filter");
const query = "type:ssh status:ongoing";
const query = "method:ssh status:ongoing";
await userEvent.type(filterField, query);
await waitFor(() =>
@@ -9,7 +9,10 @@ import { useDashboard } from "#/modules/dashboard/useDashboard";
import { useFeatureVisibility } from "#/modules/dashboard/useFeatureVisibility";
import { useOrganizationsFilterMenu } from "#/modules/tableFiltering/options";
import { pageTitle } from "#/utils/page";
import { useStatusFilterMenu, useTypeFilterMenu } from "./ConnectionLogFilter";
import {
useMethodFilterMenu,
useStatusFilterMenu,
} from "./ConnectionLogFilter";
import { ConnectionLogPageView } from "./ConnectionLogPageView";
const ConnectionLogPage: React.FC = () => {
@@ -52,13 +55,14 @@ const ConnectionLogPage: React.FC = () => {
}),
});
const typeMenu = useTypeFilterMenu({
value: filter.values.type,
onChange: (option) =>
filter.update({
...filter.values,
type: option?.value,
}),
const methodMenu = useMethodFilterMenu({
value: filter.values.method,
onChange: (option) => {
// Saved links can carry the deprecated type filter, which the API
// rejects when combined with method.
const { type: _legacyType, ...values } = filter.values;
filter.update({ ...values, method: option?.value });
},
});
const organizationsMenu = useOrganizationsFilterMenu({
@@ -87,7 +91,7 @@ const ConnectionLogPage: React.FC = () => {
menus: {
user: userMenu,
status: statusMenu,
type: typeMenu,
method: methodMenu,
organization: showOrganizations ? organizationsMenu : undefined,
},
}}
@@ -28,13 +28,13 @@ const defaultFilterProps = getDefaultFilterProps<FilterProps>({
values: {
username: MockUserOwner.username,
status: undefined,
type: undefined,
method: undefined,
organization: undefined,
},
menus: {
user: MockMenu,
status: MockMenu,
type: MockMenu,
method: MockMenu,
},
});
@@ -59,6 +59,7 @@ export const PortForwardingAuthenticated: Story = {
connectionLog: {
...MockWebConnectionLog,
type: "port_forwarding",
connection_method: "port_forwarding",
web_info: {
...MockWebConnectionLog.web_info!,
slug_or_port: "8080",
@@ -80,20 +81,23 @@ export const AppUnauthenticatedRedirect: Story = {
},
};
export const VSCode: Story = {
export const SSHWithApp: Story = {
args: {
connectionLog: {
...MockWebConnectionLog,
...MockConnectedSSHConnectionLog,
type: "vscode",
app_name: "cursor",
app_display_name: "Cursor",
},
},
};
export const JetBrains: Story = {
export const SSHWithUnknownApp: Story = {
args: {
connectionLog: {
...MockWebConnectionLog,
type: "jetbrains",
...MockConnectedSSHConnectionLog,
app_name: "an_unregistered_ide",
app_display_name: "an_unregistered_ide",
},
},
};
@@ -129,11 +133,12 @@ export const TunnelDenied: Story = {
},
};
export const WebTerminal: Story = {
export const ReconnectingPTY: Story = {
args: {
connectionLog: {
...MockWebConnectionLog,
...MockConnectedSSHConnectionLog,
type: "reconnecting_pty",
connection_method: "reconnecting_pty",
},
},
};
@@ -1,7 +1,7 @@
import { Link as RouterLink } from "react-router";
import type { ConnectionLog } from "#/api/typesGenerated";
import { Link } from "#/components/Link/Link";
import { connectionTypeToFriendlyName } from "#/utils/connection";
import { connectionLogMethodLabels } from "../../connectionLogMethodLabels";
type ConnectionLogDescriptionProps = {
connectionLog: ConnectionLog;
@@ -10,16 +10,21 @@ type ConnectionLogDescriptionProps = {
export const ConnectionLogDescription: React.FC<
ConnectionLogDescriptionProps
> = ({ connectionLog }) => {
const { type, workspace_owner_username, workspace_name, web_info } =
connectionLog;
const {
connection_method,
app_display_name,
workspace_owner_username,
workspace_name,
web_info,
} = connectionLog;
switch (type) {
switch (connection_method) {
case "port_forwarding":
case "workspace_app": {
if (!web_info) return null;
const { user, slug_or_port, status_code } = web_info;
const isPortForward = type === "port_forwarding";
const isPortForward = connection_method === "port_forwarding";
const presentAction = isPortForward ? "access" : "open";
const pastAction = isPortForward ? "accessed" : "opened";
@@ -71,14 +76,22 @@ export const ConnectionLogDescription: React.FC<
);
}
case "reconnecting_pty":
case "ssh":
case "jetbrains":
case "vscode": {
const friendlyType = connectionTypeToFriendlyName(type);
case "reconnecting_pty": {
const methodName = connectionLogMethodLabels[connection_method];
return (
<span>
{friendlyType} session to {workspace_owner_username}'s{" "}
{app_display_name ? (
<>
{app_display_name}{" "}
<span className="text-xs text-content-secondary">
({methodName})
</span>
</>
) : (
methodName
)}{" "}
session to {workspace_owner_username}'s{" "}
<Link asChild showExternalIcon={false} className="text-base">
<RouterLink to={`/@${workspace_owner_username}/${workspace_name}`}>
<strong>{workspace_name}</strong>
@@ -12,7 +12,6 @@ import {
TooltipContent,
TooltipTrigger,
} from "#/components/Tooltip/Tooltip";
import { connectionTypeIsWeb } from "#/utils/connection";
import { ConnectionLogDescription } from "./ConnectionLogDescription/ConnectionLogDescription";
type ConnectionLogRowProps = {
@@ -25,7 +24,7 @@ export const ConnectionLogRow: React.FC<ConnectionLogRowProps> = ({
const userAgent = connectionLog.web_info?.user_agent
? userAgentParser(connectionLog.web_info?.user_agent)
: undefined;
const isWeb = connectionTypeIsWeb(connectionLog.type);
const isWeb = connectionLog.web_info !== undefined;
const code =
connectionLog.web_info?.status_code ?? connectionLog.ssh_info?.exit_code;
@@ -0,0 +1,9 @@
import type { ConnectionLogMethod } from "#/api/typesGenerated";
export const connectionLogMethodLabels: Record<ConnectionLogMethod, string> = {
ssh: "SSH",
reconnecting_pty: "Web Terminal",
workspace_app: "Workspace App",
port_forwarding: "Port Forwarding",
tunnel: "Tunnel",
};
+4
View File
@@ -3110,6 +3110,7 @@ export const MockWebConnectionLog: TypesGen.ConnectionLog = {
agent_name: "dev",
ip: "127.0.0.1",
type: "workspace_app",
connection_method: "workspace_app",
web_info: {
user_agent:
'"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"',
@@ -3129,6 +3130,7 @@ const MockTunnelWebInfo: TypesGen.ConnectionLogWebInfo = {
export const MockTunnelConnectionLog: TypesGen.ConnectionLog = {
...MockWebConnectionLog,
type: "tunnel",
connection_method: "tunnel",
web_info: MockTunnelWebInfo,
};
@@ -3157,6 +3159,7 @@ export const MockConnectedSSHConnectionLog: TypesGen.ConnectionLog = {
agent_name: "dev",
ip: "127.0.0.1",
type: "ssh",
connection_method: "ssh",
ssh_info: {
connection_id: "026c8c11-fc5c-4df8-a286-5fe6d7f54f98",
disconnect_reason: undefined,
@@ -3181,6 +3184,7 @@ export const MockDisconnectedSSHConnectionLog: TypesGen.ConnectionLog = {
agent_name: "dev",
ip: "127.0.0.1",
type: "ssh",
connection_method: "ssh",
ssh_info: {
connection_id: "026c8c11-fc5c-4df8-a286-5fe6d7f54f98",
disconnect_reason: "server shut down",
-41
View File
@@ -1,41 +0,0 @@
import type { ConnectionType } from "#/api/typesGenerated";
export const connectionTypeToFriendlyName = (type: ConnectionType): string => {
switch (type) {
case "jetbrains":
return "JetBrains";
case "reconnecting_pty":
return "Web Terminal";
case "ssh":
return "SSH";
case "vscode":
return "VS Code";
case "port_forwarding":
return "Port Forwarding";
case "workspace_app":
return "Workspace App";
case "tunnel":
return "Tunnel";
}
};
// connectionTypeIsWeb returns true for connection types reported by
// coderd from an HTTP request. These carry `web_info` (user, IP, user
// agent, HTTP status code) rather than agent-reported `ssh_info`, and
// are not necessarily browser connections (tunnels are typically
// established by the CLI or an IDE extension).
export const connectionTypeIsWeb = (type: ConnectionType): boolean => {
switch (type) {
case "port_forwarding":
case "workspace_app":
case "tunnel": {
return true;
}
case "reconnecting_pty":
case "ssh":
case "jetbrains":
case "vscode": {
return false;
}
}
};