2023-04-04 10:59:41 +10:00
package workspaceapps
import (
"context"
"database/sql"
"fmt"
"net/http"
"net/url"
2023-04-17 14:57:21 -05:00
"path"
2025-03-03 21:46:49 +08:00
"slices"
2023-04-17 14:57:21 -05:00
"strings"
2025-03-18 13:50:52 +02:00
"sync/atomic"
2023-04-04 10:59:41 +10:00
"time"
2025-03-18 13:50:52 +02:00
"github.com/go-jose/go-jose/v4/jwt"
"github.com/google/uuid"
2023-04-04 10:59:41 +10:00
"golang.org/x/xerrors"
2026-01-08 10:29:41 +04:00
"cdr.dev/slog/v3"
2025-07-15 14:36:06 +10:00
"github.com/coder/coder/v2/coderd/connectionlog"
2024-10-25 17:14:35 +01:00
"github.com/coder/coder/v2/coderd/cryptokeys"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
2025-03-18 13:50:52 +02:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
2024-10-25 17:14:35 +01:00
"github.com/coder/coder/v2/coderd/jwtutils"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/rbac"
2024-05-15 09:46:35 -05:00
"github.com/coder/coder/v2/coderd/rbac/policy"
2025-03-18 13:50:52 +02:00
"github.com/coder/coder/v2/coderd/tracing"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
2023-04-04 10:59:41 +10:00
)
// DBTokenProvider provides authentication and authorization for workspace apps
// by querying the database if the request is missing a valid token.
type DBTokenProvider struct {
Logger slog . Logger
2025-11-20 13:01:50 +04:00
ctx context . Context
2023-04-04 10:59:41 +10:00
2023-04-17 14:57:21 -05:00
// DashboardURL is the main dashboard access URL for error pages.
2025-03-18 13:50:52 +02:00
DashboardURL * url . URL
Authorizer rbac . Authorizer
2025-07-15 14:36:06 +10:00
ConnectionLogger * atomic . Pointer [ connectionlog . ConnectionLogger ]
2025-03-18 13:50:52 +02:00
Database database . Store
DeploymentValues * codersdk . DeploymentValues
OAuth2Configs * httpmw . OAuth2Configs
WorkspaceAgentInactiveTimeout time . Duration
WorkspaceAppAuditSessionTimeout time . Duration
Keycache cryptokeys . SigningKeycache
2023-04-04 10:59:41 +10:00
}
var _ SignedTokenProvider = & DBTokenProvider {}
2025-11-20 13:01:50 +04:00
func NewDBTokenProvider ( ctx context . Context ,
log slog . Logger ,
2024-10-25 17:14:35 +01:00
accessURL * url . URL ,
authz rbac . Authorizer ,
2025-07-15 14:36:06 +10:00
connectionLogger * atomic . Pointer [ connectionlog . ConnectionLogger ],
2024-10-25 17:14:35 +01:00
db database . Store ,
cfg * codersdk . DeploymentValues ,
oauth2Cfgs * httpmw . OAuth2Configs ,
workspaceAgentInactiveTimeout time . Duration ,
2025-03-18 13:50:52 +02:00
workspaceAppAuditSessionTimeout time . Duration ,
2024-10-25 17:14:35 +01:00
signer cryptokeys . SigningKeycache ,
) SignedTokenProvider {
2023-04-04 10:59:41 +10:00
if workspaceAgentInactiveTimeout == 0 {
workspaceAgentInactiveTimeout = 1 * time . Minute
}
2025-03-18 13:50:52 +02:00
if workspaceAppAuditSessionTimeout == 0 {
workspaceAppAuditSessionTimeout = time . Hour
}
2023-04-04 10:59:41 +10:00
return & DBTokenProvider {
2025-03-18 13:50:52 +02:00
Logger : log ,
2025-11-20 13:01:50 +04:00
ctx : ctx ,
2025-03-18 13:50:52 +02:00
DashboardURL : accessURL ,
Authorizer : authz ,
2025-07-15 14:36:06 +10:00
ConnectionLogger : connectionLogger ,
2025-03-18 13:50:52 +02:00
Database : db ,
DeploymentValues : cfg ,
OAuth2Configs : oauth2Cfgs ,
WorkspaceAgentInactiveTimeout : workspaceAgentInactiveTimeout ,
WorkspaceAppAuditSessionTimeout : workspaceAppAuditSessionTimeout ,
Keycache : signer ,
2023-04-04 10:59:41 +10:00
}
}
2023-04-17 14:57:21 -05:00
func ( p * DBTokenProvider ) FromRequest ( r * http . Request ) ( * SignedToken , bool ) {
2024-10-25 17:14:35 +01:00
return FromRequest ( r , p . Keycache )
2023-04-04 10:59:41 +10:00
}
2023-04-17 14:57:21 -05:00
func ( p * DBTokenProvider ) Issue ( ctx context . Context , rw http . ResponseWriter , r * http . Request , issueReq IssueTokenRequest ) ( * SignedToken , string , bool ) {
2023-04-04 10:59:41 +10:00
// nolint:gocritic // We need to make a number of database calls. Setting a system context here
// // is simpler than calling dbauthz.AsSystemRestricted on every call.
// // dangerousSystemCtx is only used for database calls. The actual authentication
// // logic is handled in Provider.authorizeWorkspaceApp which directly checks the actor's
// // permissions.
dangerousSystemCtx := dbauthz . AsSystemRestricted ( ctx )
2025-11-20 13:01:50 +04:00
aReq , commitAudit := p . connLogInitRequest ( rw , r )
2025-03-18 13:50:52 +02:00
defer commitAudit ()
2023-04-17 14:57:21 -05:00
appReq := issueReq . AppRequest . Normalize ()
2024-10-25 17:14:35 +01:00
err := appReq . Check ()
2023-04-04 10:59:41 +10:00
if err != nil {
2023-04-17 14:57:21 -05:00
WriteWorkspaceApp500 ( p . Logger , p . DashboardURL , rw , r , & appReq , err , "invalid app request" )
2023-04-04 10:59:41 +10:00
return nil , "" , false
}
token := SignedToken {
Request : appReq ,
}
// We use the regular API apiKey extraction middleware fn here to avoid any
// differences in behavior between the two.
apiKey , authz , ok := httpmw . ExtractAPIKey ( rw , r , httpmw . ExtractAPIKeyConfig {
DB : p . Database ,
OAuth2Configs : p . OAuth2Configs ,
RedirectToLogin : false ,
2024-04-10 10:34:49 -05:00
DisableSessionExpiryRefresh : p . DeploymentValues . Sessions . DisableExpiryRefresh . Value (),
2023-04-17 14:57:21 -05:00
// Optional is true to allow for public apps. If the authorization check
// (later on) fails and the user is not authenticated, they will be
// redirected to the login page or app auth endpoint using code below.
2023-04-04 10:59:41 +10:00
Optional : true ,
2025-03-26 01:56:39 -05:00
SessionTokenFunc : func ( _ * http . Request ) string {
2023-04-17 14:57:21 -05:00
return issueReq . SessionToken
},
2023-04-04 10:59:41 +10:00
})
if ! ok {
return nil , "" , false
}
2025-03-18 13:50:52 +02:00
aReq . apiKey = apiKey // Update audit request.
2023-04-04 10:59:41 +10:00
// Lookup workspace app details from DB.
dbReq , err := appReq . getDatabase ( dangerousSystemCtx , p . Database )
2025-03-26 01:56:39 -05:00
switch {
case xerrors . Is ( err , sql . ErrNoRows ):
2023-09-19 16:54:51 -05:00
WriteWorkspaceApp404 ( p . Logger , p . DashboardURL , rw , r , & appReq , nil , err . Error ())
2023-04-04 10:59:41 +10:00
return nil , "" , false
2025-03-26 01:56:39 -05:00
case xerrors . Is ( err , errWorkspaceStopped ):
2024-01-17 12:06:59 -06:00
WriteWorkspaceOffline ( p . Logger , p . DashboardURL , rw , r , & appReq )
return nil , "" , false
2025-03-26 01:56:39 -05:00
case err != nil :
2023-04-17 14:57:21 -05:00
WriteWorkspaceApp500 ( p . Logger , p . DashboardURL , rw , r , & appReq , err , "get app details from database" )
2023-04-04 10:59:41 +10:00
return nil , "" , false
}
2025-03-18 13:50:52 +02:00
aReq . dbReq = dbReq // Update audit request.
2026-01-19 12:36:33 +00:00
token . UserID = dbReq . UserID
2023-04-04 10:59:41 +10:00
token . WorkspaceID = dbReq . Workspace . ID
token . AgentID = dbReq . Agent . ID
2023-04-17 14:57:21 -05:00
if dbReq . AppURL != nil {
token . AppURL = dbReq . AppURL . String ()
}
2025-07-30 13:42:39 -07:00
token . CORSBehavior = codersdk . CORSBehavior ( dbReq . CorsBehavior )
2023-04-04 10:59:41 +10:00
// Verify the user has access to the app.
2023-09-19 16:54:51 -05:00
authed , warnings , err := p . authorizeRequest ( r . Context (), authz , dbReq )
2023-04-04 10:59:41 +10:00
if err != nil {
2023-04-17 14:57:21 -05:00
WriteWorkspaceApp500 ( p . Logger , p . DashboardURL , rw , r , & appReq , err , "verify authz" )
2023-04-04 10:59:41 +10:00
return nil , "" , false
}
if ! authed {
if apiKey != nil {
// The request has a valid API key but insufficient permissions.
2023-09-19 16:54:51 -05:00
WriteWorkspaceApp404 ( p . Logger , p . DashboardURL , rw , r , & appReq , warnings , "insufficient permissions" )
2023-04-04 10:59:41 +10:00
return nil , "" , false
}
// Redirect to login as they don't have permission to access the app
// and they aren't signed in.
2023-04-17 14:57:21 -05:00
// We don't support login redirects for the terminal since it's a
// WebSocket endpoint and redirects won't work. The token must be
// specified as a query parameter.
if appReq . AccessMethod == AccessMethodTerminal {
2023-04-04 10:59:41 +10:00
httpapi . ResourceNotFound ( rw )
2023-04-17 14:57:21 -05:00
return nil , "" , false
2023-04-04 10:59:41 +10:00
}
2023-04-17 14:57:21 -05:00
appBaseURL , err := issueReq . AppBaseURL ()
if err != nil {
WriteWorkspaceApp500 ( p . Logger , p . DashboardURL , rw , r , & appReq , err , "get app base URL" )
return nil , "" , false
}
// If the app is a path app and it's on the same host as the dashboard
// access URL, then we need to redirect to login using the standard
// login redirect function.
if appReq . AccessMethod == AccessMethodPath && appBaseURL . Host == p . DashboardURL . Host {
httpmw . RedirectToLogin ( rw , r , p . DashboardURL , httpmw . SignedOutErrorMessage )
return nil , "" , false
}
// Otherwise, we need to redirect to the app auth endpoint, which will
// redirect back to the app (with an encrypted API key) after the user
// has logged in.
//
// TODO: We should just make this a "BrowserURL" field on the issue struct. Then
// we can remove this logic and just defer to that. It can be set closer to the
// actual initial request that makes the IssueTokenRequest. Eg the external moon.
// This would replace RawQuery and AppPath fields.
redirectURI := * appBaseURL
if dbReq . AppURL != nil {
// Just use the user's current path and query if set.
if issueReq . AppPath != "" {
redirectURI . Path = path . Join ( redirectURI . Path , issueReq . AppPath )
} else if ! strings . HasSuffix ( redirectURI . Path , "/" ) {
redirectURI . Path += "/"
}
q := issueReq . AppQuery
if q != "" && dbReq . AppURL . RawQuery != "" {
q = dbReq . AppURL . RawQuery
}
redirectURI . RawQuery = q
}
// This endpoint accepts redirect URIs from the primary app wildcard
// host, proxy access URLs and proxy wildcard app hosts. It does not
// accept redirect URIs from the primary access URL or any other host.
u := * p . DashboardURL
u . Path = "/api/v2/applications/auth-redirect"
q := u . Query ()
q . Add ( RedirectURIQueryParam , redirectURI . String ())
u . RawQuery = q . Encode ()
http . Redirect ( rw , r , u . String (), http . StatusSeeOther )
2023-04-04 10:59:41 +10:00
return nil , "" , false
}
// Check that the agent is online.
2026-04-14 22:23:06 -07:00
agentStatus := dbReq . Agent . Status ( dbtime . Now (), p . WorkspaceAgentInactiveTimeout )
2023-04-04 10:59:41 +10:00
if agentStatus . Status != database . WorkspaceAgentStatusConnected {
2023-04-17 14:57:21 -05:00
WriteWorkspaceAppOffline ( p . Logger , p . DashboardURL , rw , r , & appReq , fmt . Sprintf ( "Agent state is %q, not %q" , agentStatus . Status , database . WorkspaceAgentStatusConnected ))
2023-04-04 10:59:41 +10:00
return nil , "" , false
}
2024-02-12 22:30:49 -08:00
// This is where we used to check app health, but we don't do that anymore
// in case there are bugs with the healthcheck code that lock users out of
// their apps completely.
2023-04-04 10:59:41 +10:00
// As a sanity check, ensure the token we just made is valid for this
// request.
if ! token . MatchesRequest ( appReq ) {
2023-04-17 14:57:21 -05:00
WriteWorkspaceApp500 ( p . Logger , p . DashboardURL , rw , r , & appReq , nil , "fresh token does not match request" )
2023-04-04 10:59:41 +10:00
return nil , "" , false
}
2024-10-25 17:14:35 +01:00
token . RegisteredClaims = jwtutils . RegisteredClaims {
Expiry : jwt . NewNumericDate ( time . Now (). Add ( DefaultTokenExpiry )),
}
2023-04-04 10:59:41 +10:00
// Sign the token.
2024-10-25 17:14:35 +01:00
tokenStr , err := jwtutils . Sign ( ctx , p . Keycache , token )
2023-04-04 10:59:41 +10:00
if err != nil {
2023-04-17 14:57:21 -05:00
WriteWorkspaceApp500 ( p . Logger , p . DashboardURL , rw , r , & appReq , err , "generate token" )
2023-04-04 10:59:41 +10:00
return nil , "" , false
}
return & token , tokenStr , true
}
2025-06-16 16:15:59 -06:00
// authorizeRequest returns true if the request is authorized. The returned []string
2023-09-19 16:54:51 -05:00
// are warnings that aid in debugging. These messages do not prevent authorization,
// but may indicate that the request is not configured correctly.
// If an error is returned, the request should be aborted with a 500 error.
2024-03-29 10:14:27 -05:00
func ( p * DBTokenProvider ) authorizeRequest ( ctx context . Context , roles * rbac . Subject , dbReq * databaseRequest ) ( bool , [] string , error ) {
2023-09-19 16:54:51 -05:00
var warnings [] string
2023-04-04 10:59:41 +10:00
accessMethod := dbReq . AccessMethod
if accessMethod == "" {
accessMethod = AccessMethodPath
}
isPathApp := accessMethod == AccessMethodPath
// If path-based app sharing is disabled (which is the default), we can
// force the sharing level to be "owner" so that the user can only access
// their own apps.
//
// Site owners are blocked from accessing path-based apps unless the
// Dangerous.AllowPathAppSiteOwnerAccess flag is enabled in the check below.
sharingLevel := dbReq . AppSharingLevel
if isPathApp && ! p . DeploymentValues . Dangerous . AllowPathAppSharing . Value () {
2023-09-19 16:54:51 -05:00
if dbReq . AppSharingLevel != database . AppSharingLevelOwner {
// This is helpful for debugging, and ok to leak to the user.
// This is because the app has the sharing level set to something that
// should be shared, but we are disabling it from a deployment wide
// flag. So the template should be fixed to set the sharing level to
// "owner" instead and this will not appear.
warnings = append ( warnings , fmt . Sprintf ( "unable to use configured sharing level %q because path-based app sharing is disabled (see --dangerous-allow-path-app-sharing), using sharing level \"owner\" instead" , sharingLevel ))
}
2023-04-04 10:59:41 +10:00
sharingLevel = database . AppSharingLevelOwner
}
// Short circuit if not authenticated.
if roles == nil {
// The user is not authenticated, so they can only access the app if it
// is public.
2023-09-19 16:54:51 -05:00
return sharingLevel == database . AppSharingLevelPublic , warnings , nil
2023-04-04 10:59:41 +10:00
}
// Block anyone from accessing workspaces they don't own in path-based apps
// unless the admin disables this security feature. This blocks site-owners
// from accessing any apps from any user's workspaces.
//
// When the Dangerous.AllowPathAppSharing flag is not enabled, the sharing
// level will be forced to "owner", so this check will always be true for
// workspaces owned by different users.
if isPathApp &&
sharingLevel == database . AppSharingLevelOwner &&
2024-03-29 10:14:27 -05:00
dbReq . Workspace . OwnerID . String () != roles . ID &&
2023-04-04 10:59:41 +10:00
! p . DeploymentValues . Dangerous . AllowPathAppSiteOwnerAccess . Value () {
2023-09-19 16:54:51 -05:00
// This is not ideal to check for the 'owner' role, but we are only checking
// to determine whether to show a warning for debugging reasons. This does
// not do any authz checks, so it is ok.
2025-06-16 16:15:59 -06:00
if slices . Contains ( roles . Roles . Names (), rbac . RoleOwner ()) {
2023-09-19 16:54:51 -05:00
warnings = append ( warnings , "path-based apps with \"owner\" share level are only accessible by the workspace owner (see --dangerous-allow-path-app-site-owner-access)" )
}
return false , warnings , nil
2023-04-04 10:59:41 +10:00
}
// Figure out which RBAC resource to check. For terminals we use execution
// instead of application connect.
var (
2026-08-21 23:46:27 -06:00
rbacAction = policy . ActionApplicationConnect
rbacResource = dbReq . Workspace . RBACObject ()
2023-04-04 10:59:41 +10:00
// rbacResourceOwned is for the level "authenticated". We still need to
// make sure the API key has permissions to connect to the actor's own
// workspace. Scopes would prevent this.
2025-10-27 17:14:16 -06:00
// TODO: This is an odd repercussion of the org_member permission level.
// This Object used to not specify an org restriction, and `InOrg` would
// actually have a significantly different meaning (only sharing with
// other authenticated users in the same org, whereas the existing behavior
// is to share with any authenticated user). Because workspaces are always
// jointly owned by an organization, there _must_ be an org restriction on
// the object to check the proper permissions. AnyOrg is almost the same,
// but technically excludes users who are not in any organization. This is
// the closest we can get though without more significant refactoring.
2026-08-21 23:46:27 -06:00
rbacResourceOwned = rbac . ResourceWorkspace . WithOwner ( roles . ID ). AnyOrganization ()
2023-04-04 10:59:41 +10:00
)
if dbReq . AccessMethod == AccessMethodTerminal {
2024-05-15 11:09:42 -05:00
rbacAction = policy . ActionSSH
2023-04-04 10:59:41 +10:00
}
// Do a standard RBAC check. This accounts for share level "owner" and any
// other RBAC rules that may be in place.
//
// Regardless of share level or whether it's enabled or not, the owner of
// the workspace can always access applications (as long as their API key's
// scope allows it).
2024-03-29 10:14:27 -05:00
err := p . Authorizer . Authorize ( ctx , * roles , rbacAction , rbacResource )
2023-04-04 10:59:41 +10:00
if err == nil {
2023-09-19 16:54:51 -05:00
return true , [] string {}, nil
2023-04-04 10:59:41 +10:00
}
switch sharingLevel {
case database . AppSharingLevelOwner :
// We essentially already did this above with the regular RBAC check.
// Owners can always access their own apps according to RBAC rules, so
// they have already been returned from this function.
case database . AppSharingLevelAuthenticated :
// Check with the owned resource to ensure the API key has permissions
// to connect to the actor's own workspace. This enforces scopes.
2024-03-29 10:14:27 -05:00
err := p . Authorizer . Authorize ( ctx , * roles , rbacAction , rbacResourceOwned )
2023-04-04 10:59:41 +10:00
if err == nil {
2023-09-19 16:54:51 -05:00
return true , [] string {}, nil
2023-04-04 10:59:41 +10:00
}
2025-06-16 16:15:59 -06:00
case database . AppSharingLevelOrganization :
// First check if they have permission to connect to their own workspace (enforces scopes)
err := p . Authorizer . Authorize ( ctx , * roles , rbacAction , rbacResourceOwned )
if err != nil {
return false , warnings , nil
}
2026-04-16 00:12:54 +10:00
// Check if the user is a member of the same organization as the workspace.
2025-06-16 16:15:59 -06:00
workspaceOrgID := dbReq . Workspace . OrganizationID
2026-04-16 00:12:54 +10:00
isMember , err := roles . HasOrganizationMembership ( workspaceOrgID )
2025-06-16 16:15:59 -06:00
if err != nil {
2026-04-16 00:12:54 +10:00
return false , warnings , xerrors . Errorf ( "check organization membership: %w" , err )
2025-06-16 16:15:59 -06:00
}
2026-04-16 00:12:54 +10:00
if isMember {
return true , [] string {}, nil
2025-06-16 16:15:59 -06:00
}
2026-04-16 00:12:54 +10:00
// User is not a member of the workspace's organization.
2025-06-16 16:15:59 -06:00
return false , warnings , nil
2023-04-04 10:59:41 +10:00
case database . AppSharingLevelPublic :
// We don't really care about scopes and stuff if it's public anyways.
// Someone with a restricted-scope API key could just not submit the API
// key cookie in the request and access the page.
2023-09-19 16:54:51 -05:00
return true , [] string {}, nil
2023-04-04 10:59:41 +10:00
}
// No checks were successful.
2023-09-19 16:54:51 -05:00
return false , warnings , nil
2023-04-04 10:59:41 +10:00
}
2025-03-18 13:50:52 +02:00
2025-07-15 14:36:06 +10:00
type connLogRequest struct {
2025-03-18 13:50:52 +02:00
time time . Time
apiKey * database . APIKey
dbReq * databaseRequest
}
2025-07-15 14:36:06 +10:00
// connLogInitRequest creates a new connection log session and connect log for the
// given request, if one does not already exist. If a connection log session
// already exists, it will be updated with the current timestamp. A session is used to
// reduce the number of connection logs created.
2025-03-18 13:50:52 +02:00
//
// A session is unique to the agent, app, user and users IP. If any of these
2025-07-15 14:36:06 +10:00
// values change, a new session and connect log is created.
2025-11-20 13:01:50 +04:00
func ( p * DBTokenProvider ) connLogInitRequest ( w http . ResponseWriter , r * http . Request ) ( aReq * connLogRequest , commit func ()) {
2025-03-18 13:50:52 +02:00
// Get the status writer from the request context so we can figure
// out the HTTP status and autocommit the audit log.
sw , ok := w .( * tracing . StatusWriter )
if ! ok {
panic ( "dev error: http.ResponseWriter is not *tracing.StatusWriter" )
}
2025-07-15 14:36:06 +10:00
aReq = & connLogRequest {
2025-03-18 13:50:52 +02:00
time : dbtime . Now (),
}
2025-07-15 14:36:06 +10:00
// Set the commit function on the status writer to create a connection log
// this ensures that the status and response body are available.
2025-03-18 13:50:52 +02:00
var committed bool
return aReq , func () {
2025-11-20 13:01:50 +04:00
// We want to log/audit the connection attempt even if the request context has expired.
ctx , cancel := context . WithCancel ( p . ctx )
defer cancel ()
2025-03-18 13:50:52 +02:00
if committed {
return
}
committed = true
if aReq . dbReq == nil {
// App doesn't exist, there's information in the Request
2025-07-15 14:36:06 +10:00
// struct but we need UUIDs for connection logging.
2025-03-18 13:50:52 +02:00
return
}
userID := uuid . Nil
if aReq . apiKey != nil {
userID = aReq . apiKey . UserID
}
userAgent := r . UserAgent ()
ip := r . RemoteAddr
// Approximation of the status code.
2025-07-15 14:36:06 +10:00
// #nosec G115 - Safe conversion as HTTP status code is expected to be within int32 range (typically 100-599)
2026-08-21 23:46:27 -06:00
statusCode := int32 ( sw . Status )
2025-03-18 13:50:52 +02:00
if statusCode == 0 {
statusCode = http . StatusOK
}
2025-07-15 14:36:06 +10:00
var (
connType database . ConnectionType
slugOrPort = aReq . dbReq . AppSlugOrPort
)
2025-03-18 13:50:52 +02:00
switch {
case aReq . dbReq . AccessMethod == AccessMethodTerminal :
2025-07-15 14:36:06 +10:00
connType = database . ConnectionTypeWorkspaceApp
slugOrPort = "terminal"
2025-03-18 13:50:52 +02:00
case aReq . dbReq . App . ID == uuid . Nil :
2025-07-15 14:36:06 +10:00
connType = database . ConnectionTypePortForwarding
default :
connType = database . ConnectionTypeWorkspaceApp
2025-03-18 13:50:52 +02:00
}
2026-07-28 15:30:12 -05:00
// An empty slug_or_port is reserved for tunnel sessions (see
// coderd/workspaceagents.go logTunnelConnection); writing one
// here would collide with them in the audit session dedupe
// index. Request.Check rejects empty slugs, so this is
// unreachable today.
if slugOrPort == "" {
p . Logger . Critical ( ctx , "workspace app audit session has empty slug_or_port, skipping connection log" ,
slog . F ( "workspace_id" , aReq . dbReq . Workspace . ID ),
slog . F ( "agent_id" , aReq . dbReq . Agent . ID ),
slog . F ( "app_id" , aReq . dbReq . App . ID ),
)
return
}
2025-03-18 13:50:52 +02:00
// If we end up logging, ensure relevant fields are set.
logger := p . Logger . With (
slog . F ( "workspace_id" , aReq . dbReq . Workspace . ID ),
slog . F ( "agent_id" , aReq . dbReq . Agent . ID ),
slog . F ( "app_id" , aReq . dbReq . App . ID ),
slog . F ( "user_id" , userID ),
slog . F ( "user_agent" , userAgent ),
2025-07-15 14:36:06 +10:00
slog . F ( "app_slug_or_port" , slugOrPort ),
2025-03-18 13:50:52 +02:00
slog . F ( "status_code" , statusCode ),
)
2025-03-20 16:10:45 +02:00
var newOrStale bool
2025-03-18 13:50:52 +02:00
err := p . Database . InTx ( func ( tx database . Store ) ( err error ) {
// nolint:gocritic // System context is needed to write audit sessions.
dangerousSystemCtx := dbauthz . AsSystemRestricted ( ctx )
2025-03-20 16:10:45 +02:00
newOrStale , err = tx . UpsertWorkspaceAppAuditSession ( dangerousSystemCtx , database . UpsertWorkspaceAppAuditSessionParams {
2025-03-18 13:50:52 +02:00
// Config.
StaleIntervalMS : p . WorkspaceAppAuditSessionTimeout . Milliseconds (),
// Data.
2025-03-20 16:10:45 +02:00
ID : uuid . New (),
2025-03-18 13:50:52 +02:00
AgentID : aReq . dbReq . Agent . ID ,
AppID : aReq . dbReq . App . ID , // Can be unset, in which case uuid.Nil is fine.
UserID : userID , // Can be unset, in which case uuid.Nil is fine.
Ip : ip ,
UserAgent : userAgent ,
2025-07-15 14:36:06 +10:00
SlugOrPort : slugOrPort ,
StatusCode : statusCode ,
2025-03-18 13:50:52 +02:00
StartedAt : aReq . time ,
UpdatedAt : aReq . time ,
})
if err != nil {
return xerrors . Errorf ( "insert workspace app audit session: %w" , err )
}
return nil
}, nil )
if err != nil {
logger . Error ( ctx , "update workspace app audit session failed" , slog . Error ( err ))
2025-07-15 14:36:06 +10:00
// Avoid spamming the connection log if deduplication failed, this should
2025-03-18 13:50:52 +02:00
// only happen if there are problems communicating with the database.
return
}
2025-03-20 16:10:45 +02:00
if ! newOrStale {
// We either didn't insert a new session, or the session
// didn't timeout due to inactivity.
2025-03-18 13:50:52 +02:00
return
}
2025-07-15 14:36:06 +10:00
connLogger := * p . ConnectionLogger . Load ()
err = connLogger . Upsert ( ctx , database . UpsertConnectionLogParams {
ID : uuid . New (),
Time : aReq . time ,
OrganizationID : aReq . dbReq . Workspace . OrganizationID ,
WorkspaceOwnerID : aReq . dbReq . Workspace . OwnerID ,
WorkspaceID : aReq . dbReq . Workspace . ID ,
WorkspaceName : aReq . dbReq . Workspace . Name ,
AgentName : aReq . dbReq . Agent . Name ,
Type : connType ,
Code : sql . NullInt32 {
Int32 : statusCode ,
Valid : true ,
},
2026-04-03 15:47:26 -05:00
IP : database . ParseIP ( ip ),
2025-07-15 14:36:06 +10:00
UserAgent : sql . NullString { Valid : userAgent != "" , String : userAgent },
UserID : uuid . NullUUID {
UUID : userID ,
Valid : userID != uuid . Nil ,
},
SlugOrPort : sql . NullString { Valid : slugOrPort != "" , String : slugOrPort },
ConnectionStatus : database . ConnectionStatusConnected ,
// N/A
ConnectionID : uuid . NullUUID {},
DisconnectReason : sql . NullString {},
})
2025-03-18 13:50:52 +02:00
if err != nil {
2025-07-15 14:36:06 +10:00
logger . Error ( ctx , "upsert connection log failed" , slog . Error ( err ))
return
2025-03-18 13:50:52 +02:00
}
}
}