From f05609b4da0c0e178288224832e64e310bd521c4 Mon Sep 17 00:00:00 2001 From: Ammar Bandukwala Date: Sat, 18 Feb 2023 18:32:09 -0600 Subject: [PATCH] chore: format Go more aggressively --- Makefile | 8 +- agent/ssh.go | 2 +- cli/clitest/clitest.go | 2 +- cli/config/file.go | 4 +- cli/create_test.go | 6 +- cli/dotfiles.go | 2 +- cli/dotfiles_test.go | 10 +- cli/logout_test.go | 2 +- cli/parameter.go | 1 - cli/publickey.go | 4 +- cli/resetpassword.go | 4 +- cli/root.go | 4 +- cli/scaletest.go | 10 +- cli/server.go | 6 +- cli/state.go | 2 +- cli/templateinit.go | 2 +- cli/templatelist_test.go | 2 +- cli/templatepull.go | 2 +- cli/templatepull_test.go | 2 +- cli/templatepush.go | 4 +- cli/templateversions.go | 2 +- cli/tokens.go | 4 +- cli/update_test.go | 6 +- cli/util.go | 8 +- cli/vscodessh.go | 4 +- cli/vscodessh_test.go | 4 +- coderd/apikey.go | 8 +- coderd/audit/request.go | 2 +- .../executor/lifecycle_executor_test.go | 3 +- coderd/autobuild/schedule/schedule.go | 6 +- coderd/awsidentity/awsidentity.go | 4 +- coderd/coderd_test.go | 1 + coderd/coderdtest/authorize.go | 1 + coderd/database/dbauthz/dbauthz.go | 8 +- coderd/database/dbauthz/querier_test.go | 12 +- coderd/database/dbauthz/setup_test.go | 10 +- coderd/database/dbauthz/system.go | 1 + coderd/devtunnel/tunnel.go | 4 +- coderd/gitauth/vscode.go | 4 +- coderd/gitauth/vscode_test.go | 2 +- coderd/httpapi/json.go | 6 +- coderd/httpmw/oauth2_test.go | 3 +- coderd/httpmw/organizationparam.go | 6 +- coderd/httpmw/organizationparam_test.go | 4 +- coderd/insights_test.go | 1 - coderd/metricscache/metricscache.go | 1 - .../provisionerdserver/provisionerdserver.go | 4 +- coderd/rbac/authz_test.go | 6 +- coderd/rbac/builtin.go | 339 +++++++++--------- coderd/rbac/partial.go | 1 - coderd/rbac/regosql/acl_group_var.go | 6 +- coderd/rbac/regosql/sqltypes/always_false.go | 7 +- coderd/rbac/regosql/sqltypes/equality.go | 8 +- coderd/rbac/regosql/sqltypes/member.go | 8 +- coderd/rbac/regosql/sqltypes/variable.go | 6 +- coderd/templates_test.go | 1 - coderd/templateversions.go | 1 - coderd/tracing/httpmw_test.go | 6 +- coderd/tracing/status_writer.go | 6 +- coderd/tracing/status_writer_test.go | 4 +- coderd/util/tz/tz_darwin.go | 6 +- coderd/util/tz/tz_linux.go | 6 +- coderd/workspaceagents_test.go | 14 +- coderd/workspacebuilds.go | 2 +- coderd/workspacebuilds_test.go | 6 +- coderd/workspaces_test.go | 5 +- codersdk/apikey.go | 2 +- codersdk/deployment.go | 12 +- codersdk/organizations.go | 1 - codersdk/templates.go | 13 +- cryptorand/errors_test.go | 2 +- enterprise/audit/audit_test.go | 2 +- enterprise/audit/diff.go | 4 +- enterprise/cli/groupcreate.go | 8 +- enterprise/cli/groupedit_test.go | 4 +- enterprise/cli/grouplist.go | 4 +- enterprise/cli/grouplist_test.go | 3 +- enterprise/cli/licenses_test.go | 8 +- enterprise/replicasync/replicasync.go | 4 +- examples/examples.go | 4 +- provisioner/appslug.go | 20 +- provisioner/echo/serve_test.go | 2 +- provisioner/terraform/install.go | 2 +- provisioner/terraform/provision.go | 34 +- provisioner/terraform/provision_test.go | 7 +- provisioner/terraform/serve_internal_test.go | 2 +- provisionerd/runner/runner.go | 8 +- provisionersdk/archive.go | 2 +- provisionersdk/archive_test.go | 2 +- scaletest/createworkspaces/run.go | 6 +- scaletest/workspacebuild/run.go | 6 +- scripts/apidocgen/postprocess/main.go | 8 +- scripts/apitypings/main.go | 6 +- scripts/apitypings/testdata/enums/enums.go | 6 +- scripts/auditdocgen/main.go | 2 +- scripts/metricsdocgen/main.go | 2 +- tailnet/derpmap_test.go | 2 +- 97 files changed, 411 insertions(+), 413 deletions(-) diff --git a/Makefile b/Makefile index d556c84e43..754788c1e8 100644 --- a/Makefile +++ b/Makefile @@ -368,9 +368,15 @@ install: build/coder_$(VERSION)_$(GOOS)_$(GOARCH)$(GOOS_BIN_EXT) cp "$<" "$$output_file" .PHONY: install -fmt: fmt/prettier fmt/terraform fmt/shfmt +fmt: fmt/prettier fmt/terraform fmt/shfmt fmt/go .PHONY: fmt +fmt/go: + # VS Code users should check out + # https://github.com/mvdan/gofumpt#visual-studio-code + go run mvdan.cc/gofumpt@v0.4.0 -w -l . +.PHONY: fmt/go + fmt/prettier: echo "--- prettier" cd site diff --git a/agent/ssh.go b/agent/ssh.go index edebbeffd1..8aa41a1d26 100644 --- a/agent/ssh.go +++ b/agent/ssh.go @@ -70,7 +70,7 @@ func (h *forwardedUnixHandler) HandleSSHRequest(ctx ssh.Context, _ *ssh.Server, // Create socket parent dir if not exists. parentDir := filepath.Dir(addr) - err = os.MkdirAll(parentDir, 0700) + err = os.MkdirAll(parentDir, 0o700) if err != nil { h.log.Warn(ctx, "create parent dir for SSH unix forward request", slog.F("parent_dir", parentDir), diff --git a/cli/clitest/clitest.go b/cli/clitest/clitest.go index 086ffa7401..a28471e0c1 100644 --- a/cli/clitest/clitest.go +++ b/cli/clitest/clitest.go @@ -78,7 +78,7 @@ func extractTar(t *testing.T, data []byte, directory string) { path := filepath.Join(directory, header.Name) mode := header.FileInfo().Mode() if mode == 0 { - mode = 0600 + mode = 0o600 } switch header.Typeflag { case tar.TypeDir: diff --git a/cli/config/file.go b/cli/config/file.go index 26af6896c1..6ec0f28874 100644 --- a/cli/config/file.go +++ b/cli/config/file.go @@ -60,7 +60,7 @@ func (f File) Delete() error { // Write writes the string to the file. func (f File) Write(s string) error { - return write(string(f), 0600, []byte(s)) + return write(string(f), 0o600, []byte(s)) } // Read reads the file to a string. @@ -72,7 +72,7 @@ func (f File) Read() (string, error) { // open opens a file in the configuration directory, // creating all intermediate directories. func open(path string, flag int, mode os.FileMode) (*os.File, error) { - err := os.MkdirAll(filepath.Dir(path), 0750) + err := os.MkdirAll(filepath.Dir(path), 0o750) if err != nil { return nil, err } diff --git a/cli/create_test.go b/cli/create_test.go index b4cf3c2f63..5445db51cd 100644 --- a/cli/create_test.go +++ b/cli/create_test.go @@ -351,7 +351,8 @@ func TestCreateWithRichParameters(t *testing.T) { }, }, }, - }}, + }, + }, ProvisionApply: []*proto.Provision_Response{{ Type: &proto.Provision_Response_Complete{ Complete: &proto.Provision_Complete{}, @@ -475,7 +476,8 @@ func TestCreateValidateRichParameters(t *testing.T) { Parameters: richParameters, }, }, - }}, + }, + }, ProvisionApply: []*proto.Provision_Response{ { Type: &proto.Provision_Response_Complete{ diff --git a/cli/dotfiles.go b/cli/dotfiles.go index 0d9248250c..4adb06cc05 100644 --- a/cli/dotfiles.go +++ b/cli/dotfiles.go @@ -111,7 +111,7 @@ func dotfiles() *cobra.Command { } // ensure command dir exists - err = os.MkdirAll(gitCmdDir, 0750) + err = os.MkdirAll(gitCmdDir, 0o750) if err != nil { return xerrors.Errorf("ensuring dir at %s: %w", gitCmdDir, err) } diff --git a/cli/dotfiles_test.go b/cli/dotfiles_test.go index 3a0c731257..479baf3f9a 100644 --- a/cli/dotfiles_test.go +++ b/cli/dotfiles_test.go @@ -27,7 +27,7 @@ func TestDotfiles(t *testing.T) { testRepo := testGitRepo(t, root) // nolint:gosec - err := os.WriteFile(filepath.Join(testRepo, ".bashrc"), []byte("wow"), 0750) + err := os.WriteFile(filepath.Join(testRepo, ".bashrc"), []byte("wow"), 0o750) require.NoError(t, err) c := exec.Command("git", "add", ".bashrc") @@ -56,7 +56,7 @@ func TestDotfiles(t *testing.T) { testRepo := testGitRepo(t, root) // nolint:gosec - err := os.WriteFile(filepath.Join(testRepo, "install.sh"), []byte("#!/bin/bash\necho wow > "+filepath.Join(string(root), ".bashrc")), 0750) + err := os.WriteFile(filepath.Join(testRepo, "install.sh"), []byte("#!/bin/bash\necho wow > "+filepath.Join(string(root), ".bashrc")), 0o750) require.NoError(t, err) c := exec.Command("git", "add", "install.sh") @@ -82,12 +82,12 @@ func TestDotfiles(t *testing.T) { testRepo := testGitRepo(t, root) // nolint:gosec - err := os.WriteFile(filepath.Join(testRepo, ".bashrc"), []byte("wow"), 0750) + err := os.WriteFile(filepath.Join(testRepo, ".bashrc"), []byte("wow"), 0o750) require.NoError(t, err) // add a conflicting file at destination // nolint:gosec - err = os.WriteFile(filepath.Join(string(root), ".bashrc"), []byte("backup"), 0750) + err = os.WriteFile(filepath.Join(string(root), ".bashrc"), []byte("backup"), 0o750) require.NoError(t, err) c := exec.Command("git", "add", ".bashrc") @@ -119,7 +119,7 @@ func testGitRepo(t *testing.T, root config.Root) string { r, err := cryptorand.String(8) require.NoError(t, err) dir := filepath.Join(string(root), fmt.Sprintf("test-repo-%s", r)) - err = os.MkdirAll(dir, 0750) + err = os.MkdirAll(dir, 0o750) require.NoError(t, err) c := exec.Command("git", "init") diff --git a/cli/logout_test.go b/cli/logout_test.go index cef16c21b7..dea70710ba 100644 --- a/cli/logout_test.go +++ b/cli/logout_test.go @@ -149,7 +149,7 @@ func TestLogout(t *testing.T) { require.NoError(t, err) } else { // Changing the permissions to throw error during deletion. - err = os.Chmod(string(config), 0500) + err = os.Chmod(string(config), 0o500) require.NoError(t, err) } defer func() { diff --git a/cli/parameter.go b/cli/parameter.go index 127ac58cf5..d826b1ec69 100644 --- a/cli/parameter.go +++ b/cli/parameter.go @@ -18,7 +18,6 @@ func createParameterMapFromFile(parameterFile string) (map[string]string, error) parameterMap := make(map[string]string) parameterFileContents, err := os.ReadFile(parameterFile) - if err != nil { return nil, err } diff --git a/cli/publickey.go b/cli/publickey.go index 6926ecf322..3872baf594 100644 --- a/cli/publickey.go +++ b/cli/publickey.go @@ -11,9 +11,7 @@ import ( ) func publickey() *cobra.Command { - var ( - reset bool - ) + var reset bool cmd := &cobra.Command{ Use: "publickey", diff --git a/cli/resetpassword.go b/cli/resetpassword.go index 72b6d65705..8aea553730 100644 --- a/cli/resetpassword.go +++ b/cli/resetpassword.go @@ -15,9 +15,7 @@ import ( ) func resetPassword() *cobra.Command { - var ( - postgresURL string - ) + var postgresURL string root := &cobra.Command{ Use: "reset-password ", diff --git a/cli/root.go b/cli/root.go index 19ac241e29..254368a01d 100644 --- a/cli/root.go +++ b/cli/root.go @@ -64,9 +64,7 @@ const ( envURL = "CODER_URL" ) -var ( - errUnauthenticated = xerrors.New(notLoggedInMessage) -) +var errUnauthenticated = xerrors.New(notLoggedInMessage) func init() { // Set cobra template functions in init to avoid conflicts in tests. diff --git a/cli/scaletest.go b/cli/scaletest.go index 8dbd270f28..b367b580bb 100644 --- a/cli/scaletest.go +++ b/cli/scaletest.go @@ -309,9 +309,7 @@ func (r *userCleanupRunner) Run(ctx context.Context, _ string, _ io.Writer) erro } func scaletestCleanup() *cobra.Command { - var ( - cleanupStrategy = &scaletestStrategyFlags{cleanup: true} - ) + cleanupStrategy := &scaletestStrategyFlags{cleanup: true} cmd := &cobra.Command{ Use: "cleanup", @@ -810,8 +808,10 @@ type runnableTraceWrapper struct { span trace.Span } -var _ harness.Runnable = &runnableTraceWrapper{} -var _ harness.Cleanable = &runnableTraceWrapper{} +var ( + _ harness.Runnable = &runnableTraceWrapper{} + _ harness.Cleanable = &runnableTraceWrapper{} +) func (r *runnableTraceWrapper) Run(ctx context.Context, id string, logs io.Writer) error { ctx, span := r.tracer.Start(ctx, r.spanName, trace.WithNewRoot()) diff --git a/cli/server.go b/cli/server.go index 75aa44d0fd..2129b6fca3 100644 --- a/cli/server.go +++ b/cli/server.go @@ -976,9 +976,7 @@ func Server(vip *viper.Viper, newAPI func(context.Context, *coderd.Options) (*co // parseURL parses a string into a URL. func parseURL(u string) (*url.URL, error) { - var ( - hasScheme = strings.HasPrefix(u, "http:") || strings.HasPrefix(u, "https:") - ) + hasScheme := strings.HasPrefix(u, "http:") || strings.HasPrefix(u, "https:") if !hasScheme { return nil, xerrors.Errorf("URL %q must have a scheme of either http or https", u) @@ -1529,7 +1527,7 @@ func buildLogger(cmd *cobra.Command, cfg *codersdk.DeploymentConfig) (slog.Logge sinks = append(sinks, sinkFn(cmd.ErrOrStderr())) default: - fi, err := os.OpenFile(loc, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + fi, err := os.OpenFile(loc, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644) if err != nil { return xerrors.Errorf("open log file %q: %w", loc, err) } diff --git a/cli/state.go b/cli/state.go index bd1c0ccad4..ca7336bffc 100644 --- a/cli/state.go +++ b/cli/state.go @@ -58,7 +58,7 @@ func statePull() *cobra.Command { return nil } - return os.WriteFile(args[1], state, 0600) + return os.WriteFile(args[1], state, 0o600) }, } cmd.Flags().IntVarP(&buildNumber, "build", "b", 0, "Specify a workspace build to target by name.") diff --git a/cli/templateinit.go b/cli/templateinit.go index b69fa1086b..dfb096bce0 100644 --- a/cli/templateinit.go +++ b/cli/templateinit.go @@ -67,7 +67,7 @@ func templateInit() *cobra.Command { relPath = "./" + relPath } _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Extracting %s to %s...\n", cliui.Styles.Field.Render(selectedTemplate.ID), relPath) - err = os.MkdirAll(directory, 0700) + err = os.MkdirAll(directory, 0o700) if err != nil { return err } diff --git a/cli/templatelist_test.go b/cli/templatelist_test.go index 3063239b28..841b1f0e2e 100644 --- a/cli/templatelist_test.go +++ b/cli/templatelist_test.go @@ -46,7 +46,7 @@ func TestTemplateList(t *testing.T) { }() // expect that templates are listed alphabetically - var templatesList = []string{firstTemplate.Name, secondTemplate.Name} + templatesList := []string{firstTemplate.Name, secondTemplate.Name} sort.Strings(templatesList) require.NoError(t, <-errC) diff --git a/cli/templatepull.go b/cli/templatepull.go index 19e5e04d82..72a69de39e 100644 --- a/cli/templatepull.go +++ b/cli/templatepull.go @@ -108,7 +108,7 @@ func templatePull() *cobra.Command { } } - err = os.WriteFile(dest, raw, 0600) + err = os.WriteFile(dest, raw, 0o600) if err != nil { return xerrors.Errorf("write to path: %w", err) } diff --git a/cli/templatepull_test.go b/cli/templatepull_test.go index 0ae1fc740a..f19725c21f 100644 --- a/cli/templatepull_test.go +++ b/cli/templatepull_test.go @@ -97,7 +97,7 @@ func TestTemplatePull(t *testing.T) { // Create the file so that we can test that the command // warns the user before overwriting a preexisting file. - fi, err := os.OpenFile(dest, os.O_CREATE|os.O_RDONLY, 0600) + fi, err := os.OpenFile(dest, os.O_CREATE|os.O_RDONLY, 0o600) require.NoError(t, err) _ = fi.Close() diff --git a/cli/templatepush.go b/cli/templatepush.go index c9217cc35f..273ee9788d 100644 --- a/cli/templatepush.go +++ b/cli/templatepush.go @@ -34,9 +34,7 @@ func (pf *templateUploadFlags) stdin() bool { } func (pf *templateUploadFlags) upload(cmd *cobra.Command, client *codersdk.Client) (*codersdk.UploadResponse, error) { - var ( - content io.Reader - ) + var content io.Reader if pf.stdin() { content = cmd.InOrStdin() } else { diff --git a/cli/templateversions.go b/cli/templateversions.go index c8c50de2f3..91f8408e7a 100644 --- a/cli/templateversions.go +++ b/cli/templateversions.go @@ -99,7 +99,7 @@ type templateVersionRow struct { func templateVersionsToRows(activeVersionID uuid.UUID, templateVersions ...codersdk.TemplateVersion) []templateVersionRow { rows := make([]templateVersionRow, len(templateVersions)) for i, templateVersion := range templateVersions { - var activeStatus = "" + activeStatus := "" if templateVersion.ID == activeVersionID { activeStatus = cliui.Styles.Code.Render(cliui.Styles.Keyword.Render("Active")) } diff --git a/cli/tokens.go b/cli/tokens.go index dadbce5b3c..125f5d35c6 100644 --- a/cli/tokens.go +++ b/cli/tokens.go @@ -47,9 +47,7 @@ func tokens() *cobra.Command { } func createToken() *cobra.Command { - var ( - tokenLifetime time.Duration - ) + var tokenLifetime time.Duration cmd := &cobra.Command{ Use: "create", Short: "Create a tokens", diff --git a/cli/update_test.go b/cli/update_test.go index 60f644744e..d148e55708 100644 --- a/cli/update_test.go +++ b/cli/update_test.go @@ -172,7 +172,8 @@ func TestUpdateWithRichParameters(t *testing.T) { }, }, }, - }}, + }, + }, ProvisionApply: []*proto.Provision_Response{{ Type: &proto.Provision_Response_Complete{ Complete: &proto.Provision_Complete{}, @@ -269,7 +270,8 @@ func TestUpdateValidateRichParameters(t *testing.T) { Parameters: richParameters, }, }, - }}, + }, + }, ProvisionApply: []*proto.Provision_Response{ { Type: &proto.Provision_Response_Complete{ diff --git a/cli/util.go b/cli/util.go index 982b3fdba3..7ea5dd27e7 100644 --- a/cli/util.go +++ b/cli/util.go @@ -12,9 +12,11 @@ import ( "github.com/coder/coder/coderd/util/tz" ) -var errInvalidScheduleFormat = xerrors.New("Schedule must be in the format Mon-Fri 09:00AM America/Chicago") -var errInvalidTimeFormat = xerrors.New("Start time must be in the format hh:mm[am|pm] or HH:MM") -var errUnsupportedTimezone = xerrors.New("The location you provided looks like a timezone. Check https://ipinfo.io for your location.") +var ( + errInvalidScheduleFormat = xerrors.New("Schedule must be in the format Mon-Fri 09:00AM America/Chicago") + errInvalidTimeFormat = xerrors.New("Start time must be in the format hh:mm[am|pm] or HH:MM") + errUnsupportedTimezone = xerrors.New("The location you provided looks like a timezone. Check https://ipinfo.io for your location.") +) // durationDisplay formats a duration for easier display: // - Durations of 24 hours or greater are displays as Xd diff --git a/cli/vscodessh.go b/cli/vscodessh.go index e6c3f83034..a97c6ae682 100644 --- a/cli/vscodessh.go +++ b/cli/vscodessh.go @@ -74,7 +74,7 @@ func vscodeSSH() *cobra.Command { ctx, cancel := context.WithCancel(cmd.Context()) defer cancel() - err = fs.MkdirAll(networkInfoDir, 0700) + err = fs.MkdirAll(networkInfoDir, 0o700) if err != nil { return xerrors.Errorf("mkdir: %w", err) } @@ -168,7 +168,7 @@ func vscodeSSH() *cobra.Command { sendErr(err) return } - err = afero.WriteFile(fs, networkInfoFilePath, rawStats, 0600) + err = afero.WriteFile(fs, networkInfoFilePath, rawStats, 0o600) if err != nil { sendErr(err) return diff --git a/cli/vscodessh_test.go b/cli/vscodessh_test.go index 83fd665bb5..605ce6a823 100644 --- a/cli/vscodessh_test.go +++ b/cli/vscodessh_test.go @@ -41,9 +41,9 @@ func TestVSCodeSSH(t *testing.T) { coderdtest.AwaitWorkspaceAgents(t, client, workspace.ID) fs := afero.NewMemMapFs() - err = afero.WriteFile(fs, "/url", []byte(client.URL.String()), 0600) + err = afero.WriteFile(fs, "/url", []byte(client.URL.String()), 0o600) require.NoError(t, err) - err = afero.WriteFile(fs, "/token", []byte(client.SessionToken()), 0600) + err = afero.WriteFile(fs, "/token", []byte(client.SessionToken()), 0o600) require.NoError(t, err) cmd, _ := clitest.New(t, diff --git a/coderd/apikey.go b/coderd/apikey.go index 06ad18f06c..7c4c6d7650 100644 --- a/coderd/apikey.go +++ b/coderd/apikey.go @@ -142,9 +142,7 @@ func (api *API) postAPIKey(rw http.ResponseWriter, r *http.Request) { // @Success 200 {object} codersdk.APIKey // @Router /users/{user}/keys/{keyid} [get] func (api *API) apiKey(rw http.ResponseWriter, r *http.Request) { - var ( - ctx = r.Context() - ) + ctx := r.Context() keyID := chi.URLParam(r, "keyid") key, err := api.Database.GetAPIKeyByID(ctx, keyID) @@ -177,9 +175,7 @@ func (api *API) apiKey(rw http.ResponseWriter, r *http.Request) { // @Success 200 {array} codersdk.APIKey // @Router /users/{user}/keys/tokens [get] func (api *API) tokens(rw http.ResponseWriter, r *http.Request) { - var ( - ctx = r.Context() - ) + ctx := r.Context() keys, err := api.Database.GetAPIKeysByLoginType(ctx, database.LoginTypeToken) if err != nil { diff --git a/coderd/audit/request.go b/coderd/audit/request.go index b9ec814568..8aba0ffc30 100644 --- a/coderd/audit/request.go +++ b/coderd/audit/request.go @@ -158,7 +158,7 @@ func InitRequest[T Auditable](w http.ResponseWriter, p *RequestParams) (*Request } } - var diffRaw = []byte("{}") + diffRaw := []byte("{}") // Only generate diffs if the request succeeded. if sw.Status < 400 { diff := Diff(p.Audit, req.Old, req.New) diff --git a/coderd/autobuild/executor/lifecycle_executor_test.go b/coderd/autobuild/executor/lifecycle_executor_test.go index 8b3e6b89fd..ac0ee6c625 100644 --- a/coderd/autobuild/executor/lifecycle_executor_test.go +++ b/coderd/autobuild/executor/lifecycle_executor_test.go @@ -628,7 +628,8 @@ func mustProvisionWorkspaceWithParameters(t *testing.T, client *codersdk.Client, Parameters: richParameters, }, }, - }}, + }, + }, ProvisionApply: []*proto.Provision_Response{ { Type: &proto.Provision_Response_Complete{ diff --git a/coderd/autobuild/schedule/schedule.go b/coderd/autobuild/schedule/schedule.go index 59433450c0..d13c367a2e 100644 --- a/coderd/autobuild/schedule/schedule.go +++ b/coderd/autobuild/schedule/schedule.go @@ -111,8 +111,10 @@ func (s Schedule) Next(t time.Time) time.Time { return s.sched.Next(t) } -var t0 = time.Date(1970, 1, 1, 1, 1, 1, 0, time.UTC) -var tMax = t0.Add(168 * time.Hour) +var ( + t0 = time.Date(1970, 1, 1, 1, 1, 1, 0, time.UTC) + tMax = t0.Add(168 * time.Hour) +) // Min returns the minimum duration of the schedule. // This is calculated as follows: diff --git a/coderd/awsidentity/awsidentity.go b/coderd/awsidentity/awsidentity.go index 472efbfe9c..98d0e69478 100644 --- a/coderd/awsidentity/awsidentity.go +++ b/coderd/awsidentity/awsidentity.go @@ -25,9 +25,7 @@ const ( GovCloud Region = "govcloud" ) -var ( - All = []Region{Other, HongKong, Bahrain, CapeTown, Milan, China, GovCloud} -) +var All = []Region{Other, HongKong, Bahrain, CapeTown, Milan, China, GovCloud} // Certificates hold public keys for various AWS regions. See: type Certificates map[Region]string diff --git a/coderd/coderd_test.go b/coderd/coderd_test.go index e38fef2e23..e62240aeda 100644 --- a/coderd/coderd_test.go +++ b/coderd/coderd_test.go @@ -115,6 +115,7 @@ func TestDERPLatencyCheck(t *testing.T) { defer res.Body.Close() require.Equal(t, http.StatusOK, res.StatusCode) } + func TestHealthz(t *testing.T) { t.Parallel() client := coderdtest.New(t, nil) diff --git a/coderd/coderdtest/authorize.go b/coderd/coderdtest/authorize.go index 294ac80c08..2b594bd1ee 100644 --- a/coderd/coderdtest/authorize.go +++ b/coderd/coderdtest/authorize.go @@ -693,6 +693,7 @@ func (s *PreparedRecorder) Authorize(ctx context.Context, object rbac.Object) er } return s.prepped.Authorize(ctx, object) } + func (s *PreparedRecorder) CompileToSQL(ctx context.Context, cfg regosql.ConvertConfig) (string, error) { s.rw.Lock() defer s.rw.Unlock() diff --git a/coderd/database/dbauthz/dbauthz.go b/coderd/database/dbauthz/dbauthz.go index bdcc85ff61..4f139bdc0b 100644 --- a/coderd/database/dbauthz/dbauthz.go +++ b/coderd/database/dbauthz/dbauthz.go @@ -17,11 +17,9 @@ import ( var _ database.Store = (*querier)(nil) -var ( - // NoActorError wraps ErrNoRows for the api to return a 404. This is the correct - // response when the user is not authorized. - NoActorError = xerrors.Errorf("no authorization actor in context: %w", sql.ErrNoRows) -) +// NoActorError wraps ErrNoRows for the api to return a 404. This is the correct +// response when the user is not authorized. +var NoActorError = xerrors.Errorf("no authorization actor in context: %w", sql.ErrNoRows) // NotAuthorizedError is a sentinel error that unwraps to sql.ErrNoRows. // This allows the internal error to be read by the caller if needed. Otherwise diff --git a/coderd/database/dbauthz/querier_test.go b/coderd/database/dbauthz/querier_test.go index a22b70ac08..8fc6178001 100644 --- a/coderd/database/dbauthz/querier_test.go +++ b/coderd/database/dbauthz/querier_test.go @@ -439,11 +439,13 @@ func (s *MethodTestSuite) TestParameters() { s.Run("TemplateVersionTemplate/InsertParameterValue", s.Subtest(func(db database.Store, check *expects) { j := dbgen.ProvisionerJob(s.T(), db, database.ProvisionerJob{}) tpl := dbgen.Template(s.T(), db, database.Template{}) - v := dbgen.TemplateVersion(s.T(), db, database.TemplateVersion{JobID: j.ID, + v := dbgen.TemplateVersion(s.T(), db, database.TemplateVersion{ + JobID: j.ID, TemplateID: uuid.NullUUID{ UUID: tpl.ID, Valid: true, - }}, + }, + }, ) check.Args(database.InsertParameterValueParams{ ScopeID: j.ID, @@ -528,12 +530,14 @@ func (s *MethodTestSuite) TestTemplate() { ID: tvid, Name: t1.Name, OrganizationID: o1.ID, - TemplateID: uuid.NullUUID{UUID: t1.ID, Valid: true}}) + TemplateID: uuid.NullUUID{UUID: t1.ID, Valid: true}, + }) b := dbgen.TemplateVersion(s.T(), db, database.TemplateVersion{ CreatedAt: now.Add(-2 * time.Hour), Name: t1.Name, OrganizationID: o1.ID, - TemplateID: uuid.NullUUID{UUID: t1.ID, Valid: true}}) + TemplateID: uuid.NullUUID{UUID: t1.ID, Valid: true}, + }) check.Args(database.GetPreviousTemplateVersionParams{ Name: t1.Name, OrganizationID: o1.ID, diff --git a/coderd/database/dbauthz/setup_test.go b/coderd/database/dbauthz/setup_test.go index d6e44406e7..6ed55c8c9f 100644 --- a/coderd/database/dbauthz/setup_test.go +++ b/coderd/database/dbauthz/setup_test.go @@ -25,12 +25,10 @@ import ( "github.com/coder/coder/coderd/util/slice" ) -var ( - skipMethods = map[string]string{ - "InTx": "Not relevant", - "Ping": "Not relevant", - } -) +var skipMethods = map[string]string{ + "InTx": "Not relevant", + "Ping": "Not relevant", +} // TestMethodTestSuite runs MethodTestSuite. // In order for 'go test' to run this suite, we need to create diff --git a/coderd/database/dbauthz/system.go b/coderd/database/dbauthz/system.go index a4e622a397..5baf6ad760 100644 --- a/coderd/database/dbauthz/system.go +++ b/coderd/database/dbauthz/system.go @@ -154,6 +154,7 @@ func (q *querier) DeleteOldAgentStats(ctx context.Context) error { func (q *querier) GetParameterSchemasCreatedAfter(ctx context.Context, createdAt time.Time) ([]database.ParameterSchema, error) { return q.db.GetParameterSchemasCreatedAfter(ctx, createdAt) } + func (q *querier) GetProvisionerJobsCreatedAfter(ctx context.Context, createdAt time.Time) ([]database.ProvisionerJob, error) { return q.db.GetProvisionerJobsCreatedAfter(ctx, createdAt) } diff --git a/coderd/devtunnel/tunnel.go b/coderd/devtunnel/tunnel.go index 8adc68fb1e..d0d8a9f466 100644 --- a/coderd/devtunnel/tunnel.go +++ b/coderd/devtunnel/tunnel.go @@ -219,7 +219,7 @@ func cfgPath() (string, error) { } cfgDir = filepath.Join(cfgDir, "coderv2") - err = os.MkdirAll(cfgDir, 0750) + err = os.MkdirAll(cfgDir, 0o750) if err != nil { return "", xerrors.Errorf("mkdirall config dir %q: %w", cfgDir, err) } @@ -327,7 +327,7 @@ func writeConfig(cfg Config) error { return xerrors.Errorf("marshal config: %w", err) } - err = os.WriteFile(cfgFi, raw, 0600) + err = os.WriteFile(cfgFi, raw, 0o600) if err != nil { return xerrors.Errorf("write file: %w", err) } diff --git a/coderd/gitauth/vscode.go b/coderd/gitauth/vscode.go index 8ab178b080..ce3c64081b 100644 --- a/coderd/gitauth/vscode.go +++ b/coderd/gitauth/vscode.go @@ -51,7 +51,7 @@ func OverrideVSCodeConfigs(fs afero.Fs) error { return xerrors.Errorf("mkdir all: %w", err) } - err = afero.WriteFile(fs, configPath, data, 0600) + err = afero.WriteFile(fs, configPath, data, 0o600) if err != nil { return xerrors.Errorf("write %q: %w", configPath, err) } @@ -72,7 +72,7 @@ func OverrideVSCodeConfigs(fs afero.Fs) error { if err != nil { return xerrors.Errorf("marshal %q: %w", configPath, err) } - err = afero.WriteFile(fs, configPath, data, 0600) + err = afero.WriteFile(fs, configPath, data, 0o600) if err != nil { return xerrors.Errorf("write %q: %w", configPath, err) } diff --git a/coderd/gitauth/vscode_test.go b/coderd/gitauth/vscode_test.go index fca7994d93..f61fb97ea6 100644 --- a/coderd/gitauth/vscode_test.go +++ b/coderd/gitauth/vscode_test.go @@ -45,7 +45,7 @@ func TestOverrideVSCodeConfigs(t *testing.T) { data, err := json.Marshal(mapping) require.NoError(t, err) for _, configPath := range configPaths { - err = afero.WriteFile(fs, configPath, data, 0600) + err = afero.WriteFile(fs, configPath, data, 0o600) require.NoError(t, err) } err = gitauth.OverrideVSCodeConfigs(fs) diff --git a/coderd/httpapi/json.go b/coderd/httpapi/json.go index 8503dae6ef..b9a50251a1 100644 --- a/coderd/httpapi/json.go +++ b/coderd/httpapi/json.go @@ -16,8 +16,10 @@ import ( // string or an integer. type Duration time.Duration -var _ json.Marshaler = Duration(0) -var _ json.Unmarshaler = (*Duration)(nil) +var ( + _ json.Marshaler = Duration(0) + _ json.Unmarshaler = (*Duration)(nil) +) // MarshalJSON implements json.Marshaler. func (d Duration) MarshalJSON() ([]byte, error) { diff --git a/coderd/httpmw/oauth2_test.go b/coderd/httpmw/oauth2_test.go index 40fcb9186e..37d5f15fb1 100644 --- a/coderd/httpmw/oauth2_test.go +++ b/coderd/httpmw/oauth2_test.go @@ -15,8 +15,7 @@ import ( "github.com/coder/coder/codersdk" ) -type testOAuth2Provider struct { -} +type testOAuth2Provider struct{} func (*testOAuth2Provider) AuthCodeURL(state string, _ ...oauth2.AuthCodeOption) string { return "?state=" + url.QueryEscape(state) diff --git a/coderd/httpmw/organizationparam.go b/coderd/httpmw/organizationparam.go index da27ac577c..8dc65df20e 100644 --- a/coderd/httpmw/organizationparam.go +++ b/coderd/httpmw/organizationparam.go @@ -11,8 +11,10 @@ import ( "github.com/coder/coder/codersdk" ) -type organizationParamContextKey struct{} -type organizationMemberParamContextKey struct{} +type ( + organizationParamContextKey struct{} + organizationMemberParamContextKey struct{} +) // OrganizationParam returns the organization from the ExtractOrganizationParam handler. func OrganizationParam(r *http.Request) database.Organization { diff --git a/coderd/httpmw/organizationparam_test.go b/coderd/httpmw/organizationparam_test.go index ce9d21457e..1e73af9898 100644 --- a/coderd/httpmw/organizationparam_test.go +++ b/coderd/httpmw/organizationparam_test.go @@ -21,9 +21,7 @@ func TestOrganizationParam(t *testing.T) { t.Parallel() setupAuthentication := func(db database.Store) (*http.Request, database.User) { - var ( - r = httptest.NewRequest("GET", "/", nil) - ) + r := httptest.NewRequest("GET", "/", nil) user := dbgen.User(t, db, database.User{ ID: uuid.New(), diff --git a/coderd/insights_test.go b/coderd/insights_test.go index 8eec448b62..7c2525c461 100644 --- a/coderd/insights_test.go +++ b/coderd/insights_test.go @@ -97,7 +97,6 @@ func TestDeploymentInsights(t *testing.T) { wantDAUs := &codersdk.DeploymentDAUsResponse{ Entries: []codersdk.DAUEntry{ { - Date: time.Now().UTC().Truncate(time.Hour * 24), Amount: 1, }, diff --git a/coderd/metricscache/metricscache.go b/coderd/metricscache/metricscache.go index 826c1dad3e..edf0512c6b 100644 --- a/coderd/metricscache/metricscache.go +++ b/coderd/metricscache/metricscache.go @@ -187,7 +187,6 @@ func (c *Cache) refresh(ctx context.Context) error { Valid: true, }, }) - if err != nil { return err } diff --git a/coderd/provisionerdserver/provisionerdserver.go b/coderd/provisionerdserver/provisionerdserver.go index 68f3fab3b8..d740d325a1 100644 --- a/coderd/provisionerdserver/provisionerdserver.go +++ b/coderd/provisionerdserver/provisionerdserver.go @@ -474,7 +474,7 @@ func (server *Server) UpdateJob(ctx context.Context, request *proto.UpdateJobReq for _, templateVariable := range request.TemplateVariables { server.Logger.Debug(ctx, "insert template variable", slog.F("template_version_id", templateVersion.ID), slog.F("template_variable", redactTemplateVariable(templateVariable))) - var value = templateVariable.DefaultValue + value := templateVariable.DefaultValue for _, v := range request.UserVariableValues { if v.Name == templateVariable.Name { value = v.Value @@ -1379,7 +1379,7 @@ func ProvisionerJobLogsNotifyChannel(jobID uuid.UUID) string { func asVariableValues(templateVariables []database.TemplateVersionVariable) []*sdkproto.VariableValue { var apiVariableValues []*sdkproto.VariableValue for _, v := range templateVariables { - var value = v.Value + value := v.Value if value == "" && v.DefaultValue != "" { value = v.DefaultValue } diff --git a/coderd/rbac/authz_test.go b/coderd/rbac/authz_test.go index 8d024b5508..381319176a 100644 --- a/coderd/rbac/authz_test.go +++ b/coderd/rbac/authz_test.go @@ -118,7 +118,7 @@ func BenchmarkRBACAuthorize(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { allowed := authorizer.Authorize(context.Background(), c.Actor, rbac.ActionRead, objects[b.N%len(objects)]) - var _ = allowed + _ = allowed } }) } @@ -170,7 +170,7 @@ func BenchmarkRBACAuthorizeGroups(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { allowed := authorizer.Authorize(context.Background(), c.Actor, neverMatchAction, objects[b.N%len(objects)]) - var _ = allowed + _ = allowed } }) } @@ -206,7 +206,7 @@ func BenchmarkRBACFilter(b *testing.B) { b.ResetTimer() allowed, err := rbac.Filter(context.Background(), authorizer, c.Actor, rbac.ActionRead, objects) require.NoError(b, err) - var _ = allowed + _ = allowed }) } } diff --git a/coderd/rbac/builtin.go b/coderd/rbac/builtin.go index dedac6a3fb..a4cacd2208 100644 --- a/coderd/rbac/builtin.go +++ b/coderd/rbac/builtin.go @@ -62,188 +62,185 @@ func RoleOrgMember(organizationID uuid.UUID) string { return roleName(orgMember, organizationID.String()) } -var ( - // builtInRoles are just a hard coded set for now. Ideally we store these in - // the database. Right now they are functions because the org id should scope - // certain roles. When we store them in the database, each organization should - // create the roles that are assignable in the org. This isn't a hard problem to solve, - // it's just easier as a function right now. - // - // This map will be replaced by database storage defined by this ticket. - // https://github.com/coder/coder/issues/1194 - builtInRoles = map[string]func(orgID string) Role{ - // admin grants all actions to all resources. - owner: func(_ string) Role { - return Role{ - Name: owner, - DisplayName: "Owner", - Site: Permissions(map[string][]Action{ - ResourceWildcard.Type: {WildcardSymbol}, - }), - Org: map[string][]Permission{}, - User: []Permission{}, - } - }, +// builtInRoles are just a hard coded set for now. Ideally we store these in +// the database. Right now they are functions because the org id should scope +// certain roles. When we store them in the database, each organization should +// create the roles that are assignable in the org. This isn't a hard problem to solve, +// it's just easier as a function right now. +// +// This map will be replaced by database storage defined by this ticket. +// https://github.com/coder/coder/issues/1194 +var builtInRoles = map[string]func(orgID string) Role{ + // admin grants all actions to all resources. + owner: func(_ string) Role { + return Role{ + Name: owner, + DisplayName: "Owner", + Site: Permissions(map[string][]Action{ + ResourceWildcard.Type: {WildcardSymbol}, + }), + Org: map[string][]Permission{}, + User: []Permission{}, + } + }, - // member grants all actions to all resources owned by the user - member: func(_ string) Role { - return Role{ - Name: member, - DisplayName: "", - Site: Permissions(map[string][]Action{ - // All users can read all other users and know they exist. - ResourceUser.Type: {ActionRead}, - ResourceRoleAssignment.Type: {ActionRead}, - // All users can see the provisioner daemons. - ResourceProvisionerDaemon.Type: {ActionRead}, - }), - Org: map[string][]Permission{}, - User: Permissions(map[string][]Action{ - ResourceWildcard.Type: {WildcardSymbol}, - }), - } - }, + // member grants all actions to all resources owned by the user + member: func(_ string) Role { + return Role{ + Name: member, + DisplayName: "", + Site: Permissions(map[string][]Action{ + // All users can read all other users and know they exist. + ResourceUser.Type: {ActionRead}, + ResourceRoleAssignment.Type: {ActionRead}, + // All users can see the provisioner daemons. + ResourceProvisionerDaemon.Type: {ActionRead}, + }), + Org: map[string][]Permission{}, + User: Permissions(map[string][]Action{ + ResourceWildcard.Type: {WildcardSymbol}, + }), + } + }, - // auditor provides all permissions required to effectively read and understand - // audit log events. - // TODO: Finish the auditor as we add resources. - auditor: func(_ string) Role { - return Role{ - Name: auditor, - DisplayName: "Auditor", - Site: Permissions(map[string][]Action{ - // Should be able to read all template details, even in orgs they - // are not in. - ResourceTemplate.Type: {ActionRead}, - ResourceAuditLog.Type: {ActionRead}, - }), - Org: map[string][]Permission{}, - User: []Permission{}, - } - }, + // auditor provides all permissions required to effectively read and understand + // audit log events. + // TODO: Finish the auditor as we add resources. + auditor: func(_ string) Role { + return Role{ + Name: auditor, + DisplayName: "Auditor", + Site: Permissions(map[string][]Action{ + // Should be able to read all template details, even in orgs they + // are not in. + ResourceTemplate.Type: {ActionRead}, + ResourceAuditLog.Type: {ActionRead}, + }), + Org: map[string][]Permission{}, + User: []Permission{}, + } + }, - templateAdmin: func(_ string) Role { - return Role{ - Name: templateAdmin, - DisplayName: "Template Admin", - Site: Permissions(map[string][]Action{ - ResourceTemplate.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, - // CRUD all files, even those they did not upload. - ResourceFile.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, - ResourceWorkspace.Type: {ActionRead}, - // CRUD to provisioner daemons for now. - ResourceProvisionerDaemon.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, - // Needs to read all organizations since - ResourceOrganization.Type: {ActionRead}, - }), - Org: map[string][]Permission{}, - User: []Permission{}, - } - }, + templateAdmin: func(_ string) Role { + return Role{ + Name: templateAdmin, + DisplayName: "Template Admin", + Site: Permissions(map[string][]Action{ + ResourceTemplate.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, + // CRUD all files, even those they did not upload. + ResourceFile.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, + ResourceWorkspace.Type: {ActionRead}, + // CRUD to provisioner daemons for now. + ResourceProvisionerDaemon.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, + // Needs to read all organizations since + ResourceOrganization.Type: {ActionRead}, + }), + Org: map[string][]Permission{}, + User: []Permission{}, + } + }, - userAdmin: func(_ string) Role { - return Role{ - Name: userAdmin, - DisplayName: "User Admin", - Site: Permissions(map[string][]Action{ - ResourceRoleAssignment.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, - ResourceUser.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, - // Full perms to manage org members - ResourceOrganizationMember.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, - ResourceGroup.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, - }), - Org: map[string][]Permission{}, - User: []Permission{}, - } - }, + userAdmin: func(_ string) Role { + return Role{ + Name: userAdmin, + DisplayName: "User Admin", + Site: Permissions(map[string][]Action{ + ResourceRoleAssignment.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, + ResourceUser.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, + // Full perms to manage org members + ResourceOrganizationMember.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, + ResourceGroup.Type: {ActionCreate, ActionRead, ActionUpdate, ActionDelete}, + }), + Org: map[string][]Permission{}, + User: []Permission{}, + } + }, - // orgAdmin returns a role with all actions allows in a given - // organization scope. - orgAdmin: func(organizationID string) Role { - return Role{ - Name: roleName(orgAdmin, organizationID), - DisplayName: "Organization Admin", - Site: []Permission{}, - Org: map[string][]Permission{ - organizationID: { - { - Negate: false, - ResourceType: "*", - Action: "*", - }, + // orgAdmin returns a role with all actions allows in a given + // organization scope. + orgAdmin: func(organizationID string) Role { + return Role{ + Name: roleName(orgAdmin, organizationID), + DisplayName: "Organization Admin", + Site: []Permission{}, + Org: map[string][]Permission{ + organizationID: { + { + Negate: false, + ResourceType: "*", + Action: "*", }, }, - User: []Permission{}, - } - }, + }, + User: []Permission{}, + } + }, - // orgMember has an empty set of permissions, this just implies their membership - // in an organization. - orgMember: func(organizationID string) Role { - return Role{ - Name: roleName(orgMember, organizationID), - DisplayName: "", - Site: []Permission{}, - Org: map[string][]Permission{ - organizationID: { - { - // All org members can read the other members in their org. - ResourceType: ResourceOrganizationMember.Type, - Action: ActionRead, - }, - { - // All org members can read the organization - ResourceType: ResourceOrganization.Type, - Action: ActionRead, - }, - { - // Can read available roles. - ResourceType: ResourceOrgRoleAssignment.Type, - Action: ActionRead, - }, - { - ResourceType: ResourceGroup.Type, - Action: ActionRead, - }, + // orgMember has an empty set of permissions, this just implies their membership + // in an organization. + orgMember: func(organizationID string) Role { + return Role{ + Name: roleName(orgMember, organizationID), + DisplayName: "", + Site: []Permission{}, + Org: map[string][]Permission{ + organizationID: { + { + // All org members can read the other members in their org. + ResourceType: ResourceOrganizationMember.Type, + Action: ActionRead, + }, + { + // All org members can read the organization + ResourceType: ResourceOrganization.Type, + Action: ActionRead, + }, + { + // Can read available roles. + ResourceType: ResourceOrgRoleAssignment.Type, + Action: ActionRead, + }, + { + ResourceType: ResourceGroup.Type, + Action: ActionRead, }, }, - User: []Permission{}, - } - }, - } -) + }, + User: []Permission{}, + } + }, +} -var ( - // assignRoles is a map of roles that can be assigned if a user has a given - // role. - // The first key is the actor role, the second is the roles they can assign. - // map[actor_role][assign_role] - assignRoles = map[string]map[string]bool{ - "system": { - owner: true, - member: true, - orgAdmin: true, - orgMember: true, - }, - owner: { - owner: true, - auditor: true, - member: true, - orgAdmin: true, - orgMember: true, - templateAdmin: true, - userAdmin: true, - }, - userAdmin: { - member: true, - orgMember: true, - }, - orgAdmin: { - orgAdmin: true, - orgMember: true, - }, - } -) +// assignRoles is a map of roles that can be assigned if a user has a given +// role. +// The first key is the actor role, the second is the roles they can assign. +// +// map[actor_role][assign_role] +var assignRoles = map[string]map[string]bool{ + "system": { + owner: true, + member: true, + orgAdmin: true, + orgMember: true, + }, + owner: { + owner: true, + auditor: true, + member: true, + orgAdmin: true, + orgMember: true, + templateAdmin: true, + userAdmin: true, + }, + userAdmin: { + member: true, + orgMember: true, + }, + orgAdmin: { + orgAdmin: true, + orgMember: true, + }, +} // CanAssignRole is a helper function that returns true if the user can assign // the specified role. This also can be used for removing a role. diff --git a/coderd/rbac/partial.go b/coderd/rbac/partial.go index cde201cd02..2ce286b31d 100644 --- a/coderd/rbac/partial.go +++ b/coderd/rbac/partial.go @@ -141,7 +141,6 @@ func (a RegoAuthorizer) newPartialAuthorizer(ctx context.Context, subject Subjec } partialQueries, err := a.partialQuery.Partial(ctx, rego.EvalParsedInput(input)) - if err != nil { return nil, xerrors.Errorf("prepare: %w", err) } diff --git a/coderd/rbac/regosql/acl_group_var.go b/coderd/rbac/regosql/acl_group_var.go index f15a520b8d..d695683a72 100644 --- a/coderd/rbac/regosql/acl_group_var.go +++ b/coderd/rbac/regosql/acl_group_var.go @@ -10,8 +10,10 @@ import ( "github.com/coder/coder/coderd/rbac/regosql/sqltypes" ) -var _ sqltypes.VariableMatcher = ACLGroupVar{} -var _ sqltypes.Node = ACLGroupVar{} +var ( + _ sqltypes.VariableMatcher = ACLGroupVar{} + _ sqltypes.Node = ACLGroupVar{} +) // ACLGroupVar is a variable matcher that handles group_acl and user_acl. // The sql type is a jsonb object with the following structure: diff --git a/coderd/rbac/regosql/sqltypes/always_false.go b/coderd/rbac/regosql/sqltypes/always_false.go index 7555805050..93831d844c 100644 --- a/coderd/rbac/regosql/sqltypes/always_false.go +++ b/coderd/rbac/regosql/sqltypes/always_false.go @@ -4,8 +4,10 @@ import ( "github.com/open-policy-agent/opa/ast" ) -var _ Node = alwaysFalse{} -var _ VariableMatcher = alwaysFalse{} +var ( + _ Node = alwaysFalse{} + _ VariableMatcher = alwaysFalse{} +) type alwaysFalse struct { Matcher VariableMatcher @@ -30,6 +32,7 @@ func AlwaysFalseNode(n Node) Node { // UseAs uses a type no one supports to always override with false. func (alwaysFalse) UseAs() Node { return alwaysFalse{} } + func (f alwaysFalse) ConvertVariable(rego ast.Ref) (Node, bool) { if f.Matcher != nil { n, ok := f.Matcher.ConvertVariable(rego) diff --git a/coderd/rbac/regosql/sqltypes/equality.go b/coderd/rbac/regosql/sqltypes/equality.go index 84134123a8..dc3f0914fb 100644 --- a/coderd/rbac/regosql/sqltypes/equality.go +++ b/coderd/rbac/regosql/sqltypes/equality.go @@ -15,9 +15,11 @@ type SupportsEquality interface { EqualsSQLString(cfg *SQLGenerator, not bool, other Node) (string, error) } -var _ BooleanNode = equality{} -var _ Node = equality{} -var _ SupportsEquality = equality{} +var ( + _ BooleanNode = equality{} + _ Node = equality{} + _ SupportsEquality = equality{} +) type equality struct { Left Node diff --git a/coderd/rbac/regosql/sqltypes/member.go b/coderd/rbac/regosql/sqltypes/member.go index 7f022eb2a8..95940a95a2 100644 --- a/coderd/rbac/regosql/sqltypes/member.go +++ b/coderd/rbac/regosql/sqltypes/member.go @@ -16,9 +16,11 @@ type SupportsContainedIn interface { ContainedInSQL(cfg *SQLGenerator, other Node) (string, error) } -var _ BooleanNode = memberOf{} -var _ Node = memberOf{} -var _ SupportsEquality = memberOf{} +var ( + _ BooleanNode = memberOf{} + _ Node = memberOf{} + _ SupportsEquality = memberOf{} +) type memberOf struct { Needle Node diff --git a/coderd/rbac/regosql/sqltypes/variable.go b/coderd/rbac/regosql/sqltypes/variable.go index 573dedb52f..ed7264d595 100644 --- a/coderd/rbac/regosql/sqltypes/variable.go +++ b/coderd/rbac/regosql/sqltypes/variable.go @@ -68,8 +68,10 @@ func RegoVarPath(path []string, terms []*ast.Term) ([]*ast.Term, error) { return terms[len(path):], nil } -var _ VariableMatcher = astStringVar{} -var _ Node = astStringVar{} +var ( + _ VariableMatcher = astStringVar{} + _ Node = astStringVar{} +) // astStringVar is any variable that represents a string. type astStringVar struct { diff --git a/coderd/templates_test.go b/coderd/templates_test.go index 482bef10cd..498c44ffac 100644 --- a/coderd/templates_test.go +++ b/coderd/templates_test.go @@ -551,7 +551,6 @@ func TestTemplateMetrics(t *testing.T) { wantDAUs := &codersdk.TemplateDAUsResponse{ Entries: []codersdk.DAUEntry{ { - Date: time.Now().UTC().Truncate(time.Hour * 24), Amount: 1, }, diff --git a/coderd/templateversions.go b/coderd/templateversions.go index ff60c576b9..04d7e25070 100644 --- a/coderd/templateversions.go +++ b/coderd/templateversions.go @@ -948,7 +948,6 @@ func (api *API) previousTemplateVersionByOrganizationTemplateAndName(rw http.Res Name: templateVersionName, TemplateID: templateVersion.TemplateID, }) - if err != nil { if xerrors.Is(err, sql.ErrNoRows) { httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{ diff --git a/coderd/tracing/httpmw_test.go b/coderd/tracing/httpmw_test.go index dbd9bdfe83..052544fdc7 100644 --- a/coderd/tracing/httpmw_test.go +++ b/coderd/tracing/httpmw_test.go @@ -21,8 +21,10 @@ type fakeTracer struct { startCalled int64 } -var _ trace.TracerProvider = &fakeTracer{} -var _ trace.Tracer = &fakeTracer{} +var ( + _ trace.TracerProvider = &fakeTracer{} + _ trace.Tracer = &fakeTracer{} +) // Tracer implements trace.TracerProvider. func (f *fakeTracer) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer { diff --git a/coderd/tracing/status_writer.go b/coderd/tracing/status_writer.go index 07a8d1389c..6f80ee4b1f 100644 --- a/coderd/tracing/status_writer.go +++ b/coderd/tracing/status_writer.go @@ -8,8 +8,10 @@ import ( "golang.org/x/xerrors" ) -var _ http.ResponseWriter = (*StatusWriter)(nil) -var _ http.Hijacker = (*StatusWriter)(nil) +var ( + _ http.ResponseWriter = (*StatusWriter)(nil) + _ http.Hijacker = (*StatusWriter)(nil) +) // StatusWriter intercepts the status of the request and the response body up // to maxBodySize if Status >= 400. It is guaranteed to be the ResponseWriter diff --git a/coderd/tracing/status_writer_test.go b/coderd/tracing/status_writer_test.go index 8668653d8f..4cc3e5507d 100644 --- a/coderd/tracing/status_writer_test.go +++ b/coderd/tracing/status_writer_test.go @@ -108,9 +108,7 @@ func TestStatusWriter(t *testing.T) { t.Run("Hijack", func(t *testing.T) { t.Parallel() - var ( - rec = httptest.NewRecorder() - ) + rec := httptest.NewRecorder() w := &tracing.StatusWriter{ResponseWriter: hijacker{rec}} diff --git a/coderd/util/tz/tz_darwin.go b/coderd/util/tz/tz_darwin.go index 88ed56f785..00250cb97b 100644 --- a/coderd/util/tz/tz_darwin.go +++ b/coderd/util/tz/tz_darwin.go @@ -10,8 +10,10 @@ import ( "golang.org/x/xerrors" ) -const etcLocaltime = "/etc/localtime" -const zoneInfoPath = "/var/db/timezone/zoneinfo/" +const ( + etcLocaltime = "/etc/localtime" + zoneInfoPath = "/var/db/timezone/zoneinfo/" +) // TimezoneIANA attempts to determine the local timezone in IANA format. // If the TZ environment variable is set, this is used. diff --git a/coderd/util/tz/tz_linux.go b/coderd/util/tz/tz_linux.go index 0f4d0d7c73..f35febfbd3 100644 --- a/coderd/util/tz/tz_linux.go +++ b/coderd/util/tz/tz_linux.go @@ -10,8 +10,10 @@ import ( "golang.org/x/xerrors" ) -const etcLocaltime = "/etc/localtime" -const zoneInfoPath = "/usr/share/zoneinfo" +const ( + etcLocaltime = "/etc/localtime" + zoneInfoPath = "/usr/share/zoneinfo" +) // TimezoneIANA attempts to determine the local timezone in IANA format. // If the TZ environment variable is set, this is used. diff --git a/coderd/workspaceagents_test.go b/coderd/workspaceagents_test.go index 3fe824f040..f367307e22 100644 --- a/coderd/workspaceagents_test.go +++ b/coderd/workspaceagents_test.go @@ -607,14 +607,12 @@ func TestWorkspaceAgentListeningPorts(t *testing.T) { res, err := client.WorkspaceAgentListeningPorts(ctx, agentID) require.NoError(t, err) - var ( - expected = map[uint16]bool{ - // expect the listener we made - lPort: false, - // expect the coderdtest server - coderdPort: false, - } - ) + expected := map[uint16]bool{ + // expect the listener we made + lPort: false, + // expect the coderdtest server + coderdPort: false, + } for _, port := range res.Ports { if port.Network == "tcp" { if val, ok := expected[port.Port]; ok { diff --git a/coderd/workspacebuilds.go b/coderd/workspacebuilds.go index 2e3757cdd1..26176f5a0c 100644 --- a/coderd/workspacebuilds.go +++ b/coderd/workspacebuilds.go @@ -1206,7 +1206,7 @@ func convertWorkspaceStatus(jobStatus codersdk.ProvisionerJobStatus, transition } func convertWorkspaceBuildParameters(parameters []database.WorkspaceBuildParameter) []codersdk.WorkspaceBuildParameter { - var apiParameters = make([]codersdk.WorkspaceBuildParameter, 0, len(parameters)) + apiParameters := make([]codersdk.WorkspaceBuildParameter, 0, len(parameters)) for _, p := range parameters { apiParameter := codersdk.WorkspaceBuildParameter{ diff --git a/coderd/workspacebuilds_test.go b/coderd/workspacebuilds_test.go index 90d057ea4b..9048975533 100644 --- a/coderd/workspacebuilds_test.go +++ b/coderd/workspacebuilds_test.go @@ -668,7 +668,8 @@ func TestWorkspaceBuildWithRichParameters(t *testing.T) { }, }, }, - }}, + }, + }, ProvisionApply: []*proto.Provision_Response{{ Type: &proto.Provision_Response_Complete{ Complete: &proto.Provision_Complete{}, @@ -810,7 +811,8 @@ func TestWorkspaceBuildValidateRichParameters(t *testing.T) { Parameters: richParameters, }, }, - }}, + }, + }, ProvisionApply: []*proto.Provision_Response{ { Type: &proto.Provision_Response_Complete{ diff --git a/coderd/workspaces_test.go b/coderd/workspaces_test.go index d059b7dd12..2b1c7dfe84 100644 --- a/coderd/workspaces_test.go +++ b/coderd/workspaces_test.go @@ -127,7 +127,7 @@ func TestWorkspace(t *testing.T) { const templateIcon = "/img/icon.svg" const templateDisplayName = "This is template" - var templateAllowUserCancelWorkspaceJobs = false + templateAllowUserCancelWorkspaceJobs := false template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID, func(ctr *codersdk.CreateTemplateRequest) { ctr.Icon = templateIcon ctr.DisplayName = templateDisplayName @@ -1835,7 +1835,8 @@ func TestWorkspaceWithRichParameters(t *testing.T) { }, }, }, - }}, + }, + }, ProvisionApply: []*proto.Provision_Response{{ Type: &proto.Provision_Response_Complete{ Complete: &proto.Provision_Complete{}, diff --git a/codersdk/apikey.go b/codersdk/apikey.go index c4611576ed..399ff41a0d 100644 --- a/codersdk/apikey.go +++ b/codersdk/apikey.go @@ -96,7 +96,7 @@ func (c *Client) Tokens(ctx context.Context, userID string) ([]APIKey, error) { if res.StatusCode > http.StatusOK { return nil, ReadBodyAsError(res) } - var apiKey = []APIKey{} + apiKey := []APIKey{} return apiKey, json.NewDecoder(res.Body).Decode(&apiKey) } diff --git a/codersdk/deployment.go b/codersdk/deployment.go index 76182f2925..69bb6b6b3f 100644 --- a/codersdk/deployment.go +++ b/codersdk/deployment.go @@ -432,13 +432,11 @@ const ( // ExperimentExample Experiment = "example" ) -var ( - // ExperimentsAll should include all experiments that are safe for - // users to opt-in to via --experimental='*'. - // Experiments that are not ready for consumption by all users should - // not be included here and will be essentially hidden. - ExperimentsAll = Experiments{ExperimentTemplateEditor} -) +// ExperimentsAll should include all experiments that are safe for +// users to opt-in to via --experimental='*'. +// Experiments that are not ready for consumption by all users should +// not be included here and will be essentially hidden. +var ExperimentsAll = Experiments{ExperimentTemplateEditor} // Experiments is a list of experiments that are enabled for the deployment. // Multiple experiments may be enabled at the same time. diff --git a/codersdk/organizations.go b/codersdk/organizations.go index 88c4d20438..5427b93e20 100644 --- a/codersdk/organizations.go +++ b/codersdk/organizations.go @@ -165,7 +165,6 @@ func (c *Client) TemplateVersionByOrganizationAndName(ctx context.Context, organ fmt.Sprintf("/api/v2/organizations/%s/templates/%s/versions/%s", organizationID.String(), templateName, versionName), nil, ) - if err != nil { return TemplateVersion{}, xerrors.Errorf("execute request: %w", err) } diff --git a/codersdk/templates.go b/codersdk/templates.go index 3ee517a041..fed87a08ce 100644 --- a/codersdk/templates.go +++ b/codersdk/templates.go @@ -39,10 +39,12 @@ type TransitionStats struct { P95 *int64 `example:"146"` } -type TemplateBuildTimeStats map[WorkspaceTransition]TransitionStats -type UpdateActiveTemplateVersion struct { - ID uuid.UUID `json:"id" validate:"required" format:"uuid"` -} +type ( + TemplateBuildTimeStats map[WorkspaceTransition]TransitionStats + UpdateActiveTemplateVersion struct { + ID uuid.UUID `json:"id" validate:"required" format:"uuid"` + } +) type TemplateRole string @@ -236,8 +238,7 @@ func (c *Client) TemplateDAUs(ctx context.Context, templateID uuid.UUID) (*Templ // AgentStatsReportRequest is a WebSocket request by coderd // to the agent for stats. // @typescript-ignore AgentStatsReportRequest -type AgentStatsReportRequest struct { -} +type AgentStatsReportRequest struct{} // AgentStatsReportResponse is returned for each report // request by the agent. diff --git a/cryptorand/errors_test.go b/cryptorand/errors_test.go index ab0fabdd1e..c201322cc5 100644 --- a/cryptorand/errors_test.go +++ b/cryptorand/errors_test.go @@ -18,7 +18,7 @@ import ( // //nolint:paralleltest func TestRandError(t *testing.T) { - var origReader = rand.Reader + origReader := rand.Reader t.Cleanup(func() { rand.Reader = origReader }) diff --git a/enterprise/audit/audit_test.go b/enterprise/audit/audit_test.go index a4f76f2ec4..06c2514323 100644 --- a/enterprise/audit/audit_test.go +++ b/enterprise/audit/audit_test.go @@ -15,7 +15,7 @@ import ( func TestAuditor(t *testing.T) { t.Parallel() - var tests = []struct { + tests := []struct { name string filterDecision audit.FilterDecision filterError error diff --git a/enterprise/audit/diff.go b/enterprise/audit/diff.go index afa6d88f49..5542ebd2a9 100644 --- a/enterprise/audit/diff.go +++ b/enterprise/audit/diff.go @@ -47,9 +47,7 @@ func diffValues(left, right any, table Table) audit.Map { rightI = rightF.Interface() ) - var ( - diffName = field.FieldType.Tag.Get("json") - ) + diffName := field.FieldType.Tag.Get("json") atype, ok := diffKey[diffName] if !ok { diff --git a/enterprise/cli/groupcreate.go b/enterprise/cli/groupcreate.go index 1a48d4af08..361df238fd 100644 --- a/enterprise/cli/groupcreate.go +++ b/enterprise/cli/groupcreate.go @@ -13,17 +13,13 @@ import ( ) func groupCreate() *cobra.Command { - var ( - avatarURL string - ) + var avatarURL string cmd := &cobra.Command{ Use: "create ", Short: "Create a user group", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - var ( - ctx = cmd.Context() - ) + ctx := cmd.Context() client, err := agpl.CreateClient(cmd) if err != nil { diff --git a/enterprise/cli/groupedit_test.go b/enterprise/cli/groupedit_test.go index 17342e4494..61e06af8ba 100644 --- a/enterprise/cli/groupedit_test.go +++ b/enterprise/cli/groupedit_test.go @@ -49,9 +49,7 @@ func TestGroupEdit(t *testing.T) { }) require.NoError(t, err) - var ( - expectedName = "beta" - ) + expectedName := "beta" cmd, root := clitest.NewWithSubcommands(t, cli.EnterpriseSubcommands(), "groups", "edit", group.Name, diff --git a/enterprise/cli/grouplist.go b/enterprise/cli/grouplist.go index 5b8c8cd036..d3560b8181 100644 --- a/enterprise/cli/grouplist.go +++ b/enterprise/cli/grouplist.go @@ -24,9 +24,7 @@ func groupList() *cobra.Command { Short: "List user groups", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - var ( - ctx = cmd.Context() - ) + ctx := cmd.Context() client, err := agpl.CreateClient(cmd) if err != nil { diff --git a/enterprise/cli/grouplist_test.go b/enterprise/cli/grouplist_test.go index 1132925bb6..e831ee938d 100644 --- a/enterprise/cli/grouplist_test.go +++ b/enterprise/cli/grouplist_test.go @@ -67,7 +67,8 @@ func TestGroupList(t *testing.T) { err = cmd.Execute() require.NoError(t, err) - matches := []string{"NAME", "ORGANIZATION ID", "MEMBERS", " AVATAR URL", + matches := []string{ + "NAME", "ORGANIZATION ID", "MEMBERS", " AVATAR URL", group2.Name, group2.OrganizationID.String(), user2.Email, group2.AvatarURL, group1.Name, group1.OrganizationID.String(), user1.Email, group1.AvatarURL, } diff --git a/enterprise/cli/licenses_test.go b/enterprise/cli/licenses_test.go index 47617d8f91..7c78367986 100644 --- a/enterprise/cli/licenses_test.go +++ b/enterprise/cli/licenses_test.go @@ -28,8 +28,10 @@ import ( "github.com/coder/coder/testutil" ) -const fakeLicenseJWT = "test.jwt.sig" -const testWarning = "This is a test warning" +const ( + fakeLicenseJWT = "test.jwt.sig" + testWarning = "This is a test warning" +) func TestLicensesAddFake(t *testing.T) { t.Parallel() @@ -69,7 +71,7 @@ func TestLicensesAddFake(t *testing.T) { defer cancel() dir := t.TempDir() filename := filepath.Join(dir, "license.jwt") - err := os.WriteFile(filename, []byte(fakeLicenseJWT), 0600) + err := os.WriteFile(filename, []byte(fakeLicenseJWT), 0o600) require.NoError(t, err) cmd := setupFakeLicenseServerTest(t, "license", "add", "-f", filename) pty := attachPty(t, cmd) diff --git a/enterprise/replicasync/replicasync.go b/enterprise/replicasync/replicasync.go index 3dc3b3414d..57aedbc10a 100644 --- a/enterprise/replicasync/replicasync.go +++ b/enterprise/replicasync/replicasync.go @@ -21,9 +21,7 @@ import ( "github.com/coder/coder/coderd/database" ) -var ( - PubsubEvent = "replica" -) +var PubsubEvent = "replica" type Options struct { ID uuid.UUID diff --git a/examples/examples.go b/examples/examples.go index c05d2649de..28036f8e7a 100644 --- a/examples/examples.go +++ b/examples/examples.go @@ -191,7 +191,7 @@ func Archive(exampleID string) ([]byte, error) { return xerrors.Errorf("get file header: %w", err) } header.Name = strings.TrimPrefix(path, "./") - header.Mode = 0644 + header.Mode = 0o644 if entry.IsDir() { // Trailing slash on entry name is not required. Our tar @@ -199,7 +199,7 @@ func Archive(exampleID string) ([]byte, error) { // include slashes so this we don't include them here for // consistency. // header.Name += "/" - header.Mode = 0755 + header.Mode = 0o755 header.Typeflag = tar.TypeDir err = tarWriter.WriteHeader(header) if err != nil { diff --git a/provisioner/appslug.go b/provisioner/appslug.go index cf3f37942d..a13fa4eb2d 100644 --- a/provisioner/appslug.go +++ b/provisioner/appslug.go @@ -2,14 +2,12 @@ package provisioner import "regexp" -var ( - // AppSlugRegex is the regex used to validate the slug of a coder_app - // resource. It must be a valid hostname and cannot contain two consecutive - // hyphens or start/end with a hyphen. - // - // This regex is duplicated in the terraform provider code, so make sure to - // update it there as well. - // - // There are test cases for this regex in appslug_test.go. - AppSlugRegex = regexp.MustCompile(`^[a-z0-9](-?[a-z0-9])*$`) -) +// AppSlugRegex is the regex used to validate the slug of a coder_app +// resource. It must be a valid hostname and cannot contain two consecutive +// hyphens or start/end with a hyphen. +// +// This regex is duplicated in the terraform provider code, so make sure to +// update it there as well. +// +// There are test cases for this regex in appslug_test.go. +var AppSlugRegex = regexp.MustCompile(`^[a-z0-9](-?[a-z0-9])*$`) diff --git a/provisioner/echo/serve_test.go b/provisioner/echo/serve_test.go index be3d1dd503..ba548ad8aa 100644 --- a/provisioner/echo/serve_test.go +++ b/provisioner/echo/serve_test.go @@ -127,7 +127,7 @@ func unpackTar(t *testing.T, fs afero.Fs, data []byte) string { } // #nosec path := filepath.Join(directory, header.Name) - file, err := fs.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) + file, err := fs.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) require.NoError(t, err) _, err = io.CopyN(file, reader, 1<<20) require.ErrorIs(t, err, io.EOF) diff --git a/provisioner/terraform/install.go b/provisioner/terraform/install.go index 08b2796d47..64c05ae78e 100644 --- a/provisioner/terraform/install.go +++ b/provisioner/terraform/install.go @@ -29,7 +29,7 @@ var ( // Install implements a thread-safe, idempotent Terraform Install // operation. func Install(ctx context.Context, log slog.Logger, dir string, wantVersion *version.Version) (string, error) { - err := os.MkdirAll(dir, 0750) + err := os.MkdirAll(dir, 0o750) if err != nil { return "", err } diff --git a/provisioner/terraform/provision.go b/provisioner/terraform/provision.go index 0ebfd86467..7b5ad8910d 100644 --- a/provisioner/terraform/provision.go +++ b/provisioner/terraform/provision.go @@ -30,9 +30,7 @@ func (s *server) Provision(stream proto.DRPCProvisioner_ProvisionStream) error { planRequest = request.GetPlan() ) - var ( - config *proto.Provision_Config - ) + var config *proto.Provision_Config if applyRequest == nil && planRequest == nil { return nil } else if applyRequest != nil { @@ -237,22 +235,20 @@ func provisionEnv(config *proto.Provision_Config, params []*proto.ParameterValue return env, nil } -var ( - // tfEnvSafeToPrint is the set of terraform environment variables that we are quite sure won't contain secrets, - // and therefore it's ok to log their values - tfEnvSafeToPrint = map[string]bool{ - "TF_LOG": true, - "TF_LOG_PATH": true, - "TF_INPUT": true, - "TF_DATA_DIR": true, - "TF_WORKSPACE": true, - "TF_IN_AUTOMATION": true, - "TF_REGISTRY_DISCOVERY_RETRY": true, - "TF_REGISTRY_CLIENT_TIMEOUT": true, - "TF_CLI_CONFIG_FILE": true, - "TF_IGNORE": true, - } -) +// tfEnvSafeToPrint is the set of terraform environment variables that we are quite sure won't contain secrets, +// and therefore it's ok to log their values +var tfEnvSafeToPrint = map[string]bool{ + "TF_LOG": true, + "TF_LOG_PATH": true, + "TF_INPUT": true, + "TF_DATA_DIR": true, + "TF_WORKSPACE": true, + "TF_IN_AUTOMATION": true, + "TF_REGISTRY_DISCOVERY_RETRY": true, + "TF_REGISTRY_CLIENT_TIMEOUT": true, + "TF_CLI_CONFIG_FILE": true, + "TF_IGNORE": true, +} func logTerraformEnvVars(sink logSink) { env := safeEnviron() diff --git a/provisioner/terraform/provision_test.go b/provisioner/terraform/provision_test.go index 9eebb422db..0ce12b2672 100644 --- a/provisioner/terraform/provision_test.go +++ b/provisioner/terraform/provision_test.go @@ -228,7 +228,8 @@ func TestProvision(t *testing.T) { Name: "missing-variable", Files: map[string]string{ "main.tf": `variable "A" { - }`}, + }`, + }, ErrorContains: "terraform plan:", ExpectLogContains: "No value for required variable", }, @@ -401,9 +402,7 @@ func TestProvision(t *testing.T) { planRequest.GetPlan().Config.Metadata = &proto.Provision_Metadata{} } - var ( - gotExpectedLog = testCase.ExpectLogContains == "" - ) + gotExpectedLog := testCase.ExpectLogContains == "" provision := func(req *proto.Provision_Request) *proto.Provision_Complete { response, err := api.Provision(ctx) diff --git a/provisioner/terraform/serve_internal_test.go b/provisioner/terraform/serve_internal_test.go index 021bb4a950..81273d64ac 100644 --- a/provisioner/terraform/serve_internal_test.go +++ b/provisioner/terraform/serve_internal_test.go @@ -72,7 +72,7 @@ func Test_absoluteBinaryPath(t *testing.T) { err := os.WriteFile( filepath.Join(tempDir, "terraform"), []byte(terraformBinaryOutput), - 0770, + 0o770, ) require.NoError(t, err) diff --git a/provisionerd/runner/runner.go b/provisionerd/runner/runner.go index be9ad47387..8b41894805 100644 --- a/provisionerd/runner/runner.go +++ b/provisionerd/runner/runner.go @@ -33,9 +33,7 @@ const ( MissingParameterErrorText = "missing parameter" ) -var ( - errUpdateSkipped = xerrors.New("update skipped; job complete or failed") -) +var errUpdateSkipped = xerrors.New("update skipped; job complete or failed") type Runner struct { tracer trace.Tracer @@ -345,7 +343,7 @@ func (r *Runner) do(ctx context.Context) (*proto.CompletedJob, *proto.FailedJob) ctx, span := r.startTrace(ctx, tracing.FuncName()) defer span.End() - err := r.filesystem.MkdirAll(r.workDirectory, 0700) + err := r.filesystem.MkdirAll(r.workDirectory, 0o700) if err != nil { return nil, r.failedJobf("create work directory %q: %s", r.workDirectory, err) } @@ -380,7 +378,7 @@ func (r *Runner) do(ctx context.Context) (*proto.CompletedJob, *proto.FailedJob) } mode := header.FileInfo().Mode() if mode == 0 { - mode = 0600 + mode = 0o600 } switch header.Typeflag { case tar.TypeDir: diff --git a/provisionersdk/archive.go b/provisionersdk/archive.go index 8aa0c1b46f..3cacc29153 100644 --- a/provisionersdk/archive.go +++ b/provisionersdk/archive.go @@ -137,7 +137,7 @@ func Untar(directory string, r io.Reader) error { switch header.Typeflag { case tar.TypeDir: if _, err := os.Stat(target); err != nil { - if err := os.MkdirAll(target, 0755); err != nil { + if err := os.MkdirAll(target, 0o755); err != nil { return err } } diff --git a/provisionersdk/archive_test.go b/provisionersdk/archive_test.go index 1d0b008b6a..bb7d25464d 100644 --- a/provisionersdk/archive_test.go +++ b/provisionersdk/archive_test.go @@ -63,7 +63,7 @@ func TestTar(t *testing.T) { file.Name = filepath.FromSlash(file.Name) if filepath.Base(file.Name) != file.Name { newDir = filepath.Join(newDir, filepath.Dir(file.Name)) - err := os.MkdirAll(newDir, 0755) + err := os.MkdirAll(newDir, 0o755) require.NoError(t, err) file.Name = filepath.Base(file.Name) } diff --git a/scaletest/createworkspaces/run.go b/scaletest/createworkspaces/run.go index 769c19c09b..3866457061 100644 --- a/scaletest/createworkspaces/run.go +++ b/scaletest/createworkspaces/run.go @@ -30,8 +30,10 @@ type Runner struct { workspacebuildRunner *workspacebuild.Runner } -var _ harness.Runnable = &Runner{} -var _ harness.Cleanable = &Runner{} +var ( + _ harness.Runnable = &Runner{} + _ harness.Cleanable = &Runner{} +) func NewRunner(client *codersdk.Client, cfg Config) *Runner { return &Runner{ diff --git a/scaletest/workspacebuild/run.go b/scaletest/workspacebuild/run.go index ebe3df17c1..49735905d6 100644 --- a/scaletest/workspacebuild/run.go +++ b/scaletest/workspacebuild/run.go @@ -26,8 +26,10 @@ type Runner struct { workspaceID uuid.UUID } -var _ harness.Runnable = &Runner{} -var _ harness.Cleanable = &Runner{} +var ( + _ harness.Runnable = &Runner{} + _ harness.Cleanable = &Runner{} +) func NewRunner(client *codersdk.Client, cfg Config) *Runner { return &Runner{ diff --git a/scripts/apidocgen/postprocess/main.go b/scripts/apidocgen/postprocess/main.go index bea72a66e4..bfd21048ed 100644 --- a/scripts/apidocgen/postprocess/main.go +++ b/scripts/apidocgen/postprocess/main.go @@ -91,7 +91,7 @@ func prepareDocsDirectory() error { return xerrors.Errorf(`os.RemoveAll failed for "%s": %w`, apiPath, err) } - err = os.MkdirAll(apiPath, 0755) + err = os.MkdirAll(apiPath, 0o755) if err != nil { return xerrors.Errorf(`os.MkdirAll failed for "%s": %w`, apiPath, err) } @@ -102,7 +102,7 @@ func writeDocs(sections [][]byte) error { log.Println("Write docs to destination") apiDir := path.Join(docsDirectory, apiSubdir) - err := os.WriteFile(path.Join(apiDir, apiIndexFile), []byte(apiIndexContent), 0644) // #nosec + err := os.WriteFile(path.Join(apiDir, apiIndexFile), []byte(apiIndexContent), 0o644) // #nosec if err != nil { return xerrors.Errorf(`can't write the index file: %w`, err) } @@ -123,7 +123,7 @@ func writeDocs(sections [][]byte) error { mdFilename := toMdFilename(sectionName) docPath := path.Join(apiDir, mdFilename) - err = os.WriteFile(docPath, section, 0644) // #nosec + err = os.WriteFile(docPath, section, 0o644) // #nosec if err != nil { return xerrors.Errorf(`can't write doc file "%s": %w`, docPath, err) } @@ -196,7 +196,7 @@ func writeDocs(sections [][]byte) error { return xerrors.Errorf("json.Marshal failed: %w", err) } - err = os.WriteFile(manifestPath, manifestFile, 0644) // #nosec + err = os.WriteFile(manifestPath, manifestFile, 0o644) // #nosec if err != nil { return xerrors.Errorf("can't write manifest file: %w", err) } diff --git a/scripts/apitypings/main.go b/scripts/apitypings/main.go index 23f3e34ab6..2499608132 100644 --- a/scripts/apitypings/main.go +++ b/scripts/apitypings/main.go @@ -780,8 +780,10 @@ func (g *Generator) typescriptType(ty types.Type) (TypescriptType, error) { // only handle the empty interface for now intf := ty if intf.Empty() { - return TypescriptType{ValueType: "any", - AboveTypeLine: indentedComment("eslint-disable-next-line @typescript-eslint/no-explicit-any -- TODO explain why this is needed")}, nil + return TypescriptType{ + ValueType: "any", + AboveTypeLine: indentedComment("eslint-disable-next-line @typescript-eslint/no-explicit-any -- TODO explain why this is needed"), + }, nil } return TypescriptType{}, xerrors.New("only empty interface types are supported") case *types.TypeParam: diff --git a/scripts/apitypings/testdata/enums/enums.go b/scripts/apitypings/testdata/enums/enums.go index baf665c62d..dc153df934 100644 --- a/scripts/apitypings/testdata/enums/enums.go +++ b/scripts/apitypings/testdata/enums/enums.go @@ -1,7 +1,9 @@ package enums -type Enum string -type Enums []Enum +type ( + Enum string + Enums []Enum +) const ( EnumFoo Enum = "foo" diff --git a/scripts/auditdocgen/main.go b/scripts/auditdocgen/main.go index 378f50e984..7616580486 100644 --- a/scripts/auditdocgen/main.go +++ b/scripts/auditdocgen/main.go @@ -152,7 +152,7 @@ func updateAuditDoc(doc []byte, auditableResourcesMap AuditableResourcesMap) ([] func writeAuditDoc(doc []byte) error { // G306: Expect WriteFile permissions to be 0600 or less /* #nosec G306 */ - return os.WriteFile(auditDocFile, doc, 0644) + return os.WriteFile(auditDocFile, doc, 0o644) } func sortKeys[T any](stringMap map[string]T) []string { diff --git a/scripts/metricsdocgen/main.go b/scripts/metricsdocgen/main.go index 09fac07445..fbeb148715 100644 --- a/scripts/metricsdocgen/main.go +++ b/scripts/metricsdocgen/main.go @@ -143,7 +143,7 @@ func updatePrometheusDoc(doc []byte, metricFamilies []dto.MetricFamily) ([]byte, func writePrometheusDoc(doc []byte) error { // G306: Expect WriteFile permissions to be 0600 or less /* #nosec G306 */ - err := os.WriteFile(prometheusDocFile, doc, 0644) + err := os.WriteFile(prometheusDocFile, doc, 0o644) if err != nil { return err } diff --git a/tailnet/derpmap_test.go b/tailnet/derpmap_test.go index 91c1a88a85..71f0da1fcc 100644 --- a/tailnet/derpmap_test.go +++ b/tailnet/derpmap_test.go @@ -68,7 +68,7 @@ func TestNewDERPMap(t *testing.T) { }, }) require.NoError(t, err) - err = os.WriteFile(localPath, content, 0600) + err = os.WriteFile(localPath, content, 0o600) require.NoError(t, err) derpMap, err := tailnet.NewDERPMap(context.Background(), &tailcfg.DERPRegion{ RegionID: 2,