Skip to content

feat: Add option to enable hsts header #6147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Feb 10, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
13 changes: 13 additions & 0 deletions cli/deployment/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,19 @@ func newConfig() *codersdk.DeploymentConfig {
Usage: "Controls if the 'Secure' property is set on browser session cookies.",
Flag: "secure-auth-cookie",
},
StrictTransportSecurity: &codersdk.DeploymentConfigField[int]{
Name: "Strict-Transport-Security",
Usage: "Controls if the 'Strict-Transport-Security' header is set on all static file responses. " +
"This header should only be set if the server is accessed via HTTPS. The value should be a whole number in seconds.",
Copy link
Member

Choose a reason for hiding this comment

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

I think it would be good to explain that the number sets the maxAge here.

The time, in seconds, that the browser should remember that a site is only to be accessed using HTTPS.

We could also consider splitting this up into an enable bool and explicit maxage option that's required when enabled.

Copy link
Member Author

Choose a reason for hiding this comment

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

I added that in the message. If I add another flag, then it's 3 flags to turn this thing fully on :(. I figure anything >0 make sense to enable it.

Default: 0,
Flag: "strict-transport-security",
},
StrictTransportSecurityOptions: &codersdk.DeploymentConfigField[[]string]{
Name: "Strict-Transport-Security Options",
Usage: "Two optional fields can be set in the Strict-Transport-Security header; 'includeSubDomains' and 'preload'. " +
"The 'strict-transport-security' flag must be set to a non-zero value for these options to be used.",
Flag: "strict-transport-security-options",
},
SSHKeygenAlgorithm: &codersdk.DeploymentConfigField[string]{
Name: "SSH Keygen Algorithm",
Usage: "The algorithm to use for generating ssh keys. Accepted values are \"ed25519\", \"ecdsa\", or \"rsa4096\".",
Expand Down
48 changes: 25 additions & 23 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,29 +457,31 @@ func Server(vip *viper.Viper, newAPI func(context.Context, *coderd.Options) (*co
}

options := &coderd.Options{
AccessURL: accessURLParsed,
AppHostname: appHostname,
AppHostnameRegex: appHostnameRegex,
Logger: logger.Named("coderd"),
Database: dbfake.New(),
DERPMap: derpMap,
Pubsub: database.NewPubsubInMemory(),
CacheDir: cacheDir,
GoogleTokenValidator: googleTokenValidator,
GitAuthConfigs: gitAuthConfigs,
RealIPConfig: realIPConfig,
SecureAuthCookie: cfg.SecureAuthCookie.Value,
SSHKeygenAlgorithm: sshKeygenAlgorithm,
TracerProvider: tracerProvider,
Telemetry: telemetry.NewNoop(),
MetricsCacheRefreshInterval: cfg.MetricsCacheRefreshInterval.Value,
AgentStatsRefreshInterval: cfg.AgentStatRefreshInterval.Value,
DeploymentConfig: cfg,
PrometheusRegistry: prometheus.NewRegistry(),
APIRateLimit: cfg.RateLimit.API.Value,
LoginRateLimit: loginRateLimit,
FilesRateLimit: filesRateLimit,
HTTPClient: httpClient,
AccessURL: accessURLParsed,
AppHostname: appHostname,
AppHostnameRegex: appHostnameRegex,
Logger: logger.Named("coderd"),
Database: dbfake.New(),
DERPMap: derpMap,
Pubsub: database.NewPubsubInMemory(),
CacheDir: cacheDir,
GoogleTokenValidator: googleTokenValidator,
GitAuthConfigs: gitAuthConfigs,
RealIPConfig: realIPConfig,
SecureAuthCookie: cfg.SecureAuthCookie.Value,
StrictTransportSecurityAge: cfg.StrictTransportSecurity.Value,
StrictTransportSecurityOptions: cfg.StrictTransportSecurityOptions.Value,
SSHKeygenAlgorithm: sshKeygenAlgorithm,
TracerProvider: tracerProvider,
Telemetry: telemetry.NewNoop(),
MetricsCacheRefreshInterval: cfg.MetricsCacheRefreshInterval.Value,
AgentStatsRefreshInterval: cfg.AgentStatRefreshInterval.Value,
DeploymentConfig: cfg,
PrometheusRegistry: prometheus.NewRegistry(),
APIRateLimit: cfg.RateLimit.API.Value,
LoginRateLimit: loginRateLimit,
FilesRateLimit: filesRateLimit,
HTTPClient: httpClient,
}
if tlsConfig != nil {
options.TLSCertificates = tlsConfig.Certificates
Expand Down
6 changes: 6 additions & 0 deletions coderd/apidoc/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions coderd/apidoc/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 12 additions & 1 deletion coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ type Options struct {
OIDCConfig *OIDCConfig
PrometheusRegistry *prometheus.Registry
SecureAuthCookie bool
StrictTransportSecurityAge int
StrictTransportSecurityOptions []string
SSHKeygenAlgorithm gitsshkey.Algorithm
Telemetry telemetry.Reporter
TracerProvider trace.TracerProvider
Expand Down Expand Up @@ -222,12 +224,21 @@ func New(options *Options) *API {
options.MetricsCacheRefreshInterval,
)

staticHandler := site.Handler(site.FS(), binFS, binHashes)
// Static file handler must be wrapped with HSTS handler if the
// StrictTransportSecurityAge is set. We only need to set this header on
// static files since it only affects browsers.
staticHandler, err = httpmw.HSTS(staticHandler, options.StrictTransportSecurityAge, options.StrictTransportSecurityOptions)
if err != nil {
panic(xerrors.Errorf("coderd: setting hsts header failed (options: %v): %w", options.StrictTransportSecurityOptions, err))
Copy link
Member

Choose a reason for hiding this comment

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

The user experience will be poor here if they enter a wrong value into options.

Ideally we should verify this input before we start creating connections/starting the database in cli/server.go so the user gets immediate feedback. But even changing this New function to return an error would be better than panic'ing here IMO (and allow for a clean shutdown).

...
2023-02-10 08:34:44.658 [DEBUG]	(devtunnel.stdlib)	<./../../../golang.zx2c4.com/wireguard/device/send.go:401>	(*Device).RoutineEncryption	Routine: encryption worker 8 - stopped
2023-02-10 08:34:44.760 [DEBUG]	(postgres.stdlib)	<./../../fergusstrange/embedded-postgres/logging.go:47>	(*syncedLogger).flush	...
  "msg": waiting for server to shut down...2023-02-10 08:34:44.659 UTC [679345] LOG:  received fast shutdown request
         .2023-02-10 08:34:44.659 UTC [679345] LOG:  aborting any active transactions
         2023-02-10 08:34:44.661 UTC [679345] LOG:  background worker "logical replication launcher" (PID 679352) exited with exit code 1
         2023-02-10 08:34:44.661 UTC [679347] LOG:  shutting down
         2023-02-10 08:34:44.670 UTC [679345] LOG:  database system is shut down
          done
         server stopped
Stopped built-in PostgreSQL
panic: coderd: setting hsts header failed (options: [derp]): hsts: invalid option: "derp". Must be 'preload' and/or 'includeSubDomains'

goroutine 1 [running]:
github.com/coder/coder/coderd.New(0x2915170?)
	/home/mafredri/src/coder/coder/coderd/coderd.go:233 +0x1c93
github.com/coder/coder/enterprise/coderd.New({0x2915170, 0xc0006f12c0}, 0xc0004ab5e0)
	/home/mafredri/src/coder/coder/enterprise/coderd/coderd.go:54 +0x271
github.com/coder/coder/enterprise/cli.server.func1({0x2915170, 0xc0006f12c0}, 0xc0016dac80)
	/home/mafredri/src/coder/coder/enterprise/cli/server.go:76 +0x8d5
github.com/coder/coder/cli.Server.func1(0xc00127ef00, {0x234b98a?, 0x2?, 0x2?})
	/home/mafredri/src/coder/coder/cli/server.go:674 +0x58c8
github.com/spf13/cobra.(*Command).execute(0xc00127ef00, {0xc0004d3e20, 0x2, 0x2})
	/home/mafredri/.local/go/pkg/mod/github.com/spf13/cobra@v1.6.1/command.go:916 +0x862
github.com/spf13/cobra.(*Command).ExecuteC(0xc00132f800)
	/home/mafredri/.local/go/pkg/mod/github.com/spf13/cobra@v1.6.1/command.go:1044 +0x3bd
main.main()
	/home/mafredri/src/coder/coder/enterprise/cmd/coder/main.go:19 +0xaf

Copy link
Member Author

Choose a reason for hiding this comment

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

I can validate in cli/server.go. It is annoying the New doesn't return an error, so the panic method is how it works :/.

I'll just duplicate the valid check.

Copy link
Member

Choose a reason for hiding this comment

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

👍. I don’t think we use New in too many places, should be relatively easy to make it return an error?

Copy link
Member Author

Choose a reason for hiding this comment

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

Ok I changed it so I validate in server.go.

Coder v0.0.0-devel+8221ab0 - Software development on your infrastucture
Using built-in PostgreSQL (/home/steven/.config/coderv2/postgres)
Started HTTP listener at http://127.0.0.1:3000
Opening tunnel so workspaces can connect to your deployment. For production scenarios, specify an external access URL

View the Web UI: https://fcca5eb9087a599c0cb643b264752ea5.pit-1.try.coder.app
Stopping built-in PostgreSQL...
Stopped built-in PostgreSQL
coderd: setting hsts header failed (options: [asd]): hsts: invalid option: "asd". Must be 'preload' and/or 'includeSubDomains'
Run 'coder server --help' for usage.    

}

r := chi.NewRouter()
api := &API{
ID: uuid.New(),
Options: options,
RootHandler: r,
siteHandler: site.Handler(site.FS(), binFS, binHashes),
siteHandler: staticHandler,
HTTPAuth: &HTTPAuthorizer{
Authorizer: options.Authorizer,
Logger: options.Logger,
Expand Down
58 changes: 58 additions & 0 deletions coderd/httpmw/hsts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package httpmw

import (
"fmt"
"net/http"
"strings"

"golang.org/x/xerrors"
)

const (
hstsHeader = "Strict-Transport-Security"
)

// HSTS will add the strict-transport-security header if enabled. This header
// forces a browser to always use https for the domain after it loads https once.
// Meaning: On first load of product.coder.com, they are redirected to https. On
// all subsequent loads, the client's local browser forces https. This prevents
// man in the middle.
//
// This header only makes sense if the app is using tls.
//
// Full header example:
// Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
func HSTS(next http.Handler, maxAge int, options []string) (http.Handler, error) {
if maxAge <= 0 {
// No header, so no need to wrap the handler
return next, nil
}

// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
var str strings.Builder
_, err := str.WriteString(fmt.Sprintf("max-age=%d", maxAge))
if err != nil {
return nil, xerrors.Errorf("hsts: write max-age: %w", err)
}

for _, option := range options {
switch {
// Only allow valid options and fix any casing mistakes
case strings.EqualFold(option, "includeSubDomains"):
option = "includeSubDomains"
case strings.EqualFold(option, "preload"):
option = "preload"
default:
return nil, xerrors.Errorf("hsts: invalid option: %q. Must be 'preload' and/or 'includeSubDomains'", option)
}
_, err = str.WriteString("; " + option)
if err != nil {
return nil, xerrors.Errorf("hsts: write option: %w", err)
}
}

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(hstsHeader, str.String())
next.ServeHTTP(w, r)
}), nil
}
102 changes: 102 additions & 0 deletions coderd/httpmw/hsts_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package httpmw_test

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/require"

"github.com/coder/coder/coderd/httpmw"
)

func TestHSTS(t *testing.T) {
t.Parallel()

tests := []struct {
Name string
MaxAge int
Options []string

wantErr bool
expectHeader string
}{
{
Name: "Empty",
MaxAge: 0,
Options: nil,
},
{
Name: "NoAge",
MaxAge: 0,
Options: []string{"includeSubDomains"},
},
{
Name: "NegativeAge",
MaxAge: -100,
Options: []string{"includeSubDomains"},
},
{
Name: "Age",
MaxAge: 1000,
Options: []string{},
expectHeader: "max-age=1000",
},
{
Name: "AgeSubDomains",
MaxAge: 1000,
// Mess with casing
Options: []string{"INCLUDESUBDOMAINS"},
expectHeader: "max-age=1000; includeSubDomains",
},
{
Name: "AgePreload",
MaxAge: 1000,
Options: []string{"Preload"},
expectHeader: "max-age=1000; preload",
},
{
Name: "AllOptions",
MaxAge: 1000,
Options: []string{"preload", "includeSubDomains"},
expectHeader: "max-age=1000; preload; includeSubDomains",
},

// Error values
{
Name: "BadOption",
MaxAge: 100,
Options: []string{"not-valid"},
wantErr: true,
},
{
Name: "BadOptions",
MaxAge: 100,
Options: []string{"includeSubDomains", "not-valid", "still-not-valid"},
wantErr: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.Name, func(t *testing.T) {
t.Parallel()

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})

got, err := httpmw.HSTS(handler, tt.MaxAge, tt.Options)
if tt.wantErr {
require.Error(t, err, "Expect error, HSTS(%v, %v)", tt.MaxAge, tt.Options)
return
}

require.NoError(t, err, "Expect no error, HSTS(%v, %v)", tt.MaxAge, tt.Options)
req := httptest.NewRequest("GET", "/", nil)
res := httptest.NewRecorder()

got.ServeHTTP(res, req)
require.Equal(t, tt.expectHeader, res.Header().Get("Strict-Transport-Security"), "expected header value")
})
}
}
2 changes: 2 additions & 0 deletions codersdk/deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ type DeploymentConfig struct {
TLS *TLSConfig `json:"tls" typescript:",notnull"`
Trace *TraceConfig `json:"trace" typescript:",notnull"`
SecureAuthCookie *DeploymentConfigField[bool] `json:"secure_auth_cookie" typescript:",notnull"`
StrictTransportSecurity *DeploymentConfigField[int] `json:"strict_transport_security" typescript:",notnull"`
StrictTransportSecurityOptions *DeploymentConfigField[[]string] `json:"strict_transport_security_options" typescript:",notnull"`
SSHKeygenAlgorithm *DeploymentConfigField[string] `json:"ssh_keygen_algorithm" typescript:",notnull"`
MetricsCacheRefreshInterval *DeploymentConfigField[time.Duration] `json:"metrics_cache_refresh_interval" typescript:",notnull"`
AgentStatRefreshInterval *DeploymentConfigField[time.Duration] `json:"agent_stat_refresh_interval" typescript:",notnull"`
Expand Down
22 changes: 22 additions & 0 deletions docs/api/general.md
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,28 @@ curl -X GET http://coder-server:8080/api/v2/config/deployment \
"usage": "string",
"value": "string"
},
"strict_transport_security": {
"default": 0,
"enterprise": true,
"flag": "string",
"hidden": true,
"name": "string",
"secret": true,
"shorthand": "string",
"usage": "string",
"value": 0
},
"strict_transport_security_options": {
"default": ["string"],
"enterprise": true,
"flag": "string",
"hidden": true,
"name": "string",
"secret": true,
"shorthand": "string",
"usage": "string",
"value": ["string"]
},
"swagger": {
"enable": {
"default": true,
Expand Down
24 changes: 24 additions & 0 deletions docs/api/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -2256,6 +2256,28 @@ CreateParameterRequest is a structure used to create a new parameter value for a
"usage": "string",
"value": "string"
},
"strict_transport_security": {
"default": 0,
"enterprise": true,
"flag": "string",
"hidden": true,
"name": "string",
"secret": true,
"shorthand": "string",
"usage": "string",
"value": 0
},
"strict_transport_security_options": {
"default": ["string"],
"enterprise": true,
"flag": "string",
"hidden": true,
"name": "string",
"secret": true,
"shorthand": "string",
"usage": "string",
"value": ["string"]
},
"swagger": {
"enable": {
"default": true,
Expand Down Expand Up @@ -2515,6 +2537,8 @@ CreateParameterRequest is a structure used to create a new parameter value for a
| `scim_api_key` | [codersdk.DeploymentConfigField-string](#codersdkdeploymentconfigfield-string) | false | | |
| `secure_auth_cookie` | [codersdk.DeploymentConfigField-bool](#codersdkdeploymentconfigfield-bool) | false | | |
| `ssh_keygen_algorithm` | [codersdk.DeploymentConfigField-string](#codersdkdeploymentconfigfield-string) | false | | |
| `strict_transport_security` | [codersdk.DeploymentConfigField-int](#codersdkdeploymentconfigfield-int) | false | | |
| `strict_transport_security_options` | [codersdk.DeploymentConfigField-array_string](#codersdkdeploymentconfigfield-array_string) | false | | |
| `swagger` | [codersdk.SwaggerConfig](#codersdkswaggerconfig) | false | | |
| `telemetry` | [codersdk.TelemetryConfig](#codersdktelemetryconfig) | false | | |
| `tls` | [codersdk.TLSConfig](#codersdktlsconfig) | false | | |
Expand Down
4 changes: 4 additions & 0 deletions docs/cli/coder_server.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ coder server [flags]
Consumes $CODER_MAX_SESSION_EXPIRY (default 24h0m0s)
--ssh-keygen-algorithm string The algorithm to use for generating ssh keys. Accepted values are "ed25519", "ecdsa", or "rsa4096".
Consumes $CODER_SSH_KEYGEN_ALGORITHM (default "ed25519")
--strict-transport-security int Controls if the 'Strict-Transport-Security' header is set on all static file responses. This header should only be set if the server is accessed via HTTPS. The value should be a whole number in seconds.
Consumes $CODER_STRICT_TRANSPORT_SECURITY
--strict-transport-security-options strings Two optional fields can be set in the Strict-Transport-Security header; 'includeSubDomains' and 'preload'. The 'strict-transport-security' flag must be set to a non-zero value for these options to be used.
Consumes $CODER_STRICT_TRANSPORT_SECURITY_OPTIONS
--swagger-enable Expose the swagger endpoint via /swagger.
Consumes $CODER_SWAGGER_ENABLE
--telemetry Whether telemetry is enabled or not. Coder collects anonymized usage data to help improve our product.
Expand Down
2 changes: 2 additions & 0 deletions site/src/api/typesGenerated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,8 @@ export interface DeploymentConfig {
readonly tls: TLSConfig
readonly trace: TraceConfig
readonly secure_auth_cookie: DeploymentConfigField<boolean>
readonly strict_transport_security: DeploymentConfigField<number>
readonly strict_transport_security_options: DeploymentConfigField<string[]>
readonly ssh_keygen_algorithm: DeploymentConfigField<string>
readonly metrics_cache_refresh_interval: DeploymentConfigField<number>
readonly agent_stat_refresh_interval: DeploymentConfigField<number>
Expand Down