Skip to content

feat(coderd): add support for external agents to API's and provisioner #19286

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: kacpersaw/feat-coder-attach-database
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
move /external-agent/{agent}/credentials endpoint to enterprise
  • Loading branch information
kacpersaw committed Aug 12, 2025
commit a4268eaf83a564d460dc10599c309990f3a00907
2 changes: 1 addition & 1 deletion coderd/apidoc/docs.go

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

2 changes: 1 addition & 1 deletion coderd/apidoc/swagger.json

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

3 changes: 0 additions & 3 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -1430,9 +1430,6 @@ func New(options *Options) *API {
r.Post("/", api.postWorkspaceAgentPortShare)
r.Delete("/", api.deleteWorkspaceAgentPortShare)
})
r.Route("/external-agent", func(r chi.Router) {
r.Get("/{agent}/credentials", api.workspaceExternalAgentCredentials)
})
r.Get("/timings", api.workspaceTimings)
r.Route("/acl", func(r chi.Router) {
r.Use(
Expand Down
68 changes: 0 additions & 68 deletions coderd/workspaceagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -2185,71 +2185,3 @@ func convertWorkspaceAgentLog(logEntry database.WorkspaceAgentLog) codersdk.Work
SourceID: logEntry.LogSourceID,
}
}

// @Summary Get workspace external agent credentials
// @ID get-workspace-external-agent-credentials
// @Security CoderSessionToken
// @Produce json
// @Tags Agents
// @Param workspace path string true "Workspace ID" format(uuid)
// @Param agent path string true "Agent name"
// @Success 200 {object} codersdk.ExternalAgentCredentials
// @Router /workspaces/{workspace}/external-agent/{agent}/credentials [get]
func (api *API) workspaceExternalAgentCredentials(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
workspace := httpmw.WorkspaceParam(r)
agentName := chi.URLParam(r, "agent")

build, err := api.Database.GetLatestWorkspaceBuildByWorkspaceID(ctx, workspace.ID)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to get latest workspace build.",
Detail: err.Error(),
})
return
}

agents, err := api.Database.GetWorkspaceAgentsByWorkspaceAndBuildNumber(ctx, database.GetWorkspaceAgentsByWorkspaceAndBuildNumberParams{
WorkspaceID: workspace.ID,
BuildNumber: build.BuildNumber,
})
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to get workspace agents.",
Detail: err.Error(),
})
return
}

var agent *database.WorkspaceAgent
for i := range agents {
if agents[i].Name == agentName {
agent = &agents[i]
break
}
}
if agent == nil {
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
Message: fmt.Sprintf("External agent '%s' not found in workspace.", agentName),
})
return
}

if agent.AuthInstanceID.Valid {
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
Message: "External agent is authenticated with an instance ID.",
})
return
}

initScriptURL := fmt.Sprintf("%s/api/v2/init-script/%s/%s", api.AccessURL.String(), agent.OperatingSystem, agent.Architecture)
command := fmt.Sprintf("CODER_AGENT_TOKEN=%q curl -fsSL %q | sh", agent.AuthToken.String(), initScriptURL)
if agent.OperatingSystem == "windows" {
command = fmt.Sprintf("$env:CODER_AGENT_TOKEN=%q; iwr -useb %q | iex", agent.AuthToken.String(), initScriptURL)
}

httpapi.Write(ctx, rw, http.StatusOK, codersdk.ExternalAgentCredentials{
AgentToken: agent.AuthToken.String(),
Command: command,
})
}
74 changes: 0 additions & 74 deletions coderd/workspaceagents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3056,77 +3056,3 @@ func (p *pubsubReinitSpy) Subscribe(event string, listener pubsub.Listener) (can
p.Unlock()
return cancel, err
}

func TestWorkspaceExternalAgentCredentials(t *testing.T) {
t.Parallel()
client, db := coderdtest.NewWithDatabase(t, nil)
user := coderdtest.CreateFirstUser(t, client)

t.Run("Success - linux", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)

r := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OrganizationID: user.OrganizationID,
OwnerID: user.UserID,
}).WithAgent(func(a []*proto.Agent) []*proto.Agent {
a[0].Name = "test-agent"
a[0].OperatingSystem = "linux"
a[0].Architecture = "amd64"
return a
}).Do()

credentials, err := client.WorkspaceExternalAgentCredentials(
ctx, r.Workspace.ID, "test-agent")
require.NoError(t, err)

require.Equal(t, r.AgentToken, credentials.AgentToken)
expectedCommand := fmt.Sprintf("CODER_AGENT_TOKEN=%q curl -fsSL \"%s/api/v2/init-script/linux/amd64\" | sh", r.AgentToken, client.URL)
require.Equal(t, expectedCommand, credentials.Command)
})

t.Run("Success - windows", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)

r := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OrganizationID: user.OrganizationID,
OwnerID: user.UserID,
}).WithAgent(func(a []*proto.Agent) []*proto.Agent {
a[0].Name = "test-agent"
a[0].OperatingSystem = "windows"
a[0].Architecture = "amd64"
return a
}).Do()

credentials, err := client.WorkspaceExternalAgentCredentials(
ctx, r.Workspace.ID, "test-agent")
require.NoError(t, err)

require.Equal(t, r.AgentToken, credentials.AgentToken)
expectedCommand := fmt.Sprintf("$env:CODER_AGENT_TOKEN=%q; iwr -useb \"%s/api/v2/init-script/windows/amd64\" | iex", r.AgentToken, client.URL)
require.Equal(t, expectedCommand, credentials.Command)
})

t.Run("WithInstanceID - should return 404", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)

r := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OrganizationID: user.OrganizationID,
OwnerID: user.UserID,
}).WithAgent(func(a []*proto.Agent) []*proto.Agent {
a[0].Name = "test-agent"
a[0].Auth = &proto.Agent_InstanceId{
InstanceId: uuid.New().String(),
}
return a
}).Do()

_, err := client.WorkspaceExternalAgentCredentials(ctx, r.Workspace.ID, "test-agent")
require.Error(t, err)
var apiErr *codersdk.Error
require.ErrorAs(t, err, &apiErr)
require.Equal(t, "External agent is authenticated with an instance ID.", apiErr.Message)
})
}
5 changes: 4 additions & 1 deletion codersdk/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ const (
// ManagedAgentLimit is a usage period feature, so the value in the license
// contains both a soft and hard limit. Refer to
// enterprise/coderd/license/license.go for the license format.
FeatureManagedAgentLimit FeatureName = "managed_agent_limit"
FeatureManagedAgentLimit FeatureName = "managed_agent_limit"
FeatureWorkspaceExternalAgent FeatureName = "workspace_external_agent"
)

var (
Expand All @@ -115,6 +116,7 @@ var (
FeatureMultipleOrganizations,
FeatureWorkspacePrebuilds,
FeatureManagedAgentLimit,
FeatureWorkspaceExternalAgent,
}

// FeatureNamesMap is a map of all feature names for quick lookups.
Expand Down Expand Up @@ -155,6 +157,7 @@ func (n FeatureName) AlwaysEnable() bool {
FeatureCustomRoles: true,
FeatureMultipleOrganizations: true,
FeatureWorkspacePrebuilds: true,
FeatureWorkspaceExternalAgent: true,
}[n]
}

Expand Down
39 changes: 0 additions & 39 deletions docs/reference/api/agents.md

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

39 changes: 39 additions & 0 deletions docs/reference/api/enterprise.md

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

9 changes: 9 additions & 0 deletions enterprise/coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,15 @@ func New(ctx context.Context, options *Options) (_ *API, err error) {
apiKeyMiddleware,
httpmw.ExtractNotificationTemplateParam(options.Database),
).Put("/notifications/templates/{notification_template}/method", api.updateNotificationTemplateMethod)

r.Route("/workspaces/{workspace}/external-agent", func(r chi.Router) {
r.Use(
apiKeyMiddleware,
httpmw.ExtractWorkspaceParam(options.Database),
api.RequireFeatureMW(codersdk.FeatureWorkspaceExternalAgent),
)
r.Get("/{agent}/credentials", api.workspaceExternalAgentCredentials)
})
})

if len(options.SCIMAPIKey) != 0 {
Expand Down
73 changes: 73 additions & 0 deletions enterprise/coderd/workspaceagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ package coderd

import (
"context"
"fmt"
"net/http"

"github.com/go-chi/chi/v5"

"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/codersdk"
)

Expand All @@ -17,3 +22,71 @@ func (api *API) shouldBlockNonBrowserConnections(rw http.ResponseWriter) bool {
}
return false
}

// @Summary Get workspace external agent credentials
// @ID get-workspace-external-agent-credentials
// @Security CoderSessionToken
// @Produce json
// @Tags Enterprise
// @Param workspace path string true "Workspace ID" format(uuid)
// @Param agent path string true "Agent name"
// @Success 200 {object} codersdk.ExternalAgentCredentials
// @Router /workspaces/{workspace}/external-agent/{agent}/credentials [get]
func (api *API) workspaceExternalAgentCredentials(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
workspace := httpmw.WorkspaceParam(r)
agentName := chi.URLParam(r, "agent")

build, err := api.Database.GetLatestWorkspaceBuildByWorkspaceID(ctx, workspace.ID)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to get latest workspace build.",
Detail: err.Error(),
})
return
}

agents, err := api.Database.GetWorkspaceAgentsByWorkspaceAndBuildNumber(ctx, database.GetWorkspaceAgentsByWorkspaceAndBuildNumberParams{
WorkspaceID: workspace.ID,
BuildNumber: build.BuildNumber,
})
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to get workspace agents.",
Detail: err.Error(),
})
return
}

var agent *database.WorkspaceAgent
for i := range agents {
if agents[i].Name == agentName {
agent = &agents[i]
break
}
}
if agent == nil {
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
Message: fmt.Sprintf("External agent '%s' not found in workspace.", agentName),
})
return
}

if agent.AuthInstanceID.Valid {
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
Message: "External agent is authenticated with an instance ID.",
})
return
}

initScriptURL := fmt.Sprintf("%s/api/v2/init-script/%s/%s", api.AccessURL.String(), agent.OperatingSystem, agent.Architecture)
Copy link
Member

Choose a reason for hiding this comment

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

Judging by the code, it seems every agent that doesn't use instance identity could be used on this endpoint and successfully return the agent token. This probably should only return a value for agents that are actually marked as external.

Copy link
Member

Choose a reason for hiding this comment

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

Could you perhaps pull all the build resources and check if the agent is a child of the external agent resource?

Copy link
Member

Choose a reason for hiding this comment

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

Should also add 404 tests for non-external agents after fixing this

command := fmt.Sprintf("CODER_AGENT_TOKEN=%q curl -fsSL %q | sh", agent.AuthToken.String(), initScriptURL)
if agent.OperatingSystem == "windows" {
command = fmt.Sprintf("$env:CODER_AGENT_TOKEN=%q; iwr -useb %q | iex", agent.AuthToken.String(), initScriptURL)
}

httpapi.Write(ctx, rw, http.StatusOK, codersdk.ExternalAgentCredentials{
AgentToken: agent.AuthToken.String(),
Command: command,
})
}
Loading