Skip to content

Commit c0b251a

Browse files
authored
fix: improve error messages when the agent token is invalid (coder#5423)
I'm not sure why this issue is common, but it seems to be based on: coder#4551. This improves the error messages to be unique, and also fixes a small edge-case bug a user ran into.
1 parent b39ba02 commit c0b251a

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

coderd/httpmw/workspaceagent.go

+7-5
Original file line numberDiff line numberDiff line change
@@ -30,25 +30,27 @@ func ExtractWorkspaceAgent(db database.Store) func(http.Handler) http.Handler {
3030
return func(next http.Handler) http.Handler {
3131
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
3232
ctx := r.Context()
33-
cookieValue := apiTokenFromRequest(r)
34-
if cookieValue == "" {
33+
tokenValue := apiTokenFromRequest(r)
34+
if tokenValue == "" {
3535
httpapi.Write(ctx, rw, http.StatusUnauthorized, codersdk.Response{
3636
Message: fmt.Sprintf("Cookie %q must be provided.", codersdk.SessionTokenKey),
3737
})
3838
return
3939
}
40-
token, err := uuid.Parse(cookieValue)
40+
token, err := uuid.Parse(tokenValue)
4141
if err != nil {
4242
httpapi.Write(ctx, rw, http.StatusUnauthorized, codersdk.Response{
43-
Message: "Agent token is invalid.",
43+
Message: "Workspace agent token invalid.",
44+
Detail: fmt.Sprintf("An agent token must be a valid UUIDv4. (len %d)", len(tokenValue)),
4445
})
4546
return
4647
}
4748
agent, err := db.GetWorkspaceAgentByAuthToken(ctx, token)
4849
if err != nil {
4950
if errors.Is(err, sql.ErrNoRows) {
5051
httpapi.Write(ctx, rw, http.StatusUnauthorized, codersdk.Response{
51-
Message: "Agent token is invalid.",
52+
Message: "Workspace agent not authorized.",
53+
Detail: "The agent cannot authenticate until the workspace provision job has been completed. If the job is no longer running, this agent is invalid.",
5254
})
5355
return
5456
}

provisioner/terraform/resources.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -218,8 +218,15 @@ func ConvertResources(module *tfjson.StateModule, rawGraph string) ([]*proto.Res
218218
if agent.Id != agentID {
219219
continue
220220
}
221-
agent.Auth = &proto.Agent_InstanceId{
222-
InstanceId: instanceID,
221+
// Only apply the instance ID if the agent authentication
222+
// type is set to do so. A user ran into a bug where they
223+
// had the instance ID block, but auth was set to "token". See:
224+
// https://github.com/coder/coder/issues/4551#issuecomment-1336293468
225+
switch t := agent.Auth.(type) {
226+
case *proto.Agent_Token:
227+
continue
228+
case *proto.Agent_InstanceId:
229+
t.InstanceId = instanceID
223230
}
224231
break
225232
}

0 commit comments

Comments
 (0)