2025-05-29 12:15:47 +01:00
package agentapi
import (
"context"
2025-06-25 17:36:23 +01:00
"crypto/sha256"
2025-06-05 11:57:02 +01:00
"database/sql"
2025-06-25 17:36:23 +01:00
"encoding/base32"
2025-06-05 11:57:02 +01:00
"errors"
"fmt"
2025-06-16 16:15:59 -06:00
"strings"
2026-06-05 16:30:15 +01:00
"sync/atomic"
2025-05-29 12:15:47 +01:00
"github.com/google/uuid"
"github.com/sqlc-dev/pqtype"
"golang.org/x/xerrors"
2026-01-08 10:29:41 +04:00
"cdr.dev/slog/v3"
2025-05-29 12:15:47 +01:00
agentproto "github.com/coder/coder/v2/agent/proto"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
2026-06-05 16:30:15 +01:00
"github.com/coder/coder/v2/coderd/portsharing"
2025-06-05 11:57:02 +01:00
"github.com/coder/coder/v2/codersdk"
2025-05-29 12:15:47 +01:00
"github.com/coder/coder/v2/provisioner"
2026-01-08 15:24:11 +04:00
"github.com/coder/quartz"
2025-05-29 12:15:47 +01:00
)
2026-10-27 14:44:25 +03:00
// sessionTokenPlaceholder stands for the viewer's session token in external
// app URLs.
const sessionTokenPlaceholder = "$SESSION_TOKEN"
2025-05-29 12:15:47 +01:00
type SubAgentAPI struct {
OwnerID uuid . UUID
OrganizationID uuid . UUID
AgentFn func ( context . Context ) ( database . WorkspaceAgent , error )
2026-06-05 16:30:15 +01:00
Log slog . Logger
Clock quartz . Clock
Database database . Store
PortSharer * atomic . Pointer [ portsharing . PortSharer ]
2025-05-29 12:15:47 +01:00
}
func ( a * SubAgentAPI ) CreateSubAgent ( ctx context . Context , req * agentproto . CreateSubAgentRequest ) ( * agentproto . CreateSubAgentResponse , error ) {
//nolint:gocritic // This gives us only the permissions required to do the job.
ctx = dbauthz . AsSubAgentAPI ( ctx , a . OrganizationID , a . OwnerID )
createdAt := a . Clock . Now ()
2025-06-06 17:30:52 +01:00
displayApps := make ([] database . DisplayApp , 0 , len ( req . DisplayApps ))
for idx , displayApp := range req . DisplayApps {
var app database . DisplayApp
switch displayApp {
case agentproto . CreateSubAgentRequest_PORT_FORWARDING_HELPER :
app = database . DisplayAppPortForwardingHelper
case agentproto . CreateSubAgentRequest_SSH_HELPER :
app = database . DisplayAppSSHHelper
case agentproto . CreateSubAgentRequest_VSCODE :
app = database . DisplayAppVscode
case agentproto . CreateSubAgentRequest_VSCODE_INSIDERS :
app = database . DisplayAppVscodeInsiders
case agentproto . CreateSubAgentRequest_WEB_TERMINAL :
app = database . DisplayAppWebTerminal
default :
return nil , codersdk . ValidationError {
Field : fmt . Sprintf ( "display_apps[%d]" , idx ),
Detail : fmt . Sprintf ( "%q is not a valid display app" , displayApp ),
}
}
displayApps = append ( displayApps , app )
}
2026-02-04 15:33:48 +00:00
parentAgent , err := a . AgentFn ( ctx )
if err != nil {
return nil , xerrors . Errorf ( "get parent agent: %w" , err )
}
// An ID is only given in the request when it is a terraform-defined devcontainer
// that has attached resources. These subagents are pre-provisioned by terraform
// (the agent record already exists), so we update configurable fields like
2026-04-10 10:11:22 -04:00
// display_apps and directory rather than creating a new agent.
2026-02-04 15:33:48 +00:00
if req . Id != nil {
id , err := uuid . FromBytes ( req . Id )
if err != nil {
return nil , xerrors . Errorf ( "parse agent id: %w" , err )
}
subAgent , err := a . Database . GetWorkspaceAgentByID ( ctx , id )
if err != nil {
return nil , xerrors . Errorf ( "get workspace agent by id: %w" , err )
}
// Validate that the subagent belongs to the current parent agent to
// prevent updating subagents from other agents within the same workspace.
if ! subAgent . ParentID . Valid || subAgent . ParentID . UUID != parentAgent . ID {
return nil , xerrors . Errorf ( "subagent does not belong to this parent agent" )
}
if err := a . Database . UpdateWorkspaceAgentDisplayAppsByID ( ctx , database . UpdateWorkspaceAgentDisplayAppsByIDParams {
ID : id ,
DisplayApps : displayApps ,
UpdatedAt : createdAt ,
}); err != nil {
return nil , xerrors . Errorf ( "update workspace agent display apps: %w" , err )
}
2026-04-10 10:11:22 -04:00
if req . Directory != "" {
if err := a . Database . UpdateWorkspaceAgentDirectoryByID ( ctx , database . UpdateWorkspaceAgentDirectoryByIDParams {
ID : id ,
Directory : req . Directory ,
UpdatedAt : createdAt ,
}); err != nil {
return nil , xerrors . Errorf ( "update workspace agent directory: %w" , err )
}
}
2026-02-04 15:33:48 +00:00
return & agentproto . CreateSubAgentResponse {
Agent : & agentproto . SubAgent {
Name : subAgent . Name ,
Id : subAgent . ID [:],
AuthToken : subAgent . AuthToken [:],
},
}, nil
}
agentName := req . Name
if agentName == "" {
return nil , codersdk . ValidationError {
Field : "name" ,
Detail : "agent name cannot be empty" ,
}
}
if ! provisioner . AgentNameRegex . MatchString ( agentName ) {
return nil , codersdk . ValidationError {
Field : "name" ,
Detail : fmt . Sprintf ( "agent name %q does not match regex %q" , agentName , provisioner . AgentNameRegex ),
}
}
2026-06-05 16:30:15 +01:00
var template database . Template
if len ( req . Apps ) > 0 {
workspace , err := a . Database . GetWorkspaceByAgentID ( ctx , parentAgent . ID )
if err != nil {
return nil , xerrors . Errorf ( "get workspace by agent id: %w" , err )
}
// Intentional: SubAgentAPI auth context enforces template ACL.
// Normal workspace operations depend on this.
template , err = a . Database . GetTemplateByID ( ctx , workspace . TemplateID )
if err != nil {
return nil , xerrors . Errorf ( "get template policy: %w. If template access was recently changed, restart the workspace to refresh agent permissions" , err )
}
}
2025-05-29 12:15:47 +01:00
subAgent , err := a . Database . InsertWorkspaceAgent ( ctx , database . InsertWorkspaceAgentParams {
ID : uuid . New (),
ParentID : uuid . NullUUID { Valid : true , UUID : parentAgent . ID },
CreatedAt : createdAt ,
UpdatedAt : createdAt ,
Name : agentName ,
ResourceID : parentAgent . ResourceID ,
AuthToken : uuid . New (),
2026-02-19 16:56:29 +00:00
AuthInstanceID : sql . NullString {},
2025-05-29 12:15:47 +01:00
Architecture : req . Architecture ,
EnvironmentVariables : pqtype . NullRawMessage {},
OperatingSystem : req . OperatingSystem ,
Directory : req . Directory ,
InstanceMetadata : pqtype . NullRawMessage {},
ResourceMetadata : pqtype . NullRawMessage {},
ConnectionTimeoutSeconds : parentAgent . ConnectionTimeoutSeconds ,
TroubleshootingURL : parentAgent . TroubleshootingURL ,
MOTDFile : "" ,
2025-06-06 17:30:52 +01:00
DisplayApps : displayApps ,
2025-05-29 12:15:47 +01:00
DisplayOrder : 0 ,
APIKeyScope : parentAgent . APIKeyScope ,
})
if err != nil {
return nil , xerrors . Errorf ( "insert sub agent: %w" , err )
}
2026-06-05 16:30:15 +01:00
// A nil PortSharer uses the AGPL default, which permits all share levels.
portSharer := portsharing . DefaultPortSharer
if a . PortSharer != nil {
if loaded := a . PortSharer . Load (); loaded != nil {
portSharer = * loaded
}
}
2025-06-05 11:57:02 +01:00
var appCreationErrors [] * agentproto . CreateSubAgentResponse_AppCreationError
appSlugs := make ( map [ string ] struct {})
for i , app := range req . Apps {
err := func () error {
slug := app . Slug
if slug == "" {
return codersdk . ValidationError {
Field : "slug" ,
Detail : "must not be empty" ,
}
}
if ! provisioner . AppSlugRegex . MatchString ( slug ) {
return codersdk . ValidationError {
Field : "slug" ,
Detail : fmt . Sprintf ( "%q does not match regex %q" , slug , provisioner . AppSlugRegex ),
}
}
if _ , exists := appSlugs [ slug ]; exists {
return codersdk . ValidationError {
Field : "slug" ,
Detail : fmt . Sprintf ( "%q is already in use" , slug ),
}
}
appSlugs [ slug ] = struct {}{}
health := database . WorkspaceAppHealthDisabled
if app . Healthcheck == nil {
app . Healthcheck = & agentproto . CreateSubAgentRequest_App_Healthcheck {}
}
if app . Healthcheck . Url != "" {
health = database . WorkspaceAppHealthInitializing
}
2025-06-16 16:15:59 -06:00
share := app . GetShare ()
protoSharingLevel , ok := agentproto . CreateSubAgentRequest_App_SharingLevel_name [ int32 ( share )]
if ! ok {
2025-06-05 11:57:02 +01:00
return codersdk . ValidationError {
Field : "share" ,
2025-06-16 16:15:59 -06:00
Detail : fmt . Sprintf ( "%q is not a valid app sharing level" , share . String ()),
2025-06-05 11:57:02 +01:00
}
}
2025-06-16 16:15:59 -06:00
sharingLevel := database . AppSharingLevel ( strings . ToLower ( protoSharingLevel ))
2026-06-05 16:30:15 +01:00
// Clamp instead of rejecting so a too-permissive app share level does
// not block the sub-agent from starting.
if err := portSharer . AuthorizedLevel ( template , codersdk . WorkspaceAgentPortShareLevel ( sharingLevel )); err != nil {
a . Log . Warn ( ctx , "clamping sub-agent app sharing level to template max port sharing level" ,
slog . F ( "sub_agent_name" , subAgent . Name ),
slog . F ( "sub_agent_id" , subAgent . ID ),
slog . F ( "app_slug" , slug ),
slog . F ( "requested_share_level" , sharingLevel ),
slog . F ( "max_port_share_level" , template . MaxPortSharingLevel ),
slog . Error ( err ))
sharingLevel = template . MaxPortSharingLevel
}
2025-06-05 11:57:02 +01:00
var openIn database . WorkspaceAppOpenIn
switch app . GetOpenIn () {
case agentproto . CreateSubAgentRequest_App_SLIM_WINDOW :
openIn = database . WorkspaceAppOpenInSlimWindow
case agentproto . CreateSubAgentRequest_App_TAB :
openIn = database . WorkspaceAppOpenInTab
default :
return codersdk . ValidationError {
Field : "open_in" ,
Detail : fmt . Sprintf ( "%q is not an open in setting" , app . GetOpenIn ()),
}
}
2026-10-27 14:44:25 +03:00
// Only template apps may receive a session token.
appURL := app . GetUrl ()
if strings . Contains ( appURL , sessionTokenPlaceholder ) {
a . Log . Warn ( ctx , "removing session token placeholder from sub-agent app url" ,
slog . F ( "sub_agent_name" , subAgent . Name ),
slog . F ( "sub_agent_id" , subAgent . ID ),
slog . F ( "app_slug" , slug ))
appURL = strings . ReplaceAll ( appURL , sessionTokenPlaceholder , "" )
}
if app . GetExternal () && appURL != "" {
if err := provisioner . ValidateExternalURL ( appURL ); err != nil {
return codersdk . ValidationError {
Field : "url" ,
Detail : fmt . Sprintf ( "invalid external url: %s" , err ),
}
}
}
2025-06-25 17:36:23 +01:00
// NOTE(DanielleMaywood):
// Slugs must be unique PER workspace/template. As of 2025-06-25,
// there is no database-layer enforcement of this constraint.
// We can get around this by creating a slug that *should* be
// unique (at least highly probable).
slugHash := sha256 . Sum256 ([] byte ( subAgent . Name + "/" + app . Slug ))
slugHashEnc := base32 . HexEncoding . WithPadding ( base32 . NoPadding ). EncodeToString ( slugHash [:])
computedSlug := strings . ToLower ( slugHashEnc [: 8 ]) + "-" + app . Slug
2026-06-11 15:02:41 -04:00
appID := uuid . New ()
2025-06-23 20:50:44 +02:00
_ , err := a . Database . UpsertWorkspaceApp ( ctx , database . UpsertWorkspaceAppParams {
2026-06-11 15:02:41 -04:00
ID : appID , // NOTE: we may need to maintain the app's ID here for stability, but for now we'll leave this as-is.
2025-06-05 11:57:02 +01:00
CreatedAt : createdAt ,
AgentID : subAgent . ID ,
2025-06-25 17:36:23 +01:00
Slug : computedSlug ,
2025-06-05 11:57:02 +01:00
DisplayName : app . GetDisplayName (),
Icon : app . GetIcon (),
Command : sql . NullString {
Valid : app . GetCommand () != "" ,
String : app . GetCommand (),
},
Url : sql . NullString {
2026-10-27 14:44:25 +03:00
Valid : appURL != "" ,
String : appURL ,
2025-06-05 11:57:02 +01:00
},
External : app . GetExternal (),
Subdomain : app . GetSubdomain (),
SharingLevel : sharingLevel ,
HealthcheckUrl : app . Healthcheck . Url ,
HealthcheckInterval : app . Healthcheck . Interval ,
HealthcheckThreshold : app . Healthcheck . Threshold ,
Health : health ,
DisplayOrder : app . GetOrder (),
Hidden : app . GetHidden (),
OpenIn : openIn ,
DisplayGroup : sql . NullString {
Valid : app . GetGroup () != "" ,
String : app . GetGroup (),
},
2025-09-10 11:01:54 -05:00
Tooltip : "" , // tooltips are not currently supported in subagent workspaces, default to empty string
2025-06-05 11:57:02 +01:00
})
if err != nil {
2026-06-11 15:02:41 -04:00
if errors . Is ( err , sql . ErrNoRows ) {
// The upsert's ON CONFLICT guard refused to rebind an
// existing workspace-owned app to an agent outside that
// workspace, including agents that resolve to no workspace.
return xerrors . Errorf ( "workspace app slug %q with ID %q is already bound to a workspace-owned agent and cannot be rebound to an agent in another workspace or to an agent without a workspace; refusing to rebind to agent ID %q" , computedSlug , appID , subAgent . ID )
}
2025-06-05 11:57:02 +01:00
return xerrors . Errorf ( "insert workspace app: %w" , err )
}
return nil
}()
if err != nil {
appErr := & agentproto . CreateSubAgentResponse_AppCreationError {
Index : int32 ( i ), //nolint:gosec // This would only overflow if we created 2 billion apps.
Error : err . Error (),
}
var validationErr codersdk . ValidationError
if errors . As ( err , & validationErr ) {
appErr . Field = & validationErr . Field
appErr . Error = validationErr . Detail
}
appCreationErrors = append ( appCreationErrors , appErr )
}
}
2025-05-29 12:15:47 +01:00
return & agentproto . CreateSubAgentResponse {
Agent : & agentproto . SubAgent {
Name : subAgent . Name ,
Id : subAgent . ID [:],
AuthToken : subAgent . AuthToken [:],
},
2025-06-05 11:57:02 +01:00
AppCreationErrors : appCreationErrors ,
2025-05-29 12:15:47 +01:00
}, nil
}
func ( a * SubAgentAPI ) DeleteSubAgent ( ctx context . Context , req * agentproto . DeleteSubAgentRequest ) ( * agentproto . DeleteSubAgentResponse , error ) {
//nolint:gocritic // This gives us only the permissions required to do the job.
ctx = dbauthz . AsSubAgentAPI ( ctx , a . OrganizationID , a . OwnerID )
subAgentID , err := uuid . FromBytes ( req . Id )
if err != nil {
return nil , err
}
if err := a . Database . DeleteWorkspaceSubAgentByID ( ctx , subAgentID ); err != nil {
return nil , err
}
return & agentproto . DeleteSubAgentResponse {}, nil
}
func ( a * SubAgentAPI ) ListSubAgents ( ctx context . Context , _ * agentproto . ListSubAgentsRequest ) ( * agentproto . ListSubAgentsResponse , error ) {
//nolint:gocritic // This gives us only the permissions required to do the job.
ctx = dbauthz . AsSubAgentAPI ( ctx , a . OrganizationID , a . OwnerID )
2026-03-20 15:42:05 -05:00
parentAgent , err := a . AgentFn ( ctx )
if err != nil {
return nil , xerrors . Errorf ( "get parent agent: %w" , err )
}
workspaceAgents , err := a . Database . GetWorkspaceAgentsByParentID ( ctx , parentAgent . ID )
2025-05-29 12:15:47 +01:00
if err != nil {
return nil , err
}
agents := make ([] * agentproto . SubAgent , len ( workspaceAgents ))
for i , agent := range workspaceAgents {
agents [ i ] = & agentproto . SubAgent {
Name : agent . Name ,
Id : agent . ID [:],
AuthToken : agent . AuthToken [:],
}
}
return & agentproto . ListSubAgentsResponse { Agents : agents }, nil
}