Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,8 +393,10 @@ func New(options *Options) *API {

derpHandler := derphttp.Handler(api.DERPServer)
derpHandler, api.derpCloseFunc = tailnet.WithWebsocketSupport(api.DERPServer, derpHandler)
cors := httpmw.CorsMW(options.DeploymentValues.Dangerous.AllowAllCors.Value())

r.Use(
cors,
httpmw.Recover(api.Logger),
tracing.StatusWriterMiddleware,
tracing.Middleware(api.TracerProvider),
Expand Down Expand Up @@ -799,6 +801,10 @@ func New(options *Options) *API {
// Add CSP headers to all static assets and pages. CSP headers only affect
// browsers, so these don't make sense on api routes.
cspMW := httpmw.CSPHeaders(func() []string {
if api.DeploymentValues.Dangerous.AllowAllCors {
// In this mode, allow all external requests
return []string{"*"}
}
if f := api.WorkspaceProxyHostsFn.Load(); f != nil {
return (*f)()
}
Expand All @@ -813,7 +819,7 @@ func New(options *Options) *API {
// This is the only route we add before all the middleware.
// We want to time the latency of the request, so any middleware will
// interfere with that timing.
rootRouter.Get("/latency-check", LatencyCheck(api.AccessURL))
rootRouter.Get("/latency-check", cors(LatencyCheck(options.DeploymentValues.Dangerous.AllowAllCors.Value(), api.AccessURL)).ServeHTTP)
rootRouter.Mount("/", r)
api.RootHandler = rootRouter

Expand Down
20 changes: 20 additions & 0 deletions coderd/httpmw/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package httpmw

import (
"github.com/go-chi/cors"
"net/http"
)

func CorsMW(allowAll bool, origins ...string) func(next http.Handler) http.Handler {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did we not have a CORS MW before?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope. We don't need CORs for the primary coderd, since all web requests are on the same domain.

The issue is the latency request checks for external proxies uses absolute urls. The local yarn dev server runs on a different port. So for the yarn dev server to hit the /latency endpoint, I need to turn on CORs.

This PR blocks all CORs requests to coderd by default if the flag is not true

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was requested by @BrunoQuaresma. Without it, it was difficult for him to work on the workspace proxy UI.

if allowAll {
origins = []string{"*"}
}
return cors.Handler(cors.Options{
AllowedOrigins: origins,
// We only need GET for latency requests
AllowedMethods: []string{http.MethodOptions, http.MethodGet},
AllowedHeaders: []string{"Accept", "Content-Type", "X-LATENCY-CHECK", "X-CSRF-TOKEN"},
// Do not send any cookies
AllowCredentials: false,
})
}
5 changes: 5 additions & 0 deletions coderd/httpmw/csp.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ func CSPHeaders(websocketHosts func() []string) func(next http.Handler) http.Han
extraConnect := websocketHosts()
if len(extraConnect) > 0 {
for _, extraHost := range extraConnect {
if extraHost == "*" {
// '*' means all
cspSrcs.Append(cspDirectiveConnectSrc, "*")
continue
}
cspSrcs.Append(cspDirectiveConnectSrc, fmt.Sprintf("wss://%[1]s ws://%[1]s", extraHost))
// We also require this to make http/https requests to the workspace proxy for latency checking.
cspSrcs.Append(cspDirectiveConnectSrc, fmt.Sprintf("https://%[1]s http://%[1]s", extraHost))
Expand Down
8 changes: 7 additions & 1 deletion coderd/latencycheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,20 @@ import (
"strings"
)

func LatencyCheck(allowedOrigins ...*url.URL) http.HandlerFunc {
// LatencyCheck is an endpoint for the web ui to measure latency with.
// allowAll allows any Origin to get timing information. The allowAll should
// only be set in dev modes.
func LatencyCheck(allowAll bool, allowedOrigins ...*url.URL) http.HandlerFunc {
allowed := make([]string, 0, len(allowedOrigins))
for _, origin := range allowedOrigins {
// Allow the origin without a path
tmp := *origin
tmp.Path = ""
allowed = append(allowed, strings.TrimSuffix(origin.String(), "/"))
}
if allowAll {
allowed = append(allowed, "*")
}
origins := strings.Join(allowed, ",")
return func(rw http.ResponseWriter, r *http.Request) {
// Allowing timing information to be shared. This allows the browser
Expand Down
11 changes: 11 additions & 0 deletions codersdk/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ type LoggingConfig struct {
type DangerousConfig struct {
AllowPathAppSharing clibase.Bool `json:"allow_path_app_sharing" typescript:",notnull"`
AllowPathAppSiteOwnerAccess clibase.Bool `json:"allow_path_app_site_owner_access" typescript:",notnull"`
AllowAllCors clibase.Bool `json:"allow_all_cors" typescript:",notnull"`
}

const (
Expand Down Expand Up @@ -1167,6 +1168,16 @@ when required by your organization's security policy.`,
Annotations: clibase.Annotations{}.Mark(annotationExternalProxies, "true"),
},
// ☢️ Dangerous settings
{
Name: "DANGEROUS: Allow all CORs requests",
Description: "For security reasons, CORs requests are blocked. If external requests are required, setting this to true will set all cors headers as '*'. This should never be used in production.",
Flag: "dangerous-allow-cors-requests",
Env: "CODER_DANGEROUS_ALLOW_CORS_REQUESTS",
Hidden: true, // Hidden, should only be used by yarn dev server
Value: &c.Dangerous.AllowAllCors,
Group: &deploymentGroupDangerous,
Annotations: clibase.Annotations{}.Mark(annotationExternalProxies, "true"),
},
{
Name: "DANGEROUS: Allow Path App Sharing",
Description: "Allow workspace apps that are not served from subdomains to be shared. Path-based app sharing is DISABLED by default for security purposes. Path-based apps can make requests to the Coder API and pose a security risk when the workspace serves malicious JavaScript. Path-based apps can be disabled entirely with --disable-path-apps for further security.",
Expand Down
27 changes: 14 additions & 13 deletions enterprise/cli/proxyserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,19 +232,20 @@ func (*RootCmd) proxyServer() *clibase.Cmd {
}

proxy, err := wsproxy.New(ctx, &wsproxy.Options{
Logger: logger,
HTTPClient: httpClient,
DashboardURL: primaryAccessURL.Value(),
AccessURL: cfg.AccessURL.Value(),
AppHostname: appHostname,
AppHostnameRegex: appHostnameRegex,
RealIPConfig: realIPConfig,
Tracing: tracer,
PrometheusRegistry: prometheusRegistry,
APIRateLimit: int(cfg.RateLimit.API.Value()),
SecureAuthCookie: cfg.SecureAuthCookie.Value(),
DisablePathApps: cfg.DisablePathApps.Value(),
ProxySessionToken: proxySessionToken.Value(),
Logger: logger,
HTTPClient: httpClient,
DashboardURL: primaryAccessURL.Value(),
AccessURL: cfg.AccessURL.Value(),
AppHostname: appHostname,
AppHostnameRegex: appHostnameRegex,
RealIPConfig: realIPConfig,
Tracing: tracer,
PrometheusRegistry: prometheusRegistry,
APIRateLimit: int(cfg.RateLimit.API.Value()),
SecureAuthCookie: cfg.SecureAuthCookie.Value(),
DisablePathApps: cfg.DisablePathApps.Value(),
ProxySessionToken: proxySessionToken.Value(),
DangerousAllowAllCors: cfg.Dangerous.AllowAllCors.Value(),
})
if err != nil {
return xerrors.Errorf("create workspace proxy: %w", err)
Expand Down
19 changes: 4 additions & 15 deletions enterprise/wsproxy/wsproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/cors"
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/trace"
Expand Down Expand Up @@ -60,7 +59,8 @@ type Options struct {
SecureAuthCookie bool
DisablePathApps bool

ProxySessionToken string
ProxySessionToken string
DangerousAllowAllCors bool
}

func (o *Options) Validate() error {
Expand Down Expand Up @@ -189,18 +189,7 @@ func New(ctx context.Context, opts *Options) (*Server, error) {

// The primary coderd dashboard needs to make some GET requests to
// the workspace proxies to check latency.
corsMW := cors.Handler(cors.Options{
AllowedOrigins: []string{
// Allow the dashboard to make requests to the proxy for latency
// checks.
opts.DashboardURL.String(),
},
// Only allow GET requests for latency checks.
AllowedMethods: []string{http.MethodOptions, http.MethodGet},
AllowedHeaders: []string{"Accept", "Content-Type", "X-LATENCY-CHECK", "X-CSRF-TOKEN"},
// Do not send any cookies
AllowCredentials: false,
})
corsMW := httpmw.CorsMW(opts.DangerousAllowAllCors, opts.DashboardURL.String())

// Routes
apiRateLimiter := httpmw.RateLimit(opts.APIRateLimit, time.Minute)
Expand Down Expand Up @@ -266,7 +255,7 @@ func New(ctx context.Context, opts *Options) (*Server, error) {
// See coderd/coderd.go for why we need this.
rootRouter := chi.NewRouter()
// Make sure to add the cors middleware to the latency check route.
rootRouter.Get("/latency-check", corsMW(coderd.LatencyCheck(s.DashboardURL, s.AppServer.AccessURL)).ServeHTTP)
rootRouter.Get("/latency-check", corsMW(coderd.LatencyCheck(opts.DangerousAllowAllCors, s.DashboardURL, s.AppServer.AccessURL)).ServeHTTP)
rootRouter.Mount("/", r)
s.Handler = rootRouter

Expand Down
4 changes: 2 additions & 2 deletions scripts/develop.sh
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ fatal() {
trap 'fatal "Script encountered an error"' ERR

cdroot
start_cmd API "" "${CODER_DEV_SHIM}" server --http-address 0.0.0.0:3000 --swagger-enable --access-url "http://127.0.0.1:3000" --experiments "*" "$@"
start_cmd API "" "${CODER_DEV_SHIM}" server --http-address 0.0.0.0:3000 --swagger-enable --access-url "http://127.0.0.1:3000" --dangerous-allow-cors-requests=true --experiments "*" "$@"

echo '== Waiting for Coder to become ready'
# Start the timeout in the background so interrupting this script
Expand Down Expand Up @@ -185,7 +185,7 @@ fatal() {
# Create the proxy
proxy_session_token=$("${CODER_DEV_SHIM}" wsproxy create --name=local-proxy --display-name="Local Proxy" --icon="/emojis/1f4bb.png" --only-token)
# Start the proxy
start_cmd PROXY "" "${CODER_DEV_SHIM}" wsproxy server --http-address=localhost:3010 --proxy-session-token="${proxy_session_token}" --primary-access-url=http://localhost:3000
start_cmd PROXY "" "${CODER_DEV_SHIM}" wsproxy server --dangerous-allow-cors-requests=true --http-address=localhost:3010 --proxy-session-token="${proxy_session_token}" --primary-access-url=http://localhost:3000
) || echo "Failed to create workspace proxy. No workspace proxy created."
fi

Expand Down