Skip to content

feat: Add support for update checks and notifications #4810

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 14 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions buildinfo/buildinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ func VersionsMatch(v1, v2 string) bool {
return semver.MajorMinor(v1) == semver.MajorMinor(v2)
}

// IsDev returns true if this is a development build.
func IsDev() bool {
return strings.HasPrefix(Version(), develPrefix)
}

// ExternalURL returns a URL referencing the current Coder version.
// For production builds, this will link directly to a release.
// For development builds, this will link to a commit.
Expand Down
7 changes: 7 additions & 0 deletions cli/deployment/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/spf13/viper"
"golang.org/x/xerrors"

"github.com/coder/coder/buildinfo"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/cli/config"
"github.com/coder/coder/codersdk"
Expand Down Expand Up @@ -405,6 +406,12 @@ func newConfig() *codersdk.DeploymentConfig {
Usage: "Enable experimental features. Experimental features are not ready for production.",
Flag: "experimental",
},
UpdateCheck: &codersdk.DeploymentConfigField[bool]{
Name: "Update Check",
Usage: "Periodically check for new releases of Coder and inform the owner. The check is performed once per day.",
Flag: "update-check",
Default: flag.Lookup("test.v") == nil && !buildinfo.IsDev(),
},
}
}

Expand Down
2 changes: 2 additions & 0 deletions cli/deployment/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func TestConfig(t *testing.T) {
"CODER_TELEMETRY": "false",
"CODER_TELEMETRY_TRACE": "false",
"CODER_WILDCARD_ACCESS_URL": "something-wildcard.com",
"CODER_UPDATE_CHECK": "false",
},
Valid: func(config *codersdk.DeploymentConfig) {
require.Equal(t, config.Address.Value, "0.0.0.0:8443")
Expand All @@ -53,6 +54,7 @@ func TestConfig(t *testing.T) {
require.Equal(t, config.Telemetry.Enable.Value, false)
require.Equal(t, config.Telemetry.Trace.Value, false)
require.Equal(t, config.WildcardAccessURL.Value, "something-wildcard.com")
require.Equal(t, config.UpdateCheck.Value, false)
},
}, {
Name: "DERP",
Expand Down
20 changes: 20 additions & 0 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import (
"github.com/coder/coder/coderd/prometheusmetrics"
"github.com/coder/coder/coderd/telemetry"
"github.com/coder/coder/coderd/tracing"
"github.com/coder/coder/coderd/updatecheck"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
"github.com/coder/coder/provisioner/echo"
Expand Down Expand Up @@ -373,6 +374,25 @@ func Server(vip *viper.Viper, newAPI func(context.Context, *coderd.Options) (*co
options.TLSCertificates = tlsConfig.Certificates
}

if cfg.UpdateCheck.Value {
options.UpdateCheckOptions = &updatecheck.Options{
// Avoid spamming GitHub API checking for updates.
Interval: 24 * time.Hour,
// Inform server admins of new versions.
Notify: func(r updatecheck.Result) {
if semver.Compare(r.Version, buildinfo.Version()) > 0 {
options.Logger.Info(
context.Background(),
"new version of coder available",
slog.F("new_version", r.Version),
slog.F("url", r.URL),
slog.F("upgrade_instructions", "https://coder.com/docs/coder-oss/latest/admin/upgrade"),
)
}
},
}
}

if cfg.OAuth2.Github.ClientSecret.Value != "" {
options.GithubOAuth2Config, err = configureGithubOAuth2(accessURLParsed,
cfg.OAuth2.Github.ClientID.Value,
Expand Down
4 changes: 4 additions & 0 deletions cli/testdata/coder_server_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,10 @@ Flags:
verbose flag was supplied, debug-level
logs will be included.
Consumes $CODER_TRACE_CAPTURE_LOGS
--update-check Periodically check for new releases of
Coder and inform the owner. The check is
performed once per day.
Consumes $CODER_UPDATE_CHECK
--wildcard-access-url string Specifies the wildcard hostname to use
for workspace applications in the form
"*.example.com".
Expand Down
28 changes: 19 additions & 9 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import (
"github.com/coder/coder/coderd/rbac"
"github.com/coder/coder/coderd/telemetry"
"github.com/coder/coder/coderd/tracing"
"github.com/coder/coder/coderd/updatecheck"
"github.com/coder/coder/coderd/wsconncache"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/provisionerd/proto"
Expand Down Expand Up @@ -105,6 +106,7 @@ type Options struct {
AgentStatsRefreshInterval time.Duration
Experimental bool
DeploymentConfig *codersdk.DeploymentConfig
UpdateCheckOptions *updatecheck.Options // Set non-nil to enable update checking.
}

// New constructs a Coder API handler.
Expand All @@ -123,20 +125,14 @@ func New(options *Options) *API {
options.AgentInactiveDisconnectTimeout = options.AgentConnectionUpdateFrequency * 2
}
if options.AgentStatsRefreshInterval == 0 {
options.AgentStatsRefreshInterval = 10 * time.Minute
options.AgentStatsRefreshInterval = 5 * time.Minute
}
if options.MetricsCacheRefreshInterval == 0 {
options.MetricsCacheRefreshInterval = time.Hour
}
if options.APIRateLimit == 0 {
options.APIRateLimit = 512
}
if options.AgentStatsRefreshInterval == 0 {
options.AgentStatsRefreshInterval = 5 * time.Minute
}
if options.MetricsCacheRefreshInterval == 0 {
options.MetricsCacheRefreshInterval = time.Hour
}
if options.Authorizer == nil {
options.Authorizer = rbac.NewAuthorizer()
}
Expand Down Expand Up @@ -181,6 +177,13 @@ func New(options *Options) *API {
metricsCache: metricsCache,
Auditor: atomic.Pointer[audit.Auditor]{},
}
if options.UpdateCheckOptions != nil {
api.updateChecker = updatecheck.New(
options.Database,
options.Logger.Named("update_checker"),
*options.UpdateCheckOptions,
)
}
api.Auditor.Store(&options.Auditor)
api.workspaceAgentCache = wsconncache.New(api.dialWorkspaceAgentTailnet, 0)
api.TailnetCoordinator.Store(&options.TailnetCoordinator)
Expand Down Expand Up @@ -308,6 +311,9 @@ func New(options *Options) *API {
})
})
})
r.Route("/updatecheck", func(r chi.Router) {
r.Get("/", api.updateCheck)
})
r.Route("/config", func(r chi.Router) {
r.Use(apiKeyMiddleware)
r.Get("/deployment", api.deploymentConfig)
Expand Down Expand Up @@ -590,13 +596,14 @@ type API struct {
// RootHandler serves "/"
RootHandler chi.Router

metricsCache *metricscache.Cache
siteHandler http.Handler
siteHandler http.Handler

WebsocketWaitMutex sync.Mutex
WebsocketWaitGroup sync.WaitGroup

metricsCache *metricscache.Cache
workspaceAgentCache *wsconncache.Cache
updateChecker *updatecheck.Checker
}

// Close waits for all WebSocket connections to drain before returning.
Expand All @@ -606,6 +613,9 @@ func (api *API) Close() error {
api.WebsocketWaitMutex.Unlock()

api.metricsCache.Close()
if api.updateChecker != nil {
api.updateChecker.Close()
}
coordinator := api.TailnetCoordinator.Load()
if coordinator != nil {
_ = (*coordinator).Close()
Expand Down
1 change: 1 addition & 0 deletions coderd/coderdtest/authorize.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func AGPLRoutes(a *AuthTester) (map[string]string, map[string]RouteCheck) {
"GET:/healthz": {NoAuthorize: true},
"GET:/api/v2": {NoAuthorize: true},
"GET:/api/v2/buildinfo": {NoAuthorize: true},
"GET:/api/v2/updatecheck": {NoAuthorize: 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.

review(api): Technically, we restrict access in the WebUI so that only owners can view this information. It's not sensitive information by any means, but it's somewhat pointless to show to users. That's why we do not require authorization here (but I can change it if this behavior seems too weird).

Copy link
Member

Choose a reason for hiding this comment

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

Unless the "updatecheck" can trigger a real update and potentially crash the deployment, I guess that it's safe to expose it to everyone. On the other hand, if there is a known security issue, all users would be informed that there is an update to install, so the system is currently vulnerable.

Copy link
Member Author

Choose a reason for hiding this comment

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

The updatecheck is read-only, so it won't do anything scandalous. If we ever add a POST endpoint, that should obviously be protected. You raised a good point about vulnerabilities. Since Coder is an open source product, this information would be available to anyone checking the GitHub releases too. More than protecting this endpoint, we should consider how we convey this information through our releases.

"GET:/api/v2/users/first": {NoAuthorize: true},
"POST:/api/v2/users/first": {NoAuthorize: true},
"POST:/api/v2/users/login": {NoAuthorize: true},
Expand Down
5 changes: 5 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import (
"github.com/coder/coder/coderd/httpmw"
"github.com/coder/coder/coderd/rbac"
"github.com/coder/coder/coderd/telemetry"
"github.com/coder/coder/coderd/updatecheck"
"github.com/coder/coder/coderd/util/ptr"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/cryptorand"
Expand Down Expand Up @@ -102,6 +103,9 @@ type Options struct {
AgentStatsRefreshInterval time.Duration
DeploymentConfig *codersdk.DeploymentConfig

// Set update check options to enable update check.
UpdateCheckOptions *updatecheck.Options

// Overriding the database is heavily discouraged.
// It should only be used in cases where multiple Coder
// test instances are running against the same database.
Expand Down Expand Up @@ -283,6 +287,7 @@ func NewOptions(t *testing.T, options *Options) (func(http.Handler), context.Can
MetricsCacheRefreshInterval: options.MetricsCacheRefreshInterval,
AgentStatsRefreshInterval: options.AgentStatsRefreshInterval,
DeploymentConfig: options.DeploymentConfig,
UpdateCheckOptions: options.UpdateCheckOptions,
}
}

Expand Down
25 changes: 22 additions & 3 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,10 @@ type data struct {
workspaceResources []database.WorkspaceResource
workspaces []database.Workspace

deploymentID string
derpMeshKey string
lastLicenseID int32
deploymentID string
derpMeshKey string
lastUpdateCheck []byte
lastLicenseID int32
}

func (fakeQuerier) IsFakeDB() {}
Expand Down Expand Up @@ -3272,6 +3273,24 @@ func (q *fakeQuerier) GetDERPMeshKey(_ context.Context) (string, error) {
return q.derpMeshKey, nil
}

func (q *fakeQuerier) InsertOrUpdateLastUpdateCheck(_ context.Context, data string) error {
q.mutex.RLock()
defer q.mutex.RUnlock()

q.lastUpdateCheck = []byte(data)
return nil
}

func (q *fakeQuerier) GetLastUpdateCheck(_ context.Context) (string, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()

if q.lastUpdateCheck == nil {
return "", sql.ErrNoRows
}
return string(q.lastUpdateCheck), nil
}

func (q *fakeQuerier) InsertLicense(
_ context.Context, arg database.InsertLicenseParams,
) (database.License, error) {
Expand Down
2 changes: 2 additions & 0 deletions coderd/database/querier.go

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

21 changes: 21 additions & 0 deletions coderd/database/queries.sql.go

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

7 changes: 7 additions & 0 deletions coderd/database/queries/siteconfig.sql
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ INSERT INTO site_configs (key, value) VALUES ('derp_mesh_key', $1);

-- name: GetDERPMeshKey :one
SELECT value FROM site_configs WHERE key = 'derp_mesh_key';

-- name: InsertOrUpdateLastUpdateCheck :exec
INSERT INTO site_configs (key, value) VALUES ('last_update_check', $1)
ON CONFLICT (key) DO UPDATE SET value = $1 WHERE site_configs.key = 'last_update_check';

-- name: GetLastUpdateCheck :one
SELECT value FROM site_configs WHERE key = 'last_update_check';
54 changes: 54 additions & 0 deletions coderd/updatecheck.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package coderd

import (
"database/sql"
"net/http"
"strings"

"golang.org/x/mod/semver"
"golang.org/x/xerrors"

"github.com/coder/coder/buildinfo"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/codersdk"
)

func (api *API) updateCheck(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()

currentVersion := codersdk.UpdateCheckResponse{
Current: true,
Version: buildinfo.Version(),
URL: buildinfo.ExternalURL(),
}

if api.updateChecker == nil {
// If update checking is disabled, echo the current
// version.
httpapi.Write(ctx, rw, http.StatusOK, currentVersion)
return
}

uc, err := api.updateChecker.Latest(ctx)
if err != nil {
if xerrors.Is(err, sql.ErrNoRows) {
// Update checking is enabled, but has never
// succeeded, reproduce behavior as if disabled.
httpapi.Write(ctx, rw, http.StatusOK, currentVersion)
return
}

httpapi.InternalServerError(rw, err)
return
}

// Since our dev version (v0.12.9-devel+f7246386) is not semver compatible,
// ignore everything after "-"."
versionWithoutDevel := strings.SplitN(buildinfo.Version(), "-", 2)[0]

httpapi.Write(ctx, rw, http.StatusOK, codersdk.UpdateCheckResponse{
Current: semver.Compare(versionWithoutDevel, uc.Version) >= 0,
Version: uc.Version,
URL: uc.URL,
})
}
Loading