fix: improve error messages when the agent token is invalid (#5423)

I'm not sure why this issue is common, but it seems to be
based on: https://github.com/coder/coder/issues/4551.

This improves the error messages to be unique,
and also fixes a small edge-case bug a user ran into.
This commit is contained in:
Kyle Carberry
2022-12-14 12:24:22 -06:00
committed by GitHub
parent b39ba02bf0
commit c0b251ac52
2 changed files with 16 additions and 7 deletions

View File

@ -30,17 +30,18 @@ func ExtractWorkspaceAgent(db database.Store) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
cookieValue := apiTokenFromRequest(r)
if cookieValue == "" {
tokenValue := apiTokenFromRequest(r)
if tokenValue == "" {
httpapi.Write(ctx, rw, http.StatusUnauthorized, codersdk.Response{
Message: fmt.Sprintf("Cookie %q must be provided.", codersdk.SessionTokenKey),
})
return
}
token, err := uuid.Parse(cookieValue)
token, err := uuid.Parse(tokenValue)
if err != nil {
httpapi.Write(ctx, rw, http.StatusUnauthorized, codersdk.Response{
Message: "Agent token is invalid.",
Message: "Workspace agent token invalid.",
Detail: fmt.Sprintf("An agent token must be a valid UUIDv4. (len %d)", len(tokenValue)),
})
return
}
@ -48,7 +49,8 @@ func ExtractWorkspaceAgent(db database.Store) func(http.Handler) http.Handler {
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
httpapi.Write(ctx, rw, http.StatusUnauthorized, codersdk.Response{
Message: "Agent token is invalid.",
Message: "Workspace agent not authorized.",
Detail: "The agent cannot authenticate until the workspace provision job has been completed. If the job is no longer running, this agent is invalid.",
})
return
}

View File

@ -218,8 +218,15 @@ func ConvertResources(module *tfjson.StateModule, rawGraph string) ([]*proto.Res
if agent.Id != agentID {
continue
}
agent.Auth = &proto.Agent_InstanceId{
InstanceId: instanceID,
// Only apply the instance ID if the agent authentication
// type is set to do so. A user ran into a bug where they
// had the instance ID block, but auth was set to "token". See:
// https://github.com/coder/coder/issues/4551#issuecomment-1336293468
switch t := agent.Auth.(type) {
case *proto.Agent_Token:
continue
case *proto.Agent_InstanceId:
t.InstanceId = instanceID
}
break
}