Skip to content

Commit 07f21aa

Browse files
committed
Rename workspace agent to agent
1 parent e4b51dc commit 07f21aa

File tree

11 files changed

+46
-78
lines changed

11 files changed

+46
-78
lines changed

cli/workspaceagent.go renamed to cli/agent.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@ import (
44
"github.com/spf13/cobra"
55
)
66

7-
func workspaceAgent() *cobra.Command {
7+
func agent() *cobra.Command {
88
return &cobra.Command{
9-
Use: "agent",
9+
Use: "agent",
10+
Hidden: true,
1011
RunE: func(cmd *cobra.Command, args []string) error {
1112
return nil
1213
},

cli/root.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ func Root() *cobra.Command {
6464
`Additional help topics:`, header.Sprint("Additional help:"),
6565
).Replace(cmd.UsageTemplate()))
6666

67+
cmd.AddCommand(agent())
6768
cmd.AddCommand(login())
6869
cmd.AddCommand(projects())
6970
cmd.AddCommand(workspaces())

cli/workspaces.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ func workspaces() *cobra.Command {
66
cmd := &cobra.Command{
77
Use: "workspaces",
88
}
9-
cmd.AddCommand(workspaceAgent())
109
cmd.AddCommand(workspaceCreate())
1110

1211
return cmd

coderd/workspaceagent.go renamed to coderd/agent.go

Lines changed: 8 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
11
package coderd
22

33
import (
4-
"database/sql"
54
"fmt"
65
"io"
76
"net/http"
8-
"time"
97

108
"github.com/hashicorp/yamux"
119
"nhooyr.io/websocket"
1210

13-
"cdr.dev/slog"
14-
"github.com/coder/coder/database"
1511
"github.com/coder/coder/httpapi"
1612
"github.com/coder/coder/httpmw"
1713
"github.com/coder/coder/peerbroker"
@@ -39,15 +35,15 @@ type AgentInstanceMetadata struct {
3935
VNC bool `json:"vnc"`
4036
}
4137

42-
func (api *api) workspaceAgentUpdate() {
38+
func (api *api) agentUpdate() {
4339

4440
}
4541

46-
func (api *api) workspaceAgentConnectByResource(rw http.ResponseWriter, r *http.Request) {
42+
func (api *api) agentConnectByResource(rw http.ResponseWriter, r *http.Request) {
4743
api.websocketWaitGroup.Add(1)
4844
defer api.websocketWaitGroup.Done()
4945

50-
agent := httpmw.WorkspaceAgent(r)
46+
agent := httpmw.Agent(r)
5147
if !agent.UpdatedAt.Valid {
5248
httpapi.Write(rw, http.StatusPreconditionRequired, httpapi.Response{
5349
Message: "Agent hasn't connected yet!",
@@ -75,7 +71,7 @@ func (api *api) workspaceAgentConnectByResource(rw http.ResponseWriter, r *http.
7571
return
7672
}
7773
err = peerbroker.ProxyListen(r.Context(), session, peerbroker.ProxyOptions{
78-
ChannelID: resource.WorkspaceAgentID.UUID.String(),
74+
ChannelID: agent.ID.String(),
7975
Logger: api.Logger.Named("peerbroker-proxy-dial"),
8076
Pubsub: api.Pubsub,
8177
})
@@ -85,11 +81,11 @@ func (api *api) workspaceAgentConnectByResource(rw http.ResponseWriter, r *http.
8581
}
8682
}
8783

88-
func (api *api) workspaceAgentServe(rw http.ResponseWriter, r *http.Request) {
84+
func (api *api) agentServe(rw http.ResponseWriter, r *http.Request) {
8985
api.websocketWaitGroup.Add(1)
9086
defer api.websocketWaitGroup.Done()
9187

92-
workspaceAgent := httpmw.WorkspaceAgent(r)
88+
agent := httpmw.Agent(r)
9389
conn, err := websocket.Accept(rw, r, &websocket.AcceptOptions{
9490
CompressionMode: websocket.CompressionDisabled,
9591
})
@@ -110,44 +106,14 @@ func (api *api) workspaceAgentServe(rw http.ResponseWriter, r *http.Request) {
110106
return
111107
}
112108
closer, err := peerbroker.ProxyDial(proto.NewDRPCPeerBrokerClient(provisionersdk.Conn(session)), peerbroker.ProxyOptions{
113-
ChannelID: workspaceAgent.ID.String(),
109+
ChannelID: agent.ID.String(),
114110
Pubsub: api.Pubsub,
115111
Logger: api.Logger.Named("peerbroker-proxy-listen"),
116112
})
117113
if err != nil {
118114
_ = conn.Close(websocket.StatusAbnormalClosure, err.Error())
119115
return
120116
}
121-
122-
err = api.Database.UpdateWorkspaceAgentByID(r.Context(), database.UpdateWorkspaceAgentByIDParams{
123-
ID: workspaceAgent.ID,
124-
UpdatedAt: sql.NullTime{
125-
Time: database.Now(),
126-
Valid: true,
127-
},
128-
})
129-
if err != nil {
130-
_ = conn.Close(websocket.StatusAbnormalClosure, err.Error())
131-
return
132-
}
133117
defer closer.Close()
134-
ticker := time.NewTicker(5 * time.Second)
135-
for {
136-
select {
137-
case <-ticker.C:
138-
err = api.Database.UpdateWorkspaceAgentByID(r.Context(), database.UpdateWorkspaceAgentByIDParams{
139-
ID: workspaceAgent.ID,
140-
UpdatedAt: sql.NullTime{
141-
Time: database.Now(),
142-
Valid: true,
143-
},
144-
})
145-
if err != nil {
146-
api.Logger.Error(r.Context(), "update workspace agent by id", slog.Error(err), slog.F("id", workspaceAgent.ID.String()))
147-
return
148-
}
149-
case <-r.Context().Done():
150-
return
151-
}
152-
}
118+
<-r.Context().Done()
153119
}

coderd/workspaceagentauth.go renamed to coderd/agentauth.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,16 @@ type GoogleInstanceIdentityToken struct {
1919
JSONWebToken string `json:"json_web_token" validate:"required"`
2020
}
2121

22-
// WorkspaceAgentAuthenticateResponse is returned when an instance ID
22+
// AgentAuthResponse is returned when an instance ID
2323
// has been exchanged for a session token.
24-
type WorkspaceAgentAuthenticateResponse struct {
24+
type AgentAuthResponse struct {
2525
SessionToken string `json:"session_token"`
2626
}
2727

2828
// Google Compute Engine supports instance identity verification:
2929
// https://cloud.google.com/compute/docs/instances/verifying-instance-identity
3030
// Using this, we can exchange a signed instance payload for an agent token.
31-
func (api *api) postAuthenticateWorkspaceAgentUsingGoogleInstanceIdentity(rw http.ResponseWriter, r *http.Request) {
31+
func (api *api) postAuthenticateAgentUsingGoogleInstanceIdentity(rw http.ResponseWriter, r *http.Request) {
3232
var req GoogleInstanceIdentityToken
3333
if !httpapi.Read(rw, r, &req) {
3434
return
@@ -121,7 +121,7 @@ func (api *api) postAuthenticateWorkspaceAgentUsingGoogleInstanceIdentity(rw htt
121121
return
122122
}
123123
render.Status(r, http.StatusOK)
124-
render.JSON(rw, r, WorkspaceAgentAuthenticateResponse{
124+
render.JSON(rw, r, AgentAuthResponse{
125125
SessionToken: agent.AuthToken.String(),
126126
})
127127
}

coderd/workspaceagentauth_test.go renamed to coderd/agentauth_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import (
2828
"github.com/coder/coder/provisionersdk/proto"
2929
)
3030

31-
func TestPostWorkspaceAgentAuthenticateGoogleInstanceIdentity(t *testing.T) {
31+
func TestPostAgentAuthenticateGoogleInstanceIdentity(t *testing.T) {
3232
t.Parallel()
3333
t.Run("Expired", func(t *testing.T) {
3434
t.Parallel()
@@ -38,7 +38,7 @@ func TestPostWorkspaceAgentAuthenticateGoogleInstanceIdentity(t *testing.T) {
3838
client := coderdtest.New(t, &coderdtest.Options{
3939
GoogleTokenValidator: validator,
4040
})
41-
_, err := client.AuthenticateWorkspaceAgentUsingGoogleCloudIdentity(context.Background(), "", createMetadataClient(signedKey))
41+
_, err := client.AuthenticateAgentWithGoogleCloudIdentity(context.Background(), "", createMetadataClient(signedKey))
4242
var apiErr *codersdk.Error
4343
require.ErrorAs(t, err, &apiErr)
4444
require.Equal(t, http.StatusUnauthorized, apiErr.StatusCode())
@@ -52,7 +52,7 @@ func TestPostWorkspaceAgentAuthenticateGoogleInstanceIdentity(t *testing.T) {
5252
client := coderdtest.New(t, &coderdtest.Options{
5353
GoogleTokenValidator: validator,
5454
})
55-
_, err := client.AuthenticateWorkspaceAgentUsingGoogleCloudIdentity(context.Background(), "", createMetadataClient(signedKey))
55+
_, err := client.AuthenticateAgentWithGoogleCloudIdentity(context.Background(), "", createMetadataClient(signedKey))
5656
var apiErr *codersdk.Error
5757
require.ErrorAs(t, err, &apiErr)
5858
require.Equal(t, http.StatusNotFound, apiErr.StatusCode())
@@ -98,7 +98,7 @@ func TestPostWorkspaceAgentAuthenticateGoogleInstanceIdentity(t *testing.T) {
9898
require.NoError(t, err)
9999
coderdtest.AwaitWorkspaceProvisionJob(t, client, user.Organization, firstHistory.ProvisionJobID)
100100

101-
_, err = client.AuthenticateWorkspaceAgentUsingGoogleCloudIdentity(context.Background(), "", createMetadataClient(signedKey))
101+
_, err = client.AuthenticateAgentWithGoogleCloudIdentity(context.Background(), "", createMetadataClient(signedKey))
102102
require.NoError(t, err)
103103
})
104104
}

coderd/coderd.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,9 @@ func New(options *Options) (http.Handler, func()) {
112112
})
113113
})
114114

115-
r.Route("/workspaceagent", func(r chi.Router) {
115+
r.Route("/agent", func(r chi.Router) {
116116
r.Route("/authenticate", func(r chi.Router) {
117-
r.Post("/google-instance-identity", api.postAuthenticateWorkspaceAgentUsingGoogleInstanceIdentity)
117+
r.Post("/google-instance-identity", api.postAuthenticateAgentUsingGoogleInstanceIdentity)
118118
})
119119
})
120120

codersdk/workspaceagent.go renamed to codersdk/agent.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ import (
1212
"github.com/coder/coder/coderd"
1313
)
1414

15-
// AuthenticateWorkspaceAgentUsingGoogleCloudIdentity uses the Google Compute Engine Metadata API to
15+
// AuthenticateAgentWithGoogleCloudIdentity uses the Google Compute Engine Metadata API to
1616
// fetch a signed JWT, and exchange it for a session token for a workspace agent.
1717
//
1818
// The requesting instance must be registered as a resource in the latest history for a workspace.
19-
func (c *Client) AuthenticateWorkspaceAgentUsingGoogleCloudIdentity(ctx context.Context, serviceAccount string, gcpClient *metadata.Client) (coderd.WorkspaceAgentAuthenticateResponse, error) {
19+
func (c *Client) AuthenticateAgentWithGoogleCloudIdentity(ctx context.Context, serviceAccount string, gcpClient *metadata.Client) (coderd.AgentAuthResponse, error) {
2020
if serviceAccount == "" {
2121
// This is the default name specified by Google.
2222
serviceAccount = "default"
@@ -27,18 +27,18 @@ func (c *Client) AuthenticateWorkspaceAgentUsingGoogleCloudIdentity(ctx context.
2727
// "format=full" is required, otherwise the responding payload will be missing "instance_id".
2828
jwt, err := gcpClient.Get(fmt.Sprintf("instance/service-accounts/%s/identity?audience=coder&format=full", serviceAccount))
2929
if err != nil {
30-
return coderd.WorkspaceAgentAuthenticateResponse{}, xerrors.Errorf("get metadata identity: %w", err)
30+
return coderd.AgentAuthResponse{}, xerrors.Errorf("get metadata identity: %w", err)
3131
}
32-
res, err := c.request(ctx, http.MethodPost, "/api/v2/workspaceagent/authenticate/google-instance-identity", coderd.GoogleInstanceIdentityToken{
32+
res, err := c.request(ctx, http.MethodPost, "/api/v2/agent/authenticate/google-instance-identity", coderd.GoogleInstanceIdentityToken{
3333
JSONWebToken: jwt,
3434
})
3535
if err != nil {
36-
return coderd.WorkspaceAgentAuthenticateResponse{}, err
36+
return coderd.AgentAuthResponse{}, err
3737
}
3838
defer res.Body.Close()
3939
if res.StatusCode != http.StatusOK {
40-
return coderd.WorkspaceAgentAuthenticateResponse{}, readBodyAsError(res)
40+
return coderd.AgentAuthResponse{}, readBodyAsError(res)
4141
}
42-
var resp coderd.WorkspaceAgentAuthenticateResponse
42+
var resp coderd.AgentAuthResponse
4343
return resp, json.NewDecoder(res.Body).Decode(&resp)
4444
}

codersdk/workspaceagent_test.go renamed to codersdk/agent_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@ import (
1313
"github.com/coder/coder/coderd/coderdtest"
1414
)
1515

16-
func TestAuthenticateWorkspaceAgentUsingGoogleCloudIdentity(t *testing.T) {
16+
func TestAuthenticateAgentUsingGoogleCloudIdentity(t *testing.T) {
1717
t.Parallel()
1818
t.Run("Error", func(t *testing.T) {
1919
t.Parallel()
2020
client := coderdtest.New(t, nil)
21-
_, err := client.AuthenticateWorkspaceAgentUsingGoogleCloudIdentity(context.Background(), "", metadata.NewClient(&http.Client{
21+
_, err := client.AuthenticateAgentWithGoogleCloudIdentity(context.Background(), "", metadata.NewClient(&http.Client{
2222
Transport: roundTripper(func(req *http.Request) (*http.Response, error) {
2323
return &http.Response{
2424
StatusCode: http.StatusOK,

httpmw/workspaceagent.go renamed to httpmw/agent.go

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,25 @@ import (
77
"fmt"
88
"net/http"
99

10+
"github.com/google/uuid"
11+
1012
"github.com/coder/coder/database"
1113
"github.com/coder/coder/httpapi"
12-
"github.com/google/uuid"
1314
)
1415

15-
type workspaceAgentContextKey struct{}
16+
type agentContextKey struct{}
1617

17-
// WorkspaceAgent returns the workspace agent from the ExtractWorkspaceAgent handler.
18-
func WorkspaceAgent(r *http.Request) database.ProvisionerJobAgent {
19-
user, ok := r.Context().Value(workspaceAgentContextKey{}).(database.ProvisionerJobAgent)
18+
// Agent returns the workspace agent from the ExtractAgent handler.
19+
func Agent(r *http.Request) database.ProvisionerJobAgent {
20+
user, ok := r.Context().Value(agentContextKey{}).(database.ProvisionerJobAgent)
2021
if !ok {
21-
panic("developer error: workspace agent middleware not provided")
22+
panic("developer error: agent middleware not provided")
2223
}
2324
return user
2425
}
2526

26-
// ExtractWorkspaceAgent requires authentication using a valid agent token.
27-
func ExtractWorkspaceAgent(db database.Store) func(http.Handler) http.Handler {
27+
// ExtractAgent requires authentication using a valid agent token.
28+
func ExtractAgent(db database.Store) func(http.Handler) http.Handler {
2829
return func(next http.Handler) http.Handler {
2930
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
3031
cookie, err := r.Cookie(AuthCookie)
@@ -41,7 +42,7 @@ func ExtractWorkspaceAgent(db database.Store) func(http.Handler) http.Handler {
4142
})
4243
return
4344
}
44-
workspaceAgent, err := db.GetProvisionerJobAgentByAuthToken(r.Context(), token)
45+
agent, err := db.GetProvisionerJobAgentByAuthToken(r.Context(), token)
4546
if errors.Is(err, sql.ErrNoRows) {
4647
if errors.Is(err, sql.ErrNoRows) {
4748
httpapi.Write(rw, http.StatusUnauthorized, httpapi.Response{
@@ -57,7 +58,7 @@ func ExtractWorkspaceAgent(db database.Store) func(http.Handler) http.Handler {
5758
return
5859
}
5960

60-
ctx := context.WithValue(r.Context(), workspaceAgentContextKey{}, workspaceAgent)
61+
ctx := context.WithValue(r.Context(), agentContextKey{}, agent)
6162
next.ServeHTTP(rw, r.WithContext(ctx))
6263
})
6364
}

httpmw/workspaceagent_test.go renamed to httpmw/agent_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
"github.com/coder/coder/httpmw"
1616
)
1717

18-
func TestWorkspaceAgent(t *testing.T) {
18+
func TestAgent(t *testing.T) {
1919
t.Parallel()
2020

2121
setup := func(db database.Store) (*http.Request, uuid.UUID) {
@@ -33,7 +33,7 @@ func TestWorkspaceAgent(t *testing.T) {
3333
db := databasefake.New()
3434
rtr := chi.NewRouter()
3535
rtr.Use(
36-
httpmw.ExtractWorkspaceAgent(db),
36+
httpmw.ExtractAgent(db),
3737
)
3838
rtr.Get("/", nil)
3939
r, _ := setup(db)
@@ -50,10 +50,10 @@ func TestWorkspaceAgent(t *testing.T) {
5050
db := databasefake.New()
5151
rtr := chi.NewRouter()
5252
rtr.Use(
53-
httpmw.ExtractWorkspaceAgent(db),
53+
httpmw.ExtractAgent(db),
5454
)
5555
rtr.Get("/", func(rw http.ResponseWriter, r *http.Request) {
56-
_ = httpmw.WorkspaceAgent(r)
56+
_ = httpmw.Agent(r)
5757
rw.WriteHeader(http.StatusOK)
5858
})
5959
r, token := setup(db)

0 commit comments

Comments
 (0)