Skip to content

Commit bebe638

Browse files
committed
Add middleware for using system ctx in middlewares
1 parent 4b292e2 commit bebe638

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

coderd/coderd.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -295,8 +295,11 @@ func New(options *Options) *API {
295295
DisableSessionExpiryRefresh: options.DeploymentConfig.DisableSessionExpiryRefresh.Value,
296296
Optional: true,
297297
}),
298-
httpmw.ExtractUserParam(api.Database, false),
299-
httpmw.ExtractWorkspaceAndAgentParam(api.Database),
298+
// TODO: We should remove this auth context after middleware.
299+
httpmw.AsAuthzSystem(
300+
httpmw.ExtractUserParam(api.Database, false),
301+
httpmw.ExtractWorkspaceAndAgentParam(api.Database),
302+
),
300303
),
301304
// Build-Version is helpful for debugging.
302305
func(next http.Handler) http.Handler {
@@ -323,6 +326,8 @@ func New(options *Options) *API {
323326
DisableSessionExpiryRefresh: options.DeploymentConfig.DisableSessionExpiryRefresh.Value,
324327
Optional: true,
325328
}),
329+
// TODO: We should remove this auth context after middleware.
330+
httpmw.SystemAuthCtx,
326331
// Redirect to the login page if the user tries to open an app with
327332
// "me" as the username and they are not logged in.
328333
httpmw.ExtractUserParam(api.Database, true),

coderd/httpmw/authz.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package httpmw
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/coder/coder/coderd/database/dbauthz"
7+
8+
"github.com/go-chi/chi/v5"
9+
)
10+
11+
// AsAuthzSystem is a bit of a kludge for now. Some middleware functions require
12+
// usage as a system user in some cases, but not all cases. To avoid large
13+
// refactors, we use this middleware to temporarily set the context to a system.
14+
//
15+
// TODO: Refact the middleware functions to not require this.
16+
func AsAuthzSystem(mws ...func(http.Handler) http.Handler) func(http.Handler) http.Handler {
17+
chain := chi.Chain(mws...)
18+
return func(next http.Handler) http.Handler {
19+
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
20+
ctx := r.Context()
21+
before, _ := dbauthz.ActorFromContext(r.Context())
22+
23+
r = r.WithContext(dbauthz.AsSystem(ctx))
24+
chain.Handler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
25+
r = r.WithContext(dbauthz.As(r.Context(), before))
26+
next.ServeHTTP(rw, r)
27+
})).ServeHTTP(rw, r)
28+
})
29+
}
30+
}

0 commit comments

Comments
 (0)