-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathworkspaceagent.go
More file actions
140 lines (123 loc) · 4.58 KB
/
workspaceagent.go
File metadata and controls
140 lines (123 loc) · 4.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package httpmw
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
"github.com/google/uuid"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
)
type workspaceAgentContextKey struct{}
func WorkspaceAgentOptional(r *http.Request) (database.WorkspaceAgent, bool) {
user, ok := r.Context().Value(workspaceAgentContextKey{}).(database.WorkspaceAgent)
return user, ok
}
// WorkspaceAgent returns the workspace agent from the ExtractAgent handler.
func WorkspaceAgent(r *http.Request) database.WorkspaceAgent {
user, ok := WorkspaceAgentOptional(r)
if !ok {
panic("developer error: agent middleware not provided or was made optional")
}
return user
}
type latestBuildContextKey struct{}
func latestBuildOptional(r *http.Request) (database.WorkspaceBuild, bool) {
wb, ok := r.Context().Value(latestBuildContextKey{}).(database.WorkspaceBuild)
return wb, ok
}
// LatestBuild returns the Latest Build from the ExtractLatestBuild handler.
func LatestBuild(r *http.Request) database.WorkspaceBuild {
wb, ok := latestBuildOptional(r)
if !ok {
panic("developer error: agent middleware not provided or was made optional")
}
return wb
}
type ExtractWorkspaceAgentAndLatestBuildConfig struct {
DB database.Store
// Optional indicates whether the middleware should be optional. If true, any
// requests without the a token or with an invalid token will be allowed to
// continue and no workspace agent will be set on the request context.
Optional bool
}
// ExtractWorkspaceAgentAndLatestBuild requires authentication using a valid agent token.
func ExtractWorkspaceAgentAndLatestBuild(opts ExtractWorkspaceAgentAndLatestBuildConfig) 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()
// optionalWrite wraps httpapi.Write but runs the next handler if the
// token is optional.
//
// It should be used when the token is not provided or is invalid, but not
// when there are other errors.
optionalWrite := func(code int, response codersdk.Response) {
if opts.Optional {
next.ServeHTTP(rw, r)
return
}
httpapi.Write(ctx, rw, code, response)
}
tokenValue := APITokenFromRequest(r)
if tokenValue == "" {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: fmt.Sprintf("Cookie %q must be provided.", codersdk.SessionTokenCookie),
})
return
}
token, err := uuid.Parse(tokenValue)
if err != nil {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: "Workspace agent token invalid.",
Detail: fmt.Sprintf("An agent token must be a valid UUIDv4. (len %d)", len(tokenValue)),
})
return
}
//nolint:gocritic // System needs to be able to get workspace agents.
row, err := opts.DB.GetAuthenticatedWorkspaceAgentAndBuildByAuthToken(dbauthz.AsSystemRestricted(ctx), token)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
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
}
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error checking workspace agent authorization.",
Detail: err.Error(),
})
return
}
subject, _, err := UserRBACSubject(
ctx,
opts.DB,
row.WorkspaceTable.OwnerID,
rbac.WorkspaceAgentScope(rbac.WorkspaceAgentScopeParams{
WorkspaceID: row.WorkspaceTable.ID,
OwnerID: row.WorkspaceTable.OwnerID,
TemplateID: row.WorkspaceTable.TemplateID,
VersionID: row.WorkspaceBuild.TemplateVersionID,
TaskID: row.TaskID,
BlockUserData: row.WorkspaceAgent.APIKeyScope == database.AgentKeyScopeEnumNoUserData,
}),
)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error with workspace agent authorization context.",
Detail: err.Error(),
})
return
}
ctx = context.WithValue(ctx, workspaceAgentContextKey{}, row.WorkspaceAgent)
ctx = context.WithValue(ctx, latestBuildContextKey{}, row.WorkspaceBuild)
// Also set the dbauthz actor for the request.
ctx = dbauthz.As(ctx, subject)
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
}