Compare commits

..

399 Commits

Author SHA1 Message Date
Stephen Kirby d1cd784866 chore: patch 2.14.2 (#14371)
* chore: sign the windows installer (#14353)

(cherry picked from commit 6f9b3c1592)

* chore: handle merge conflicts

* make fmt patch

---------

Co-authored-by: Kyle Carberry <kyle@coder.com>
Co-authored-by: Jaayden Halko <jaayden.halko@gmail.com>
2024-08-20 15:46:19 -05:00
Stephen Kirby db94b30b1c fix: patch known issues in 2.14.1 (#14207)
* chore: revert status code change for delete users endpoint (#14168)

Revert from https://github.com/coder/coder/pull/13870

(cherry picked from commit b80d99550a)

* chore: delete user codersdk to support status code regression (#14173)

* chore: delete user codersdk to support status code regression
* Update codersdk/users.go

Co-authored-by: Kayla Washburn-Love <mckayla@hey.com>

---------

Co-authored-by: Kayla Washburn-Love <mckayla@hey.com>
(cherry picked from commit b55a7a8b78)

* fix: add template editor to /templates/:templateName route group (#14206)

(cherry picked from commit d0feb70811)

---------

Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
Co-authored-by: Kayla Washburn-Love <mckayla@hey.com>
2024-08-07 11:56:07 -05:00
Stephen Kirby a0411a39f9 chore: bump github.com/docker/docker (#14185)
* chore: bump github.com/docker/docker

* fixup! chore: bump github.com/docker/docker

---------

Co-authored-by: Colin Adler <colin1adler@gmail.com>
2024-08-06 10:40:34 -05:00
Bruno Quaresma ae40f8a82e chore(site): fix storybook font issue (#14137) 2024-08-02 20:08:32 -03:00
Bruno Quaresma a3c45861bf chore: upgrade nodejs tooling (#14134) 2024-08-02 19:56:12 -03:00
Bruno Quaresma 500a789e05 chore(site): remove proxy menu warnings about using fragment as child (#14121) 2024-08-02 18:52:47 -03:00
Jon Ayers f3ff172979 chore: remove dependency license review (#14131)
- It's bafflingly buggy and is a source of annoyance for virtually the
  whole team.
- Will revisit if we don't have alternatives to catching invalid licenses.
2024-08-02 14:14:14 -04:00
Stephen Kirby 98202b309e version bumps (#14128) 2024-08-02 12:34:50 -05:00
Kayla Washburn-Love 166467caf0 fix: don't require organization_id in body when updating a custom role (#14102) 2024-08-02 11:25:00 -06:00
Kyle Carberry e2cec454bc fix: check for io.EOF error in derpmap to resolve flake (#14125)
See: https://github.com/coder/coder/actions/runs/10218717887/job/28275465405?pr=14045
2024-08-02 17:08:47 +00:00
Kyle Carberry 6e36082b0f chore: add github.com user id association (#14045)
* chore: add github.com user id association

This will eventually be used to show an indicator in the UI
to star the repository if you've been using Coder for a while
and have not starred the repo.

If you have, we'll never show a thing!

* gen

* Fix model query

* Fix linting

* Ignore auditing github.com user id

* Add test

* Fix gh url var name

* Update migration

* Update coderd/database/dbauthz/dbauthz.go

Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>

* Fix updating to when the token changes

* Fix migration

---------

Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
2024-08-02 12:49:36 -04:00
Bruno Quaresma 4d4d27c509 chore(site): allow pnpm packages license (#14122) 2024-08-02 13:02:22 -03:00
Marcin Tojek 6428a766a9 feat: notify when a user account is deleted (#14113) 2024-08-02 14:56:54 +02:00
Marcin Tojek 4242fd9c1b fix: wrong notification group (#14112) 2024-08-02 10:00:27 +00:00
Muhammad Atif Ali 7619d1c49a chore: skip dogfood workflow for dependabot PRs (#14111) 2024-08-02 09:32:35 +00:00
Marcin Tojek 76ce460cc4 fix: typo in notification template (#14108) 2024-08-02 11:03:11 +02:00
dependabot[bot] 83963b9e61 chore: bump github.com/moby/moby from 26.1.0+incompatible to 27.1.1+incompatible (#14042)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-02 10:24:45 +03:00
dependabot[bot] 1d9162dc2f chore: bump google.golang.org/api from 0.188.0 to 0.190.0 (#14107)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-02 09:53:57 +03:00
Muhammad Atif Ali 894020db6a chore: skip dogfood workflow for dependabot PRs (#14106) 2024-08-02 09:39:57 +03:00
dependabot[bot] 78f1cdaebe chore: bump github.com/fergusstrange/embedded-postgres from 1.27.0 to 1.28.0 (#14043)
* chore: bump github.com/fergusstrange/embedded-postgres

Bumps [github.com/fergusstrange/embedded-postgres](https://github.com/fergusstrange/embedded-postgres) from 1.27.0 to 1.28.0.
- [Release notes](https://github.com/fergusstrange/embedded-postgres/releases)
- [Commits](https://github.com/fergusstrange/embedded-postgres/compare/v1.27.0...v1.28.0)

---
updated-dependencies:
- dependency-name: github.com/fergusstrange/embedded-postgres
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* [dependabot skip] Update Nix Flake SRI Hash

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-02 09:28:34 +03:00
Kayla Washburn-Love 7125b37545 feat(site): allow selecting an organization when creating a template (#14061) 2024-08-01 18:04:21 -06:00
Steven Masley a27ac30e11 chore: add sql filter to fetching audit logs (#14070)
* chore: add sql filter to fetching audit logs
* use sqlc.embed for audit logs
* fix sql query matcher
2024-08-01 12:07:19 -05:00
dependabot[bot] d23670ad53 chore: bump github.com/open-policy-agent/opa from 0.58.0 to 0.67.0 (#14040)
* chore: bump github.com/open-policy-agent/opa from 0.58.0 to 0.67.0

Bumps [github.com/open-policy-agent/opa](https://github.com/open-policy-agent/opa) from 0.58.0 to 0.67.0.
- [Release notes](https://github.com/open-policy-agent/opa/releases)
- [Changelog](https://github.com/open-policy-agent/opa/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-policy-agent/opa/compare/v0.58.0...v0.67.0)

---
updated-dependencies:
- dependency-name: github.com/open-policy-agent/opa
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* [dependabot skip] Update Nix Flake SRI Hash

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <dependabot[bot]@users.noreply.github.com>
2024-08-01 19:41:44 +03:00
Alex Ivanov 6d3f7fb2a2 chore: update meticulous CI job (#14073) 2024-08-01 12:26:44 -04:00
Muhammad Atif Ali b0eaf4ca94 chore: commit update-flake as @dependabot (#14091)
Thıs is needed to bypass the dependency check job for dependabot PRs.

https://github.com/coder/coder/blob/1289937eaeac63f27f2856a4374a0fedc5cc0e58/.github/workflows/ci.yaml#L973

The username and email are fetched from a previous  dependabot commit. 
https://github.com/coder/coder/commit/1289937eaeac63f27f2856a4374a0fedc5cc0e58.patch
2024-08-01 19:24:51 +03:00
dependabot[bot] a88e1cc5f8 chore: bump github.com/go-chi/httprate from 0.9.0 to 0.12.0 (#14039)
* chore: bump github.com/go-chi/httprate from 0.9.0 to 0.12.0

Bumps [github.com/go-chi/httprate](https://github.com/go-chi/httprate) from 0.9.0 to 0.12.0.
- [Release notes](https://github.com/go-chi/httprate/releases)
- [Commits](https://github.com/go-chi/httprate/compare/v0.9.0...v0.12.0)

---
updated-dependencies:
- dependency-name: github.com/go-chi/httprate
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* [dependabot skip] Update Nix Flake SRI Hash

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <dependabot[bot]@users.noreply.github.com>
2024-08-01 19:22:23 +03:00
dependabot[bot] 1289937eae chore: bump alpine from 3.20.1 to 3.20.2 in /scripts (#14037)
Bumps alpine from 3.20.1 to 3.20.2.

---
updated-dependencies:
- dependency-name: alpine
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-01 18:57:37 +03:00
Ethan 956d0cb042 fix: block creating oidc users when oidc has not been configured (#14064) 2024-08-01 13:30:10 +10:00
Muhammad Atif Ali 7a4737cf76 ci: handle retriggering ci and human authors in update-flake (#14052)
Co-authored-by: Dean Sheather <dean@deansheather.com>
2024-07-31 16:12:40 +00:00
Kyle Carberry 5d42f4aa7b fix: run update-flake with PAT to allow workflow runs (#14067)
See the comment in the code.
2024-07-31 11:43:43 -04:00
Danny Kopping c3390993dd chore: update generated files after pnpm upgrade (#14036) 2024-07-31 17:23:55 +02:00
Kayla Washburn-Love bf4b7abf14 chore(coderd): allow creating workspaces without specifying an organization (#14048) 2024-07-30 10:44:02 -06:00
Kayla Washburn-Love 56dfc64bb0 fix: don't highlight inactive org in management settings sidebar (#14059) 2024-07-30 09:33:22 -06:00
Marcin Tojek cf1fcab514 feat: notify about created user account (#14010) 2024-07-30 15:37:45 +02:00
Cian Johnston c6fb779c50 chore(scaletest): update dashboard (#14054) 2024-07-30 10:47:13 +01:00
dependabot[bot] c88ea26d7c ci: bump crate-ci/typos from 1.23.2 to 1.23.5 in the github-actions group (#14038)
Bumps the github-actions group with 1 update: [crate-ci/typos](https://github.com/crate-ci/typos).


Updates `crate-ci/typos` from 1.23.2 to 1.23.5
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.23.2...v1.23.5)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-30 11:07:30 +03:00
Kyle Carberry 893169c83b fix: duplicate tags map in mutation to resolve race (#14047)
* fix: duplicate tags map in mutation to resolve race

See: https://github.com/coder/coder/actions/runs/10149619748/job/28064952716?pr=14046

* Fix deployment values race
2024-07-30 07:37:13 +00:00
Steven Masley 3209c863b8 chore: authz 'any_org' to return if at least 1 org has perms (#14009)
* chore: authz 'any_org' to return if at least 1 org has perms

Allows checking if a user can do an action in any organization,
rather than a specific one. Allows asking general questions on the
UI to determine which elements to show.

* more strict, add comments to policy
* add unit tests and extend to /authcheck api
* make field optional
2024-07-29 19:58:48 -05:00
Kyle Carberry b7102b39af chore: add script to update flake automatically (#14046) 2024-07-29 14:29:22 -04:00
Bruno Quaresma 58b810fb0a fix: fix dormancy notifications (#14029) 2024-07-29 11:20:04 -03:00
dependabot[bot] 22143d3e80 chore: bump github.com/gohugoio/hugo from 0.128.2 to 0.129.0 (#13966)
Bumps [github.com/gohugoio/hugo](https://github.com/gohugoio/hugo) from 0.128.2 to 0.129.0.
- [Release notes](https://github.com/gohugoio/hugo/releases)
- [Changelog](https://github.com/gohugoio/hugo/blob/master/hugoreleaser.toml)
- [Commits](https://github.com/gohugoio/hugo/compare/v0.128.2...v0.129.0)

---
updated-dependencies:
- dependency-name: github.com/gohugoio/hugo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-27 13:49:05 +00:00
dependabot[bot] f88a48df26 chore: bump github.com/zclconf/go-cty from 1.14.4 to 1.15.0 (#13967)
Bumps [github.com/zclconf/go-cty](https://github.com/zclconf/go-cty) from 1.14.4 to 1.15.0.
- [Release notes](https://github.com/zclconf/go-cty/releases)
- [Changelog](https://github.com/zclconf/go-cty/blob/main/CHANGELOG.md)
- [Commits](https://github.com/zclconf/go-cty/compare/v1.14.4...v1.15.0)

---
updated-dependencies:
- dependency-name: github.com/zclconf/go-cty
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-27 16:43:54 +03:00
Asher 712662d014 chore: embed audit log in deployment settings page (#14023)
* Move audit page to /deployment/audit

The existing link remains but will redirect to the new URL.
If multi-org is not enabled, nothing changes.

* Redirect organization audit page to site-wide audit page

* Always wrap audit log filters when in deployment settings

Otherwise the input is teeny tiny and barely fits a few characters.
Normally we only wrap when the screen shrinks.  Again, no change
if multi-org is not enabled.

This also makes the filter menus take up available space when
wrapping (*does* apply to non-multi-org setups as well).

* Show audit log details in a tooltip

If multi-org is not enabled, details continue to be shown inline.
2024-07-26 14:12:24 -08:00
Charlie Voiselle eacdfb9f9c fix: change time format string from 15:40 to 15:04 (#14033)
* Change string format to constant value
2024-07-26 17:57:47 -04:00
Asher d8ddce8628 chore: use latest code-server in examples (#14030)
Instead, leave a comment describing how to pin the version.  This negates
the need to continually update the version in the examples.
2024-07-26 21:53:17 +00:00
Kayla Washburn-Love d68340b125 feat: manage groups from deployment settings for single-org deployments (#14016) 2024-07-26 13:10:13 -06:00
Cian Johnston 68fa34feae ci: remove ci make concurrency to fix docker image race (#14027)
This PR removes the `-j` argument to `make` when building and pushing Docker images on merge to main.
Seen here: https://github.com/coder/coder/actions/runs/10108431095/job/27954323032#step:9:119
We ran into this previously in #13769 for the release workflow, but neglected to apply the same change to the CI workflow.
2024-07-26 10:53:18 +01:00
Cian Johnston 37a859f071 chore(testutil): add testutil.GetRandomName that does not return duplicates (#14020)
Fixes #13910

Adds testutil.GetRandomName that replaces namesgenerator.GetRandomName but instead appends a monotonically increasing integer instead of a number between 1 and 10.
2024-07-26 09:44:34 +01:00
Steven Masley 96011e1b29 fix: handle legacy licenses missing feature_set field (#14025)
* fix: legacy licenses missing feature_set field
2024-07-25 22:43:08 -05:00
Raul Salamanca 5b35f65305 docs: add proxmox coder template in list of community templates (#14022) 2024-07-26 06:05:49 +03:00
Michael Brewer ce6ee9c6c6 feat(site): add jetbrains fleet icon (#14021) 2024-07-26 06:05:08 +03:00
Garrett Delfosse 6c2336b8e9 chore: shorten provisioner key (#14017) 2024-07-25 16:08:12 -05:00
Steven Masley 7ea1a4c686 chore: protect organization endpoints with license (#14001)
* chore: move multi-org endpoints into enterprise directory

All multi-organization features are gated behind "premium" licenses. Enterprise licenses can no longer
access organization CRUD.
2024-07-25 16:07:53 -05:00
Steven Masley 915f69080a chore: fix csrf error message on empty session header (#14018)
* chore: fix csrf error message on empty session header

A more detailed error message was added to catch mismatched
session tokens. This error was mistakenly applying to all CSRF
failures.
2024-07-25 15:58:23 -05:00
Garrett Delfosse 2279441517 feat: add --key flag to provisionerd start (#14002) 2024-07-25 15:26:26 -04:00
Steven Masley c082868f55 chore: indicate premium vs enterprise on license page (#14008)
* chore: indicate premium vs enterprise on license page

Premium licenses should say "premium" instead of "enterprise"
2024-07-25 14:04:32 -05:00
Michael Smith 9f3c1c7367 fix: resolve text overflow issues for workspace empty state (#14015) 2024-07-25 18:19:57 +00:00
Kira Pilot 4eb67ad98a Revert "feat: implement multi-org template gallery (#13784)" (#14013)
This reverts commit 554c4ab1eb.
2024-07-25 13:09:04 -04:00
Kayla Washburn-Love 615bb94ec4 feat(site): embed users page in management settings (#14006) 2024-07-25 10:50:07 -06:00
Garrett Delfosse 6161d173d3 feat: add tags to provisioner keys api (#13989) 2024-07-25 15:20:45 +00:00
Garrett Delfosse ca83017dc1 feat: accept provisioner keys for provisioner auth (#13972) 2024-07-25 10:22:55 -04:00
Marcin Tojek d488853393 fix: notifications: use username in workspace URLs (#14011) 2024-07-25 12:02:24 +02:00
Muhammad Atif Ali 88bc491778 chore: add stable version info to repository-dispatch event (#13997)
Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
2024-07-25 11:03:01 +03:00
Asher e8b3db8c7a feat: add organizations filter to audit table (#13978)
* Ignore organization ID in member and role audit logs

Since the organization will never change in any resources, 
and the org is already on the top-level of the response. 

* Add organization details and filter to audit table

These only display if the multi-org experiment is enabled.

This also includes a modification to customize the width 
of the filters since with four things get a bit squishy.

* Add more audit mocks

To test different org names and no org.
2024-07-24 14:28:23 -08:00
Steven Masley 4f01372179 feat: implement disabling oidc issuer checks (#13991)
* use DANGEROUS prefix and drop a warning log
2024-07-24 16:45:47 -05:00
Muhammad Atif Ali 652827f0e8 docs: add preview image to release schedule (#13948) 2024-07-24 23:20:52 +03:00
Kayla Washburn-Love 38b573857b feat(site): edit organization member roles (#13977) 2024-07-24 11:36:45 -06:00
Steven Masley 15fda232b7 feat: implement premium vs enterprise licenses (#13907)
* feat: implement premium vs enterprise licenses

Implement different sets of licensed features.
2024-07-24 12:07:59 -05:00
Bruno Quaresma 0d9615b4fd feat(coderd): notify when workspace is marked as dormant (#13868) 2024-07-24 13:38:21 -03:00
Garrett Delfosse ccb5b4df80 chore: move provisioner keys commands into slim build (#13993) 2024-07-24 11:30:50 -04:00
Marcin Tojek b3a3671c6a fix: use static port number for prometheus test (#14000) 2024-07-24 12:54:36 +00:00
Marcin Tojek dac14fe581 test: skip TestProvisionerDaemon_PrometheusEnabled (#13996) 2024-07-24 09:28:53 +02:00
Ethan 7028ff79c3 feat(codersdk): export template variable parser (#13984) 2024-07-24 14:11:29 +10:00
Stephen Kirby 177c7d3c68 updated version for patches 2.12.5 and 2.13.2 (#13995) 2024-07-23 15:36:14 -05:00
Kayla Washburn-Love 0d453437de fix(site): select default organization on /organizations page (#13992) 2024-07-23 12:35:38 -06:00
Steven Masley a61c09e4dc fix: use correct group url in multi-org experiment (#13986)
* fix: use correct group url in multi-org experiment

When not using the experiment, default to the "default" org.
Assuming groups are all in the primary org

---------

Co-authored-by: McKayla Washburn <mckayla@hey.com>
2024-07-23 13:17:21 -05:00
Jon Ayers 3a614f1602 fix: random typos in offline docs documentation (#13979) 2024-07-23 11:48:58 -05:00
Steven Masley ecc356f5a9 chore: generate rbac resource types to typescript (#13975)
* chore: generate rbac resource types to typescript

The existing typesGenerated.ts cannot support this as the generator
only inspects the types, not the values. So traversing the value AST
would have to be added. The rbac gen is already used for the sdk,
this extends it to the typescript
2024-07-23 10:07:52 -05:00
Danny Kopping b817c863ef fix: webhook endpoint YAML attribute (#13983)
Signed-off-by: Danny Kopping <danny@coder.com>
2024-07-23 14:59:27 +00:00
Garrett Delfosse 0a07c7e554 feat: get org scoped provisioners (#13953) 2024-07-23 14:56:46 +00:00
Danny Kopping 695afb80e6 fix: address TestPendingUpdatesMetric flake 2024-07-23 14:39:57 +00:00
Marcin Tojek 966c888e9d fix: test: no parallel when starting Prometheus endpoint (#13981)
* fix: test: no parallel when starting Prometheus endpoint

* fix
2024-07-23 11:31:27 +01:00
Mathias Fredriksson 5a4dbcfc02 chore(scripts): fix cherry-pick check in check_commit_metadata.sh (#13980) 2024-07-23 06:49:29 +00:00
Asher a8e6e89f65 feat: add organization details to audit log response (#13961)
* Allow creating test audits with nil org

Not all audit entries have organization IDs, so this will allow us to
test those cases.

* Add organization details to audit log queries

* Add organization to audit log response

This replaces the old ID.  This is a breaking change but organizations
were not being used before.
2024-07-22 13:28:44 -08:00
Dean Sheather 38c7dcda94 fix: avoid vscodessh exit when server restarts (#13970)
Mitigates an issue where vscodessh would restart when the control plane
restarts, causing the entire SSH session to be reestablished.
2024-07-22 17:19:44 +00:00
Dean Sheather d2b035312e chore: fix parse typo for network telemetry (#13971) 2024-07-22 17:14:37 +00:00
Kayla Washburn-Love 0a71c34d46 feat: create and modify organization groups (#13887) 2024-07-22 09:47:14 -06:00
Steven Masley dd99457a04 chore: although unfortunate, it is possible for a user to be in no orgs (#13956) 2024-07-22 10:39:50 -05:00
Cian Johnston 005254d64a chore(examples): update sample devcontainer templates (#13796)
Updates docker and kubernetes devcontainer templates

Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
2024-07-22 14:10:02 +01:00
Stephen Kirby 3c2c5ab7fc chore(docs): add missing author to support bundle guide (#13918)
* fixed missing author

* make fmt

Signed-off-by: Cian Johnston <cian@coder.com>

---------

Signed-off-by: Cian Johnston <cian@coder.com>
Co-authored-by: Cian Johnston <cian@coder.com>
2024-07-22 09:09:31 +01:00
Nano 40b70dbdb0 docs: update caddy config example & guide (#13964) 2024-07-22 10:47:41 +03:00
Muhammad Atif Ali 88d2dbd994 docs: replace coder_git_auth with coder_external_auth (#13936) 2024-07-20 07:43:09 +03:00
Steven Masley 03c5d42233 chore: keep active users active in scim (#13955)
* chore: scim should keep active users active
* chore: add a unit test to excercise dormancy bug
* audit log should not be dropped when there is no change
* add ability to cancel audit log
2024-07-19 16:30:02 -05:00
Steven Masley 49d6d0f41b chore: add built in organization roles to match site (#13938)
* chore: add built in organization roles to match site

Added org user admin, org template admin, and org auditor
2024-07-19 15:44:18 -05:00
Muhammad Atif Ali 8beb0b131f chore: update flake.nix to handle aarch64 linux (#13930) 2024-07-19 22:15:50 +03:00
Stephen Kirby bac9b38e05 autoversion 2.12.4 and 2.13.1 (#13951) 2024-07-19 13:26:13 -05:00
Alex Ivanov dba23872eb chore: only add Meticulous recorder when running in dev mode (#13950) 2024-07-19 12:47:38 -05:00
Jaayden Halko 554c4ab1eb feat: implement multi-org template gallery (#13784)
* feat: initial changes for multi-org templates page

* feat: add TemplateCard component

* feat: add component stories

* chore: update template query naming

* fix: fix formatting

* feat: template card interaction and navigation

* fix: copy updates

* chore: update TemplateFilter type to include FilterQuery

* chore: update typesGenerated.ts

* feat: update template filter api logic

* fix: fix format

* fix: get activeOrg

* fix: add format annotation

* chore: use organization display name

* feat: client side org filtering

* fix: use org display name

* fix: add ExactName

* feat: show orgs filter only if more than 1 org

* chore: updates for PR review

* fix: fix format

* chore: add story for multi org

* fix: aggregate templates by organization id

* fix: fix format

* fix: check org count

* fix: update ExactName type
2024-07-19 10:33:08 -04:00
Marcin Tojek 40609c26e9 fix: test: do not block Prometheus port (#13945) 2024-07-19 16:29:10 +02:00
Danny Kopping c88e4162d8 fix: TestPendingUpdatesMetric flake (#13944)
Signed-off-by: Danny Kopping <danny@coder.com>
2024-07-19 12:54:15 +02:00
Danny Kopping 492ab1cc7e chore: add webhook tests for notification subsystem (#13942) 2024-07-19 12:03:29 +02:00
Danny Kopping 943ea7c52a feat: add SMTP auth & TLS support (#13902) 2024-07-19 09:22:15 +02:00
Jon Ayers 8d4bccc612 feat: add meticulous recorder (#13886) 2024-07-18 20:15:07 -05:00
Kayla Washburn-Love 4dcbd7179f fix: hardcode default organization id in DashboardProvider (#13940) 2024-07-18 16:55:38 -06:00
Steven Masley aa6e6e3d58 chore: implement fetch all organizations endpoint (#13941)
* chore: implement fetch all organizations endpoint
* update ui to use list all orgs
2024-07-18 17:28:36 -05:00
Garrett Delfosse 6f20a64f9d chore: add multi-org flag to develop.sh (#13923) 2024-07-18 14:43:07 -05:00
Garrett Delfosse f975701b34 feat: add provisioner key cli commands (#13875) 2024-07-18 14:44:20 -04:00
Marcin Tojek 91cbe679c0 chore: move notiffake to testutil (#13933) 2024-07-18 13:36:02 +00:00
Marcin Tojek fbd1d7f9a7 feat: notify on successful autoupdate (#13903) 2024-07-18 15:19:12 +02:00
Steven Masley 44924cd8d8 chore: add updated_at to codersdk users (#13928)
* chore: add updated_at to codersdk users
2024-07-17 17:59:42 -05:00
Kyle Carberry 3e1fae7d3d chore: add Star the Repo to support links (#13924) 2024-07-17 15:39:03 -04:00
Kayla Washburn-Love 80cbffe843 chore: remove organizationIds from AuthProvider (#13917) 2024-07-17 09:53:40 -06:00
Spike Curtis f21f2dce57 fix: fix heartbeat select to prevent leak (#13909)
fixes #13816
2024-07-16 23:38:07 +04:00
Spike Curtis 70c5c47efd fix: stop blocking fake Agent API channel writes after context expires (#13908) 2024-07-16 23:22:13 +04:00
Spike Curtis 1f24aceea2 fix: change audit descriptions to indicate unsuccessful attempts (#13897) 2024-07-16 22:47:32 +04:00
Kayla Washburn-Love a3f40d5ef8 feat: add members settings page for organizations (#13817) 2024-07-16 12:25:36 -06:00
Garrett Delfosse b697c6939a chore: add provisioner key crud apis (#13857) 2024-07-16 13:27:12 -04:00
Marcin Tojek a5e4bf38fe feat: notify owner about failed autobuild (#13891) 2024-07-16 10:48:17 +02:00
Cian Johnston 36454aa81b fix(dogfood/Dockerfile): create /etc/suoders.d/nopasswd instead of COPY (#13900) 2024-07-15 23:19:23 +01:00
Muhammad Atif Ali ab59460e2c chore: bump terraform to v1.9.2 (#13899) 2024-07-15 21:25:42 +00:00
Cian Johnston 17626b8dd1 Revert "fix(dogfood/Dockerfile): change ownership of /etc/sudoers.d to root (#13793)" (#13898)
This reverts commit da8911426b.
2024-07-15 21:08:48 +00:00
Colin Adler 7a34a70cb8 chore: upgrade terraform to 1.9.2 (#13895) 2024-07-15 13:27:08 -05:00
dependabot[bot] d6e2801478 chore: bump github.com/adrg/xdg from 0.4.0 to 0.5.0 (#13892)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-15 19:26:25 +03:00
dependabot[bot] 0a73ae1036 chore: bump google.golang.org/api from 0.187.0 to 0.188.0 (#13894)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-15 19:25:57 +03:00
dependabot[bot] 6058bcdad8 chore: bump cloud.google.com/go/compute/metadata from 0.4.0 to 0.5.0 (#13893)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-15 18:51:55 +03:00
dependabot[bot] bece042fa8 chore: bump @testing-library/jest-dom from 6.1.2 to 6.4.6 in /site (#13732)
Bumps [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) from 6.1.2 to 6.4.6.
- [Release notes](https://github.com/testing-library/jest-dom/releases)
- [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/jest-dom/compare/v6.1.2...v6.4.6)

---
updated-dependencies:
- dependency-name: "@testing-library/jest-dom"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-15 09:41:57 -06:00
dependabot[bot] aaf295badf ci: bump the github-actions group with 2 updates (#13890)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-15 15:56:12 +03:00
dependabot[bot] b00f746cac chore: bump monaco-editor from 0.44.0 to 0.50.0 in /site (#13835)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Muhammad Atif Ali <atif@coder.com>
2024-07-14 15:48:29 +03:00
Steven Masley 9cbe2b27e7 chore: create workspaces and templates for multiple orgs (#13866)
* chore: creating workspaces and templates to work with orgs
* handle wrong org selected
* create org member in coderdtest helper
2024-07-12 15:47:28 -05:00
Steven Masley e4aef272fa chore: add example prompt command for multiple prompt bug (#13885)
Prompt message is not erased after the prompt ends
2024-07-12 11:59:13 -05:00
Steven Masley c6b7588933 chore: add organization id to provisioner sdk type (#13883)
* chore: add organization id to provisioner sdk type
2024-07-12 10:56:34 -05:00
Danny Kopping 1691768fb9 chore: use store enqueuer with external provisioners (#13881) 2024-07-12 13:51:13 +02:00
Kayla Washburn-Love de2585b0b6 chore: use rw.WriteHeader to write responses without bodies (#13870) 2024-07-11 13:38:33 -06:00
Mathias Fredriksson fd10ea1dcc chore(scripts): add script to update list of experiments after release (#13872)
Fixes #13119
2024-07-11 21:45:50 +03:00
Steven Masley 687d9538de chore: provisioner acquirer to respect organization ID of jobs (#13874)
* test: add unit test to verify creation of templates in multiple orgs
* chore: provisioner acquirer to respect organization ID of jobs

Prior to this the wrong provisioner was awakened on any new job
posting.

* add comment and stricter check
2024-07-11 11:26:47 -05:00
Marcin Tojek bee913ac45 feat(cli): pause notifications (#13873) 2024-07-11 15:22:20 +02:00
Ethan f36b816391 chore: add coder version to network telemetry events (#13871) 2024-07-11 20:46:37 +10:00
Danny Kopping b2dab3308d feat: implement observability of notifications subsystem (#13799) 2024-07-11 10:57:49 +02:00
Colin Adler a6d66cc7ec chore: ensure correct version of golangci-lint is run in ci (#13869) 2024-07-10 14:50:38 -05:00
Eric Paulsen 90a6025e18 fix-sa-docs (#13724) 2024-07-10 18:40:45 +00:00
Muhammad Atif Ali 0787de88a9 chore: update documentation links to the new format (#13797) 2024-07-10 21:31:37 +03:00
Eric Paulsen 2a297b073a docs: fix vs code web module reference (#13785) 2024-07-10 21:29:40 +03:00
Colin Adler 2238593f57 chore: update pnpm to v9 (#13843)
* chore: update pnpm to v9

* pin golangci-lint and shfmt
2024-07-10 13:13:19 -05:00
Steven Masley a588ec5b21 chore: assign user to multiple orgs in coderdtest user create (#13867)
* chore: coderdtest assign user to multiple orgs on create
2024-07-10 12:38:48 -05:00
Steven Masley 7bb3e0db4a chore: return organization's display name and icon in templates (#13858)
* chore: templates return organization display name and icon
* templates api response includes organization display name and icon
2024-07-10 10:06:49 -05:00
Marcin Tojek bf392ffea4 feat: add killswitch for notifications (#13794) 2024-07-10 16:15:06 +02:00
Danny Kopping 542fff7df0 chore: improve notifications tests (#13863) 2024-07-10 15:25:23 +02:00
Mathias Fredriksson c8484b4fc8 fix(cli): follow logs only when agent is starting (#13864) 2024-07-10 15:39:43 +03:00
Marcin Tojek 70046ea08d fix: missing nolint comment (#13862) 2024-07-10 09:55:30 +00:00
Ethan e8db21c89e chore: add additional network telemetry stats & events (#13800) 2024-07-10 14:14:35 +10:00
dependabot[bot] 38035da846 chore: bump github.com/google/nftables (#13859) 2024-07-09 19:02:16 -04:00
Jon Ayers 464e7979c4 docs: remove mention of built-in remote desktop on the roadmap (#13459) 2024-07-09 16:29:44 -05:00
dependabot[bot] e00a80e029 chore: bump github.com/gofrs/flock from 0.8.1 to 0.12.0 (#13782)
Bumps [github.com/gofrs/flock](https://github.com/gofrs/flock) from 0.8.1 to 0.12.0.
- [Release notes](https://github.com/gofrs/flock/releases)
- [Commits](https://github.com/gofrs/flock/compare/v0.8.1...v0.12.0)

---
updated-dependencies:
- dependency-name: github.com/gofrs/flock
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 21:16:05 +00:00
dependabot[bot] d4f0a22ac6 chore: bump axios from 1.6.0 to 1.7.2 in /site (#13697)
Bumps [axios](https://github.com/axios/axios) from 1.6.0 to 1.7.2.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.6.0...v1.7.2)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 21:14:16 +00:00
dependabot[bot] f6cd002542 chore: bump yup from 1.3.2 to 1.4.0 in /site (#13715)
Bumps [yup](https://github.com/jquense/yup) from 1.3.2 to 1.4.0.
- [Release notes](https://github.com/jquense/yup/releases)
- [Changelog](https://github.com/jquense/yup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jquense/yup/compare/v1.3.2...v1.4.0)

---
updated-dependencies:
- dependency-name: yup
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 21:12:56 +00:00
dependabot[bot] d209c5ff99 chore: bump github.com/bramvdbogaerde/go-scp from 1.4.0 to 1.5.0 (#13806)
Bumps [github.com/bramvdbogaerde/go-scp](https://github.com/bramvdbogaerde/go-scp) from 1.4.0 to 1.5.0.
- [Release notes](https://github.com/bramvdbogaerde/go-scp/releases)
- [Commits](https://github.com/bramvdbogaerde/go-scp/compare/v1.4.0...v1.5.0)

---
updated-dependencies:
- dependency-name: github.com/bramvdbogaerde/go-scp
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 21:10:55 +00:00
dependabot[bot] 7574a2d3ab chore: bump github.com/gohugoio/hugo from 0.126.1 to 0.128.2 (#13811)
Bumps [github.com/gohugoio/hugo](https://github.com/gohugoio/hugo) from 0.126.1 to 0.128.2.
- [Release notes](https://github.com/gohugoio/hugo/releases)
- [Changelog](https://github.com/gohugoio/hugo/blob/master/hugoreleaser.toml)
- [Commits](https://github.com/gohugoio/hugo/compare/v0.126.1...v0.128.2)

---
updated-dependencies:
- dependency-name: github.com/gohugoio/hugo
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 16:04:51 -05:00
dependabot[bot] de1da93d04 chore: bump github.com/bgentry/speakeasy (#13729)
Bumps [github.com/bgentry/speakeasy](https://github.com/bgentry/speakeasy) from 0.1.1-0.20220910012023-760eaf8b6816 to 0.2.0.
- [Release notes](https://github.com/bgentry/speakeasy/releases)
- [Commits](https://github.com/bgentry/speakeasy/commits/v0.2.0)

---
updated-dependencies:
- dependency-name: github.com/bgentry/speakeasy
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 16:59:06 -04:00
dependabot[bot] 03a8cc7d4e chore: bump cloud.google.com/go/compute/metadata from 0.3.0 to 0.4.0 (#13808)
Bumps [cloud.google.com/go/compute/metadata](https://github.com/googleapis/google-cloud-go) from 0.3.0 to 0.4.0.
- [Release notes](https://github.com/googleapis/google-cloud-go/releases)
- [Changelog](https://github.com/googleapis/google-cloud-go/blob/main/CHANGES.md)
- [Commits](https://github.com/googleapis/google-cloud-go/compare/v0.3.0...v0.4.0)

---
updated-dependencies:
- dependency-name: cloud.google.com/go/compute/metadata
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 14:35:30 -05:00
Colin Adler d50ffa78f6 fix: exit reset password request before passwords are compared (#13856) 2024-07-09 14:28:39 -05:00
dependabot[bot] 3894ae17a7 chore: bump the mui group across 1 directory with 5 updates (#13829)
Bumps the mui group with 5 updates in the /site directory:

| Package | From | To |
| --- | --- | --- |
| [@mui/icons-material](https://github.com/mui/material-ui/tree/HEAD/packages/mui-icons-material) | `5.15.20` | `5.16.0` |
| [@mui/material](https://github.com/mui/material-ui/tree/HEAD/packages/mui-material) | `5.15.21` | `5.16.0` |
| [@mui/system](https://github.com/mui/material-ui/tree/HEAD/packages/mui-system) | `5.15.20` | `5.16.0` |
| [@mui/utils](https://github.com/mui/material-ui/tree/HEAD/packages/mui-utils) | `5.15.20` | `5.16.0` |
| [@mui/x-tree-view](https://github.com/mui/mui-x/tree/HEAD/packages/x-tree-view) | `7.8.0` | `7.9.0` |



Updates `@mui/icons-material` from 5.15.20 to 5.16.0
- [Release notes](https://github.com/mui/material-ui/releases)
- [Changelog](https://github.com/mui/material-ui/blob/v5.16.0/CHANGELOG.md)
- [Commits](https://github.com/mui/material-ui/commits/v5.16.0/packages/mui-icons-material)

Updates `@mui/material` from 5.15.21 to 5.16.0
- [Release notes](https://github.com/mui/material-ui/releases)
- [Changelog](https://github.com/mui/material-ui/blob/v5.16.0/CHANGELOG.md)
- [Commits](https://github.com/mui/material-ui/commits/v5.16.0/packages/mui-material)

Updates `@mui/system` from 5.15.20 to 5.16.0
- [Release notes](https://github.com/mui/material-ui/releases)
- [Changelog](https://github.com/mui/material-ui/blob/v5.16.0/CHANGELOG.md)
- [Commits](https://github.com/mui/material-ui/commits/v5.16.0/packages/mui-system)

Updates `@mui/utils` from 5.15.20 to 5.16.0
- [Release notes](https://github.com/mui/material-ui/releases)
- [Changelog](https://github.com/mui/material-ui/blob/v5.16.0/CHANGELOG.md)
- [Commits](https://github.com/mui/material-ui/commits/v5.16.0/packages/mui-utils)

Updates `@mui/x-tree-view` from 7.8.0 to 7.9.0
- [Release notes](https://github.com/mui/mui-x/releases)
- [Changelog](https://github.com/mui/mui-x/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mui/mui-x/commits/v7.9.0/packages/x-tree-view)

---
updated-dependencies:
- dependency-name: "@mui/icons-material"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: mui
- dependency-name: "@mui/material"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: mui
- dependency-name: "@mui/system"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: mui
- dependency-name: "@mui/utils"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: mui
- dependency-name: "@mui/x-tree-view"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: mui
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 11:12:42 -08:00
Mathias Fredriksson 35a808f089 fix(coderd/agentapi): set ReadyAt for start timeout (#13846) 2024-07-09 18:55:16 +00:00
Jyotirmoy Bandyopadhayaya b07e3069dd feat: added whomai cmd to coder cli (#13814)
* feat: added whomai cmd to coder cli
* refactor: update Coder CLI's whoami command to use client URL instead of deployment config
* feat(cli): add unit tests for the whoami command
* chore(docs): add coder command to fetch authenticated user info
* chore(doc): update help desc
2024-07-09 13:23:11 -05:00
Bruno Quaresma 01b30eaa32 fix(site): enable dormant workspace to be deleted (#13850) 2024-07-09 14:55:46 -03:00
Colin Adler af001773db fix!: remove TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA cipher by default (#13837)
This cipher is included by default in Go as a fallback, but is marked as
an insecure cipher. This removes the 3des cipher by default.

Before:
```
$ nmap --script ssl-enum-ciphers -p 443 xxxxxxx
Starting Nmap 7.94 ( https://nmap.org ) at 2024-07-08 14:16 CDT
Nmap scan report for xxxxx (xxx.xxx.xxx.xxx)
Host is up (0.038s latency).
rDNS record for xxx.xxx.xxx.xxx: xxx.xxx.xxx.xxx.bc.googleusercontent.com

PORT    STATE SERVICE
443/tcp open  https
| ssl-enum-ciphers:
|   TLSv1.2:
|     ciphers:
|       TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA (secp256r1) - C
|     compressors:
|       NULL
|     cipher preference: server
|     warnings:
|       64-bit block cipher 3DES vulnerable to SWEET32 attack
|   TLSv1.3:
|     ciphers:
|       TLS_AKE_WITH_AES_128_GCM_SHA256 (ecdh_x25519) - A
|       TLS_AKE_WITH_AES_256_GCM_SHA384 (ecdh_x25519) - A
|       TLS_AKE_WITH_CHACHA20_POLY1305_SHA256 (ecdh_x25519) - A
|     cipher preference: server
|_  least strength: C
```

After:
```
$ nmap --script ssl-enum-ciphers -p 443 xxxxxxx
Starting Nmap 7.94 ( https://nmap.org ) at 2024-07-08 15:04 CDT
Nmap scan report for xxxxx (xxx.xxx.xxx.xxx)
Host is up (0.039s latency).
rDNS record for xxx.xxx.xxx.xxx: xxx.xxx.xxx.xxx.bc.googleusercontent.com

PORT    STATE SERVICE
443/tcp open  https
| ssl-enum-ciphers:
|   TLSv1.2:
|     ciphers:
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
|       TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (secp256r1) - A
|     compressors:
|       NULL
|     cipher preference: client
|   TLSv1.3:
|     ciphers:
|       TLS_AKE_WITH_AES_128_GCM_SHA256 (ecdh_x25519) - A
|       TLS_AKE_WITH_AES_256_GCM_SHA384 (ecdh_x25519) - A
|       TLS_AKE_WITH_CHACHA20_POLY1305_SHA256 (ecdh_x25519) - A
|     cipher preference: server
|_  least strength: A
```

* fixup! fix!(cli): remove `TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA` cipher by default

* fixup! fix!(cli): remove `TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA` cipher by default
2024-07-09 17:18:27 +00:00
Bruno Quaresma 879c61ce23 feat(site): display tooltip in bars for app usage chart (#13854) 2024-07-09 14:02:45 -03:00
Bruno Quaresma 6bf7e5af91 feat(site): support match option for auto create workspace flow (#13836) 2024-07-09 16:14:08 +00:00
Steven Masley 8c33b028d2 chore: include all templates in cli template list (#13841)
* chore: cli template list includes all templates

Shows all accessible templates from all organizations
2024-07-09 11:04:16 -05:00
Steven Masley f9272046d5 chore: remove references to restarting/stopping in update workspace language (#13852)
* chore: remove references to restarting/stopping in update workspace language
* reword updating workspaces to remove the word "restart"
* fix batch wording
2024-07-09 11:02:13 -05:00
Eric Paulsen 266913a357 fix: remove templates plan docs (#13824)
* fix: remove templates plan docs

* make gen

* make update-golden-files
2024-07-09 14:27:34 +00:00
Muhammad Atif Ali c62512a8bb chore: use base64 encoded kubeconfig for pr deployments (#13851) 2024-07-09 14:24:43 +00:00
Muhammad Atif Ali a123badccc chore: use base64 encoded kubeconfig for pr deployments (#13849) 2024-07-09 13:44:59 +00:00
Marcin Tojek 54898033b1 fix: dbpurge: disable parallel tests (#13848) 2024-07-09 15:10:57 +02:00
dependabot[bot] c1440ac4f0 chore: bump github.com/coreos/go-oidc/v3 from 3.10.0 to 3.11.0 (#13827)
Bumps [github.com/coreos/go-oidc/v3](https://github.com/coreos/go-oidc) from 3.10.0 to 3.11.0.
- [Release notes](https://github.com/coreos/go-oidc/releases)
- [Commits](https://github.com/coreos/go-oidc/compare/v3.10.0...v3.11.0)

---
updated-dependencies:
- dependency-name: github.com/coreos/go-oidc/v3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 13:09:04 +00:00
dependabot[bot] 65e1d0af4b ci: bump crate-ci/typos from 1.22.9 to 1.23.1 in the github-actions group (#13803)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Muhammad Atif Ali <atif@coder.com>
2024-07-09 15:45:09 +03:00
Mathias Fredriksson ac6db5edf9 feat(cli): show information about --wait=no for ssh (#13847)
Fixes #11923
2024-07-09 14:32:52 +03:00
Mathias Fredriksson 54055dc4cc fix(cli): prevent asynchronous print of version mismatch in config-ssh (#13845) 2024-07-09 14:32:08 +03:00
dependabot[bot] 407d263cd2 chore: bump google.golang.org/api from 0.182.0 to 0.187.0 (#13828)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 07:59:58 +00:00
dependabot[bot] 0c423f07a7 chore: bump semver and @types/semver in /site (#13834)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 10:49:43 +03:00
Mathias Fredriksson 978364bd3e fix(cli): do not overwrite repeated SSH options in config-ssh (#13819)
Fixes #11593
2024-07-09 09:44:56 +03:00
dependabot[bot] 5cdfc08422 chore: bump google.golang.org/grpc from 1.64.0 to 1.65.0 (#13826)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.64.0 to 1.65.0.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.64.0...v1.65.0)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 06:25:53 +00:00
dependabot[bot] 1f05a4a05e chore: bump github.com/go-chi/chi/v5 from 5.0.10 to 5.1.0 (#13730)
Bumps [github.com/go-chi/chi/v5](https://github.com/go-chi/chi) from 5.0.10 to 5.1.0.
- [Release notes](https://github.com/go-chi/chi/releases)
- [Changelog](https://github.com/go-chi/chi/blob/master/CHANGELOG.md)
- [Commits](https://github.com/go-chi/chi/compare/v5.0.10...v5.1.0)

---
updated-dependencies:
- dependency-name: github.com/go-chi/chi/v5
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 01:19:18 -05:00
dependabot[bot] 996863936a chore: bump the x group with 7 updates (#13825)
Bumps the x group with 7 updates:

| Package | From | To |
| --- | --- | --- |
| [golang.org/x/crypto](https://github.com/golang/crypto) | `0.24.0` | `0.25.0` |
| [golang.org/x/mod](https://github.com/golang/mod) | `0.18.0` | `0.19.0` |
| [golang.org/x/net](https://github.com/golang/net) | `0.26.0` | `0.27.0` |
| [golang.org/x/oauth2](https://github.com/golang/oauth2) | `0.20.0` | `0.21.0` |
| [golang.org/x/sys](https://github.com/golang/sys) | `0.21.0` | `0.22.0` |
| [golang.org/x/term](https://github.com/golang/term) | `0.21.0` | `0.22.0` |
| [golang.org/x/tools](https://github.com/golang/tools) | `0.22.0` | `0.23.0` |


Updates `golang.org/x/crypto` from 0.24.0 to 0.25.0
- [Commits](https://github.com/golang/crypto/compare/v0.24.0...v0.25.0)

Updates `golang.org/x/mod` from 0.18.0 to 0.19.0
- [Commits](https://github.com/golang/mod/compare/v0.18.0...v0.19.0)

Updates `golang.org/x/net` from 0.26.0 to 0.27.0
- [Commits](https://github.com/golang/net/compare/v0.26.0...v0.27.0)

Updates `golang.org/x/oauth2` from 0.20.0 to 0.21.0
- [Commits](https://github.com/golang/oauth2/compare/v0.20.0...v0.21.0)

Updates `golang.org/x/sys` from 0.21.0 to 0.22.0
- [Commits](https://github.com/golang/sys/compare/v0.21.0...v0.22.0)

Updates `golang.org/x/term` from 0.21.0 to 0.22.0
- [Commits](https://github.com/golang/term/compare/v0.21.0...v0.22.0)

Updates `golang.org/x/tools` from 0.22.0 to 0.23.0
- [Release notes](https://github.com/golang/tools/releases)
- [Commits](https://github.com/golang/tools/compare/v0.22.0...v0.23.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: x
- dependency-name: golang.org/x/mod
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: x
- dependency-name: golang.org/x/net
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: x
- dependency-name: golang.org/x/oauth2
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: x
- dependency-name: golang.org/x/sys
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: x
- dependency-name: golang.org/x/term
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: x
- dependency-name: golang.org/x/tools
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: x
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 01:13:37 -05:00
dependabot[bot] 3085c4cf5b chore: bump @types/lodash from 4.14.196 to 4.17.6 in /site (#13704)
Bumps [@types/lodash](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/lodash) from 4.14.196 to 4.17.6.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/lodash)

---
updated-dependencies:
- dependency-name: "@types/lodash"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 09:11:00 +03:00
dependabot[bot] 83a177e0c7 chore: bump ssh2 and @types/ssh2 in /site (#13710)
Bumps [ssh2](https://github.com/mscdex/ssh2) and [@types/ssh2](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/ssh2). These dependencies needed to be updated together.

Updates `ssh2` from 1.14.0 to 1.15.0
- [Commits](https://github.com/mscdex/ssh2/compare/v1.14.0...v1.15.0)

Updates `@types/ssh2` from 1.11.13 to 1.15.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/ssh2)

---
updated-dependencies:
- dependency-name: ssh2
  dependency-type: direct:development
  update-type: version-update:semver-minor
- dependency-name: "@types/ssh2"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 09:10:28 +03:00
Colin Adler b40d543cb5 chore(offlinedocs): update braces to v3.0.3 (#13842) 2024-07-09 01:01:49 -05:00
dependabot[bot] eafa8f5cb2 chore: bump the vite group across 1 directory with 3 updates (#13833)
Bumps the vite group with 3 updates in the /site directory: [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react), [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) and [vite-plugin-checker](https://github.com/fi3ework/vite-plugin-checker).


Updates `@vitejs/plugin-react` from 4.1.0 to 4.3.1
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/v4.3.1/packages/plugin-react)

Updates `vite` from 4.5.3 to 5.3.3
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.3.3/packages/vite)

Updates `vite-plugin-checker` from 0.6.0 to 0.7.1
- [Release notes](https://github.com/fi3ework/vite-plugin-checker/releases)
- [Changelog](https://github.com/fi3ework/vite-plugin-checker/blob/main/CHANGELOG.md)
- [Commits](https://github.com/fi3ework/vite-plugin-checker/compare/vite-plugin-checker@0.6.0...vite-plugin-checker@0.7.1)

---
updated-dependencies:
- dependency-name: "@vitejs/plugin-react"
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: vite
- dependency-name: vite
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: vite
- dependency-name: vite-plugin-checker
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: vite
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-08 18:25:19 -04:00
Muhammad Atif Ali 05fdb9c1f7 chore: group dependencies (#13798) 2024-07-08 23:11:44 +03:00
Stephen Kirby 79b5d20cd2 typo (#13823) 2024-07-08 15:08:56 -05:00
Colin Adler f9ca9c7a22 chore: upgrade Go to 1.22.5 (#13820)
* chore: upgrade Go to 1.22.5

* fixup! chore: upgrade Go to 1.22.5
2024-07-08 19:42:55 +00:00
Steven Masley 44cb400c8e chore: include host and port in oidc test logs (#13818)
* chore: include host and port in oidc test logs

Log fake IDP's log for debugging port conflicts between tests
2024-07-08 10:24:41 -05:00
Steven Masley d9bdef915d chore: fix typo in oidctest package (#13815) 2024-07-08 14:35:06 +00:00
Danny Kopping bdd2caf95d feat: implement thin vertical slice of system-generated notifications (#13537) 2024-07-08 15:38:50 +02:00
Marcin Tojek 10aa32ca08 chore: refactor AgentHasNotConnectedSinceWeek_LogsExpired (#13802) 2024-07-08 13:52:56 +02:00
Muhammad Atif Ali fecc5b3027 docs: update release schedule (#13795) 2024-07-06 12:17:11 +03:00
Cian Johnston da8911426b fix(dogfood/Dockerfile): change ownership of /etc/sudoers.d to root (#13793) 2024-07-05 12:42:14 +01:00
Marcin Tojek 7c41f957de feat: autostop workspaces owned by suspended users (#13790) 2024-07-04 13:35:41 +00:00
Cian Johnston c2d44d16a3 feat(codersdk/agentsdk): export LogDest interface (#13792)
Signed-off-by: Cian Johnston <cian@coder.com>
2024-07-04 14:04:43 +01:00
Ferran Basora dd80958efb chore: update troubleshooting documentation about dir setting (#13681) 2024-07-03 22:24:49 +03:00
Steven Masley ccf34901bc chore: add templates search query to a filter (#13772)
* chore: add templates search query to a filter
2024-07-03 13:42:23 -05:00
Cian Johnston 8778aa0f71 chore(deps): update go-playground/validator and remove replace directive (#13779)
We had a replace directive in place due to a PR we were waiting to have
merged in go-playground/validator. This was since merged in v10.22.0.

Signed-off-by: Cian Johnston <cian@coder.com>
2024-07-03 18:14:27 +01:00
Cian Johnston ea675897fd fix(dogfood/Dockerfile): revert add explicit --chown to COPY directive (#13569) (#13781)
* Revert "fix(dogfood/Dockerfile): add explicit --chown to COPY directive (#13569)"

This reverts commit c587af7c0e.

* add a bogus comment to ensure hashes change
2024-07-03 17:42:18 +01:00
Michael Smith 940afa1ab1 fix: let workspace pages download partial logs for unhealthy workspaces (#13761)
* fix: get basic fix in for  preventing download logs from blowing up UI

* fix: make sure blob units can't go out of bounds

* fix: make sure timeout is cleared on component unmount

* fix: reduce risk of shared cache state breaking useAgentLogs

* fix: allow partial downloading of logs

* fix: make sure useMemo cache is used properly

* wip: commit current progress on updated logs functionality

* docs: rewrite comment for clarity

* refactor: clean up current code

* fix: update styles for unavailable logs

* fix: resolve linter violations

* fix: update type signature of getErrorDetail

* fix: revert log/enabled logic for useAgentLogs

* fix: remove memoization from DownloadLogsDialog

* fix: update name of timeout state

* refactor: make log web sockets logic more clear

* docs: reword comment for clarity

* fix: commit current style update progress

* fix: finish style updates
2024-07-03 10:17:54 -04:00
Marcin Tojek 07d41716ad fix(provisioner): handle multiple agents, apps, scripts and envs (#13741) 2024-07-03 14:55:28 +02:00
Spike Curtis f6639b788f feat: add ConnectRPC variants for older Agent API versions (#13778) 2024-07-03 16:11:05 +04:00
Spike Curtis e5268e4551 chore: spin clock library out to coder/quartz repo (#13777)
Code that was in `/clock` has been moved to github.com/coder/quartz.  This PR refactors our use of the clock library to point to the external Quartz repo.
2024-07-03 15:02:54 +04:00
Ethan a110d18275 chore: add DRPC tailnet & cli network telemetry (#13687) 2024-07-03 15:23:46 +10:00
Kayla Washburn-Love bfbf634bec chore: update mui (#13747) 2024-07-02 15:19:01 -06:00
Eric Paulsen 80a2a5d6a8 docs: clarify envbox version pinning (#13773) 2024-07-02 20:36:08 +00:00
Stephen Kirby e40cc9314c docs: bump mainline version to v2.13.0 (#13766) 2024-07-02 15:24:26 -05:00
Mathias Fredriksson a114288ef2 ci: remove release make concurrency to fix docker image race (#13769) 2024-07-02 17:49:18 +00:00
Cian Johnston 5ea5db29e9 ci: use postgres version 13 to test migrations (#13767) 2024-07-02 17:03:21 +00:00
Bruno Quaresma 9ee53e5b4e chore(site): refactor filter component to be more extendable (#13688) 2024-07-02 13:15:13 -03:00
Michael Smith 21a923a7a0 chore: add SVG desktop icon (#13765)
* chore: add SVG desktop icon

* fix: add desktop icon to to icons.json
2024-07-02 16:00:16 +00:00
Kayla Washburn-Love b1e7498e77 chore: update xterm (#13752) 2024-07-02 09:29:34 -06:00
Danny Kopping 98c09bf5d2 fix: add policy.go as dependency of Makefile rbac target (#13757) 2024-07-02 14:29:00 +00:00
Steven Masley bde9fd58ea chore: add organization name to workspaces (#13755)
* chore: add organization name to workspaces
2024-07-02 09:25:05 -05:00
Steven Masley 128674918b chore: include organization name when fetching templates (#13751)
* chore: include organization name when fetching templates
* chore: rename template_with_user to template_with_names
2024-07-02 09:08:30 -05:00
Muhammad Atif Ali b87c12ba92 chore(dogfood): fix duplicate security repository entry (#13758) 2024-07-02 14:09:45 +03:00
Steven Masley abc0ff9689 chore: remove database import from cli (#13756)
Cli was using a utility function from a database package.
2024-07-01 21:58:23 +00:00
Kayla Washburn-Love b1ec4630f2 chore: update react dependencies (#13749) 2024-07-01 15:55:27 -06:00
Steven Masley 5bf46f360a chore: remove org context switcher in the cli (#13674)
* chore: remove org context switcher in the cli
2024-07-01 16:04:45 -05:00
Kayla Washburn-Love 4a0fd7466c chore: update emoji-mart data (#13746) 2024-07-01 14:40:15 -06:00
Jaayden Halko f26f123391 feat: route groups by name instead of id (#13692)
* feat: route groups by name instead of id

* fix: update group navigation when name changes

* fix: update isLoading and error checking

* fix: fix format

* fix: update isLoading and error

* fix: cleanup
2024-07-01 15:48:14 -04:00
Kayla Washburn-Love 41e1383640 chore: update caniuse (#13745) 2024-07-01 13:11:04 -06:00
Steven Masley 10c2817f4d chore: swagger docs omit brower based credentials, rely on swagger auth (#13742)
* chore: swagger docs omit brower based credentials, rely on swagger auth

Swagger has an "Authorize" button which should be the only
authentication being used in the api requests
2024-07-01 13:44:35 -05:00
Kayla Washburn-Love cd069faf01 chore: update storybook (#13744) 2024-07-01 12:12:41 -06:00
Kayla Washburn-Love d977654f05 feat: unify organization and deployment management settings (#13602) 2024-07-01 11:15:00 -06:00
Jaayden Halko 9b1d8f79ae docs: update workspace filters docs (#13725) 2024-07-01 12:44:32 -04:00
Eric Paulsen d8d86b16dc docs: move architecture to top level (#13722) 2024-07-01 11:58:56 -04:00
Dean Sheather 6c94dd4f23 chore: add DRPC server implementation for network telemetry (#13675) 2024-07-02 01:50:52 +10:00
dependabot[bot] 2fde054e10 chore: bump rollup-plugin-visualizer from 5.9.0 to 5.12.0 in /site (#13706)
Bumps [rollup-plugin-visualizer](https://github.com/btd/rollup-plugin-visualizer) from 5.9.0 to 5.12.0.
- [Changelog](https://github.com/btd/rollup-plugin-visualizer/blob/master/CHANGELOG.md)
- [Commits](https://github.com/btd/rollup-plugin-visualizer/compare/v5.9.0...v5.12.0)

---
updated-dependencies:
- dependency-name: rollup-plugin-visualizer
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-28 13:45:42 -08:00
dependabot[bot] 8735e234b4 chore: bump storybook/test from 8.0.5 to 8.1.11 in /site (#13716)
* chore: bump @storybook/test from 8.0.5 to 8.1.11 in /site

Bumps [@storybook/test](https://github.com/storybookjs/storybook/tree/HEAD/code/lib/test) from 8.0.5 to 8.1.11.
- [Release notes](https://github.com/storybookjs/storybook/releases)
- [Changelog](https://github.com/storybookjs/storybook/blob/next/CHANGELOG.md)
- [Commits](https://github.com/storybookjs/storybook/commits/v8.1.11/code/lib/test)

---
updated-dependencies:
- dependency-name: "@storybook/test"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* Update remaining storybook dependencies

Not sure if you need to update all of them, but without this you get "no
matchinge export" from at least one of these.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Asher <ash@coder.com>
2024-06-28 20:45:25 +00:00
dependabot[bot] 472ea7ebbf chore: bump @storybook/addon-essentials from 8.0.5 to 8.1.11 in /site (#13712)
Bumps [@storybook/addon-essentials](https://github.com/storybookjs/storybook/tree/HEAD/code/addons/essentials) from 8.0.5 to 8.1.11.
- [Release notes](https://github.com/storybookjs/storybook/releases)
- [Changelog](https://github.com/storybookjs/storybook/blob/next/CHANGELOG.md)
- [Commits](https://github.com/storybookjs/storybook/commits/v8.1.11/code/addons/essentials)

---
updated-dependencies:
- dependency-name: "@storybook/addon-essentials"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-28 12:15:16 -08:00
Steven Masley 6daf330d3a chore: allow organization name or uuid for audit log searching (#13721)
* chore: allow organization name or uuid for audit log searching
2024-06-28 10:01:23 -05:00
Steven Masley 3cc86cf62d chore: implement sane default pagination limit for audit logs (#13676)
* chore: implement sane default pagination limit for audit logs
2024-06-28 07:38:04 -05:00
Cian Johnston 1a877716ca chore: add envbuilder-dogfood template (#13720)
Adds a template that can be used to dogfood on envbuilder!
2024-06-28 12:56:22 +01:00
Danny Kopping 0a221e8d5b feat: create database tables and queries for notifications (#13536) 2024-06-28 09:21:25 +00:00
dependabot[bot] 4213560b7a chore: bump @mui/icons-material from 5.14.0 to 5.15.20 in /site (#13703)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-28 03:49:56 +03:00
dependabot[bot] 2a21b0d144 ci: bump toshimaru/auto-author-assign in the github-actions group (#13696)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-28 03:48:01 +03:00
dependabot[bot] 86ee75b672 chore: bump undici from 6.11.1 to 6.19.2 in /site (#13699)
Bumps [undici](https://github.com/nodejs/undici) from 6.11.1 to 6.19.2.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v6.11.1...v6.19.2)

---
updated-dependencies:
- dependency-name: undici
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-27 12:43:24 -06:00
dependabot[bot] 0b8b227dcf chore: bump emoji-mart from 5.4.0 to 5.6.0 in /site (#13709)
Bumps [emoji-mart](https://github.com/missive/emoji-mart/tree/HEAD/packages/emoji-mart) from 5.4.0 to 5.6.0.
- [Release notes](https://github.com/missive/emoji-mart/releases)
- [Commits](https://github.com/missive/emoji-mart/commits/v5.6.0/packages/emoji-mart)

---
updated-dependencies:
- dependency-name: emoji-mart
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-27 12:41:09 -06:00
Muhammad Atif Ali bda94bfc77 chore: optimize dependabot configuration (#13670) 2024-06-27 21:14:17 +03:00
Kayla Washburn-Love 8b615f4522 fix: disable agent app buttons while a blocking startup script is running (#13667) 2024-06-27 11:25:03 -06:00
Jaayden Halko 093ec3d05b fix: improve checkbox text in template schedule settings dialog (#13669)
* fix: improve checkbox text in template schedule settings dialog

* fix: format

* fix: remove (s) plural language

* fix: fix format
2024-06-27 13:14:06 -04:00
Steven Masley 5a0afd8b7e chore: revert to default survey templates (#13690)
Revert to the default template provided by the package. Includes all fields like the "Message" field. Our template omits headers and keybind helpers.
2024-06-27 05:32:12 -10:00
Steven Masley 22f2c6da4f chore: add command to render all existing cli prompts (#13689)
Adds a command to render all the existing cli prompts we use. This is to validate a change to how our cli ui prompts look.
2024-06-27 05:20:15 -10:00
Spike Curtis ce7f13c6c3 fix: fix TestPGCoordinatorSingle_MissedHeartbeats flake (#13686) 2024-06-27 19:17:24 +04:00
Muhammad Atif Ali 089f06886b chore: add .pnpm-store to .gitignore (#13685) 2024-06-27 15:07:04 +03:00
Spike Curtis c94b5188bd fix: modify workspacesdk to ask for tailnet API 2.0 (#13684)
#13617 bumped the Agent/Tailnet API minor version because it adds telemetry features.  However, we don't actually use the protocol features yet, so it's a bit obnoxious for our CLI client to ask for the newest API version.

This is particularly true of the CLI client, since that's distributed separately, so if an end user installs the latest CLI client and their organization hasn't fully upgraded, then it will fail to connect.

Since we have a release coming up and the telemetry stuff won't make it, I think we should roll back to version 2.0 until we actually implement the telemetry stuff. That way the newest release (2.13) will work with Coder servers all the way back to 2.9.
2024-06-27 15:38:21 +04:00
Spike Curtis 5b59f2880f fix: fix workspacesdk to return error on API mismatch (#13683) 2024-06-27 15:02:43 +04:00
Marcin Tojek c4f1676055 feat: expose workspace build ID to terraform-plugin-coder (#13680) 2024-06-27 10:07:30 +02:00
Steven Masley 30c4b4db5c chore: implement fetch all authorized templates api (#13678) 2024-06-26 11:50:32 -06:00
Steven Masley 08e728bcb2 chore: implement organization scoped audit log requests (#13663)
* chore: add organization_id filter to audit logs
* chore: implement organization scoped audit log requests
2024-06-26 12:38:46 -05:00
Cian Johnston 20e59e0797 ci: test with multiple postgres versions (#13665)
- Tests now run on postgres 16 by default when run locally (can be specified with POSTGRES_VERSION)
- Adds test-go-pg-16 to test against postgres version 16
- Updates Dogfood dockerfile / nix flake to postgres version 16
- Updates docker-compose.yaml postgres tag to 16
2024-06-26 16:22:24 +01:00
Danny Kopping d5d8b918d7 feat: lint github actions workflows (#13552) 2024-06-26 10:28:16 +02:00
Cian Johnston 8a3592582b feat: add "Full Name" field to user creation (#13659)
Adds the ability to specify "Full Name" (a.k.a. Name) when
creating users either via CLI or UI.
2024-06-26 09:00:42 +01:00
austinrhode 87ad560aff feat: add groups and group members to telemetry snapshot (#13655)
* feat: Added in groups and groups members to telemetry snapshot
* feat: adding in test to dbauthz for getting group members and groups
2024-06-25 11:01:40 -07:00
Muhammad Atif Ali 58325dfd14 chore: minor improvements and link updates in README.md (#13656)
* chore: minor improvements and link updates in README.md

* fixup!
2024-06-25 13:29:08 -04:00
Garrett Delfosse fed668b432 chore: switch ssh session stats based on experiment (#13637) 2024-06-25 10:58:45 -04:00
Steven Masley d7eadee4d7 chore: insert audit log entries for organization CRUD (#13660)
* chore: insert audit log entries for organization CRUD
2024-06-25 09:03:15 -05:00
Spike Curtis 9c1a6a29f2 feat: add docstrings to mock timer and ticker methods and structs (#13658) 2024-06-25 16:59:35 +04:00
Spike Curtis 46e1c36c42 feat: add Next() method to mock Clock (#13657) 2024-06-25 16:48:26 +04:00
Spike Curtis 0d2f14606b chore: add usage information to clock library README (#13594)
Adds a Usage section to the README of the clock testing library.
2024-06-25 16:38:32 +04:00
Muhammad Atif Ali 136900268e ci: migrate to depot.dev runners (#13467) 2024-06-25 09:36:33 +03:00
Cian Johnston 313d4e02d2 chore(scaletest/dashboard): stub out initChromeDPCtx in unit tests (#13650) 2024-06-24 21:33:24 +01:00
Steven Masley 65b9f9bfd6 chore: audit organization member add/delete/edit (#13620)
* chore: audit organization member add/removals
2024-06-24 14:19:32 -05:00
Stephen Kirby 94639730f8 docs: bump mainline version to v2.12.3 (#13652)
* docs: bump mainline version to v2.12.3

* updated stable version
2024-06-24 14:07:42 -05:00
Steven Masley 34c67e8428 test: add unit test helper to create templates in second organizations (#13628)
* chore: add coderdtest helpers
2024-06-24 12:55:57 -05:00
Steven Masley e4333c0433 chore: 'coder login' reset cli organization context (#13646)
Cli organization context is reset on `coder login` if the organization
selected is an invalid organization.
2024-06-24 12:55:39 -05:00
dependabot[bot] 8ccdf05bbc chore: bump github.com/aws/aws-sdk-go-v2 from 1.27.0 to 1.30.0 (#13643)
Bumps [github.com/aws/aws-sdk-go-v2](https://github.com/aws/aws-sdk-go-v2) from 1.27.0 to 1.30.0.
- [Release notes](https://github.com/aws/aws-sdk-go-v2/releases)
- [Commits](https://github.com/aws/aws-sdk-go-v2/compare/v1.27.0...v1.30.0)

---
updated-dependencies:
- dependency-name: github.com/aws/aws-sdk-go-v2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-24 12:22:17 -05:00
dependabot[bot] 218f429336 chore: bump github.com/hashicorp/hcl/v2 from 2.20.0 to 2.21.0 (#13642)
Bumps [github.com/hashicorp/hcl/v2](https://github.com/hashicorp/hcl) from 2.20.0 to 2.21.0.
- [Release notes](https://github.com/hashicorp/hcl/releases)
- [Changelog](https://github.com/hashicorp/hcl/blob/main/CHANGELOG.md)
- [Commits](https://github.com/hashicorp/hcl/compare/v2.20.0...v2.21.0)

---
updated-dependencies:
- dependency-name: github.com/hashicorp/hcl/v2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-24 12:21:45 -05:00
dependabot[bot] 6f4a9b6b51 chore: bump github.com/valyala/fasthttp from 1.54.0 to 1.55.0 (#13640)
Bumps [github.com/valyala/fasthttp](https://github.com/valyala/fasthttp) from 1.54.0 to 1.55.0.
- [Release notes](https://github.com/valyala/fasthttp/releases)
- [Commits](https://github.com/valyala/fasthttp/compare/1.54.0...v1.55.0)

---
updated-dependencies:
- dependency-name: github.com/valyala/fasthttp
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-24 12:21:18 -05:00
Colin Adler 3dec6ff32f chore: add protobuf types for tailnet telemetry (#13617) 2024-06-24 12:13:03 -05:00
Stephen Kirby b9d83c75de fixed changelog script release channel flag (#13649) 2024-06-24 11:50:24 -05:00
dependabot[bot] 7e20b56352 chore: bump alpine from 3.20.0 to 3.20.1 in /scripts (#13644)
Bumps alpine from 3.20.0 to 3.20.1.

---
updated-dependencies:
- dependency-name: alpine
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-24 11:48:07 -05:00
Stephen Kirby 3d6c9799e3 fixed script ref (#13647) 2024-06-24 11:27:13 -05:00
Cian Johnston b4a5c7ffa9 chore: upgrade Go version to 1.22.4 (#13623)
Updates Go version to 1.22.4

Co-authored-by: Muhammad Atif Ali <me@matifali.dev>
2024-06-24 15:50:52 +01:00
dependabot[bot] 7cb8bfb133 ci: bump the github-actions group with 2 updates (#13645)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-24 15:52:05 +03:00
Stephen Kirby 2cfadad023 manually updated autoversion (#13633) 2024-06-22 12:16:07 -05:00
Stephen Kirby 9abaa94599 docs: bump mainline version to v2.12.2 (#13632) 2024-06-21 15:11:58 -05:00
Kyle Carberry 54e8f30002 chore: remove failing_sections from healthcheck (#13426)
Closes #10854.
2024-06-21 14:49:02 -04:00
Steven Masley 5177f366f5 fix: organization 404 write 1 http status (#13629) 2024-06-21 13:01:46 -05:00
Steven Masley 0e933f0537 chore: refactor user -> rbac.subject into a function (#13624)
* chore: refactor user subject logic to be in 1 place
* test: implement test to assert deleted custom roles are omitted
* add unit test for deleted role
2024-06-21 11:30:02 -05:00
Kyle Carberry 3ef12ac284 fix: remove connected button (#13625)
It didn't make a lot of sense in current form. It will when we improve autostop.
2024-06-21 11:41:59 -04:00
Steven Masley 75e7213ac2 feat: add cli command to remove organization member (#13619) 2024-06-21 10:35:59 -05:00
Bruno Quaresma cbdaa63b68 chore(site): refactor popover to make it easier to extend (#13611) 2024-06-21 11:15:37 -03:00
Ethan 714f2ef83c fix: fix shallow clones not retrieving a valid semver (#13609) 2024-06-22 00:02:12 +10:00
Bruno Quaresma 73a25c3bc5 chore(site): add InputGroup component (#13597) 2024-06-21 10:54:55 -03:00
Steven Masley 819bfd3170 fix: remove assigning org-member role, this is implied from membership (#13578) 2024-06-21 08:01:39 -05:00
dependabot[bot] 66a604d779 chore: bump golang.org/x/tools from 0.21.0 to 0.22.0 (#13513)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-21 08:54:06 +03:00
Steven Masley 2ef2f97388 chore: improve error message on adding existing org_member (#13621) 2024-06-20 18:05:11 -05:00
Colin Adler 889daf200e feat(enterprise): add auditing to SCIM (#13614) 2024-06-20 17:22:27 -05:00
Steven Masley c4656d77cc chore: add help to error to reset organization context (#13616) 2024-06-20 16:44:47 -05:00
Kyle Carberry 495eea452f fix: track login page correctly (#13618) 2024-06-20 21:33:47 +00:00
Asher 43e45f4ab7 fix: fill out zero-value user properties in /audit (#13604) 2024-06-20 12:40:08 -08:00
Kyle Carberry 57b38e5bb8 fix: allow coder.com in CSP if telemetry is enabled (#13615)
* fix: allow coder.com in CSP if telemetry is enabled

* Fix control couple lint
2024-06-20 16:05:22 -04:00
Kyle Carberry 0793a4b35b feat: add cross-origin reporting for telemetry in the dashboard (#13612)
* feat: add cross-origin reporting for telemetry in the dashboard

* Respect the telemetry flag

* Fix embedded metadata

* Fix compilation error

* Fix linting
2024-06-20 15:19:45 -04:00
Steven Masley a1db6d809e chore: implement delete organization member (#13589)
Side effects of removing an organization member will orphan their
user resources. These side effects are not addressed here
2024-06-20 10:06:37 -05:00
Kelly Peilin Chan a1ec8ad6e9 Update docker-in-workspaces.md (#13606) 2024-06-20 11:05:21 -04:00
Steven Masley 8e06ad46d0 chore: add organization member api + cli (#13577) 2024-06-20 09:19:24 -05:00
Dean Sheather 4699adee5e chore: update dogfood sydney server (#13610) 2024-06-20 14:12:25 +00:00
Spike Curtis 8923ce5216 fix: fix flake in TestAppHealth_Healthy (#13607) 2024-06-20 12:02:31 +04:00
Spike Curtis 02ffff11dd feat: add NewTicker to clock testing library (#13593) 2024-06-20 10:16:04 +04:00
Kyle Carberry 7049d7a881 fix: display trial errors in the dashboard (#13601)
* fix: display trial errors in the dashboard

The error was essentially being ignored before!

* Remove day mention in product of trial

* fmt
2024-06-19 12:02:51 -04:00
dependabot[bot] 84cdcac8ad chore: bump ws from 8.14.2 to 8.17.1 in /site (#13595)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-19 10:51:25 +03:00
Kayla Washburn-Love e987ad1d89 fix: don't allow "new" or "create" as url-friendly names (#13596) 2024-06-18 15:36:13 -06:00
Kyle Carberry 3a1fa04590 fix: write server config to telemetry (#13590)
* fix: add external auth configs to telemetry

* Refactor telemetry to send the entire config

* gen

* Fix linting
2024-06-18 16:20:21 -04:00
Spike Curtis d0b2f6196c fix: allow mock clock Timers to accept negative duration (#13592)
The standard library `NewTimer`, `AfterFunc` and `Reset` allow negative durations, so our mock clock library should as well.
2024-06-18 15:40:56 +04:00
Spike Curtis 1de023a121 chore: add README to clock testing (#13583)
Adds README with some draft content explaining why the library exists.  Will be most relevant when we spin out into a standalone library.
2024-06-18 10:16:49 +04:00
Steven Masley 1d3642d0be chore: fix link in v2.0.0 changelog to scale tests (#13591) 2024-06-17 14:24:07 -05:00
Kayla Washburn-Love 8c1bd32c33 feat(site): add basic organization management ui (#13288) 2024-06-17 11:02:39 -06:00
Kayla Washburn-Love 07cd9acb2c fix: fix workspace actions options (#13572) 2024-06-17 10:24:30 -06:00
dependabot[bot] eed9794516 ci: bump crate-ci/typos in the github-actions group (#13584)
Bumps the github-actions group with 1 update: [crate-ci/typos](https://github.com/crate-ci/typos).


Updates `crate-ci/typos` from 1.22.3 to 1.22.7
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.22.3...v1.22.7)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-17 09:03:26 -04:00
Ben Potter 808e1c0d89 docs: add screenshots page (#13582)
* docs: add screenshots page

* fmt
2024-06-15 15:34:18 -05:00
Garrett Delfosse 44d69139d5 chore: accept payload on workspace usage route (#13544) 2024-06-14 10:08:45 -04:00
Eric Paulsen 87820a29d7 docs: reorganize scaling docs (#13574)
* refactor scaling docs

* manifest

* make fmt

* fix 404s

* fix 404s pt 2

* fix manifest
2024-06-14 09:30:04 -04:00
Spike Curtis c01d6fdf46 chore: refactor apphealth and tests to use clock testing library (#13576)
Refactors the apphealth subsystem and unit tests to use `clock.Clock`.

Also slightly simplifies the implementation, which wrapped a function that never returned an error in a `retry.Retry`.  The retry is entirely superfluous in that case, so removed.

UTs used to take a few seconds to run, and now run in milliseconds or better.  No sleeps, `Eventually`, or polling.

Dropped the "no spamming" test since we can directly assert the number of handler calls on the mainline test case.
2024-06-14 15:06:33 +04:00
Cian Johnston fe240add86 fix(coderd): userOIDC: ignore leading @ of EmailDomain (#13568) 2024-06-14 09:29:07 +01:00
Steven Masley d04959cea8 chore: implement custom role assignment for organization admins (#13570)
* chore: static role assignment mapping

Until a dynamic approach is created in the database, only org-admins
can assign custom organization roles.
2024-06-13 15:59:06 -05:00
Steven Masley 3d30c8dc68 chore: protect reserved builtin rolenames (#13571)
Conflicting built-in and database role names makes it hard to
disambiguate
2024-06-13 15:12:37 -05:00
Steven Masley 7d51515f9d chore: implement assign organization roles from the cli (#13558)
Basic functionality to assign roles to an organization member via cli.
2024-06-13 14:49:32 -05:00
Eric Paulsen 87a172fb14 docs: add validated architecture (#13561)
* docs: add validated architecture

* make: fmt

* formatting

* fix 404s

* fix 404s pt 2

* fix 404s pt 3
2024-06-13 13:00:26 -04:00
Cian Johnston c587af7c0e fix(dogfood/Dockerfile): add explicit --chown to COPY directive (#13569) 2024-06-13 15:16:34 +01:00
Cian Johnston 5d3f3c08cd chore(dogfood): add devcontainer for use with envbuilder (#13567) 2024-06-13 14:31:49 +01:00
Spike Curtis 0268c7a659 chore: refactor autobuild/notify to use clock test (#13566)
Refactor autobuild/notify and tests to use the clock testing library.

I also rewrote some of the comments because I didn't understand them when I was looking at the package.
2024-06-13 16:01:17 +04:00
Spike Curtis 4b0b9b08d5 feat: add interfaces report to support bundle (#13563) 2024-06-13 13:09:54 +04:00
Spike Curtis 88eb6ce378 fix: fix flake in TestDERPEndToEnd (#13564) 2024-06-13 11:38:51 +04:00
Spike Curtis fc09077b7b feat!: add interface report to coder netcheck (#13562)
re: #13327

Adds local interfaces to `coder netcheck` and checks their MTUs for potential problems.

This is mostly relevant for end-user systems where VPNs are common.  We _could_ also add it to coderd healthcheck, but until I see coderd connecting to workspaces over a VPN in the wild, I don't think its worth the UX effort.

Netcheck results get the following:

```
  "interfaces": {
    "error": null,
    "severity": "ok",
    "warnings": null,
    "dismissed": false,
    "interfaces": [
      {
        "name": "lo0",
        "mtu": 16384,
        "addresses": [
          "127.0.0.1/8",
          "::1/128",
          "fe80::1/64"
        ]
      },
      {
        "name": "en8",
        "mtu": 1500,
        "addresses": [
          "192.168.50.217/24",
          "fe80::c13:1a92:3fa5:dd7e/64"
        ]
      }
    ]
  }
```

_Technically_ not back compatible if anyone is parsing `coder netcheck` output as JSON, since the original output is now under `"derp"` in the output.
2024-06-13 10:19:36 +04:00
Steven Masley d0fc81a51c chore: implement cli list organization members (#13555)
example cli command: 
`coder organization members`
2024-06-12 10:07:12 -10:00
Steven Masley bbe23edc7d chore: implement api layer for listing organization members (#13546) 2024-06-12 09:52:18 -10:00
Steven Masley de9e6889bb chore: merge organization member db queries (#13542)
Merge members queries into 1 that also joins in the user table for username.
Required to list organization members on UI/cli
2024-06-12 09:23:48 -10:00
Kyle Carberry 1ca5dc0328 chore: always use the latest released version tag when building (#13556)
* chore: always use the latest released version tag when building

* Update version.sh

Co-authored-by: Dean Sheather <dean@deansheather.com>

---------

Co-authored-by: Dean Sheather <dean@deansheather.com>
2024-06-12 14:52:35 -04:00
Kayla Washburn-Love 28228f1bcb feat: allow editing org icon (#13547) 2024-06-12 12:28:13 -06:00
Ethan 58bf0ec1c6 chore: add additional tailnet topology integration tests (#13549) 2024-06-12 16:02:34 +00:00
Spike Curtis ba7d1835e5 fix: fix flake in TestWorkspaceAgent_Metadata_CatchMemoryLeak (#13553)
Fixes flake seen here: https://github.com/coder/coder/actions/runs/9461246505/job/26061605278

#13486 subtly changes the test so that `post` uses the new v2 Agent API, and when canceling context, there is a race condition where the yamux session underpinning the API can get torn down before the RPC processes the canceled context, yielding a different error response than the test was previously expecting.

I've refactored the test to just stop posting when the test finishes, rather than depend on a context cancel to end the posting goroutine.
2024-06-12 18:33:22 +04:00
Bruno Quaresma 0c627a4cb9 refactor(site): refactor filter search field (#13545) 2024-06-12 10:22:20 -03:00
Ethan a11f8b003b chore: write speedtest connection updates to stderr (#13550) 2024-06-12 07:10:28 +00:00
Kira Pilot dd99897bb2 chore: updating Ashby link to be position agnostic (#13543) 2024-06-11 12:59:33 -04:00
Steven Masley 5ccf5084e8 chore: create type for unique role names (#13506)
* chore: create type for unique role names

Using `string` was confusing when something should be combined with
org context, and when not to. Naming this new name, "RoleIdentifier"
2024-06-11 08:55:28 -05:00
Kyle Carberry c9cca9d56e fix: transform underscores to hyphens for github login (#13384)
Fixes #13339.
2024-06-11 13:34:05 +00:00
Marcin Tojek 7958c52918 docs: faq: restrict file transfers from workspaces (#13534) 2024-06-11 09:29:29 +00:00
Spike Curtis 1f9bdc36bf fix: ignore yamux.ErrSessionShutdown on TestTailnetAPIConnector_Disconnects (#13532) 2024-06-11 11:16:49 +04:00
Ethan dd243686e4 chore!: remove deprecated agent v1 routes (#13486) 2024-06-11 12:22:59 +10:00
dependabot[bot] e7bea17e70 chore: bump braces from 3.0.2 to 3.0.3 in /site (#13526)
Bumps [braces](https://github.com/micromatch/braces) from 3.0.2 to 3.0.3.
- [Changelog](https://github.com/micromatch/braces/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/braces/compare/3.0.2...3.0.3)

---
updated-dependencies:
- dependency-name: braces
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-11 03:54:42 +03:00
dependabot[bot] 363dbad3a3 ci: bump the github-actions group with 2 updates (#13521)
Bumps the github-actions group with 2 updates: [crate-ci/typos](https://github.com/crate-ci/typos) and [aquasecurity/trivy-action](https://github.com/aquasecurity/trivy-action).


Updates `crate-ci/typos` from 1.21.0 to 1.22.3
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crate-ci/typos/compare/v1.21.0...v1.22.3)

Updates `aquasecurity/trivy-action` from 0.21.0 to 0.22.0
- [Release notes](https://github.com/aquasecurity/trivy-action/releases)
- [Commits](https://github.com/aquasecurity/trivy-action/compare/fd25fed6972e341ff0007ddb61f77e88103953c2...595be6a0f6560a0a8fc419ddf630567fc623531d)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: aquasecurity/trivy-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-11 01:06:40 +03:00
Garrett Delfosse 5b9a65e5c1 chore: move Batcher and Tracker to workspacestats (#13418) 2024-06-10 15:35:23 -04:00
Colin Adler c7e7312cb0 fix(site): don't show start button while starting (#13495) 2024-06-10 13:28:21 -05:00
Marcin Tojek e96652ebbc feat: block file transfers for security (#13501) 2024-06-10 12:12:23 +00:00
Spike Curtis 8326a3a675 chore: change mock clock to allow Advance() within timer/tick functions (#13500) 2024-06-10 15:27:24 +04:00
Kyle Carberry 7c081dcd6f fix: replace invalid utf-8 sequences in agent logs (#13436)
* fix: replace invalid utf-8 sequences in agent logs

Fixes #13433.

* fix: replace invalid UTF-8 with , add regression

Signed-off-by: Spike Curtis <spike@coder.com>

---------

Signed-off-by: Spike Curtis <spike@coder.com>
Co-authored-by: Spike Curtis <spike@coder.com>
2024-06-10 15:27:11 +04:00
Steven Masley 0d65143301 chore: implement audit log for custom role edits (#13494)
* chore: implement audit log for custom role edits
2024-06-07 14:11:57 -05:00
Bruno Quaresma 056a697eff feat(site): add download logs option (#13466) 2024-06-07 10:03:05 -03:00
Cian Johnston 48ecee1025 chore(cli): address cli netcheck test flake (#13492)
* netcheck: removes check for healthy node report in test
* coderd/healthcheck/derphealth: do not override parent context deadline
2024-06-07 10:01:54 +01:00
Steven Masley 7c3b8b6224 chore: duplicate migration file fix, 000216 (#13498) 2024-06-06 16:13:00 -05:00
Steven Masley e2b330fcba chore: change sql parameter for custom roles to be a (name,org_id) tuple (#13480)
* chore: sql parameter to custom roles to be a (name,org) tuple

CustomRole lookup takes (name,org_id) tuples as the search criteria.
2024-06-06 15:36:37 -05:00
Bruno Quaresma 1adc19b41f fix(site): allow user to update their name (#13493) 2024-06-06 15:32:51 -03:00
Bruno Quaresma 4dfa901990 refactor(site): hide select helper when only one proxy exists (#13496) 2024-06-06 15:17:43 -03:00
Bruno Quaresma a8a81a61cd fix(site): fix tooltip in start button group (#13497) 2024-06-06 14:51:52 -03:00
Kayla Washburn-Love 44a70a5bc2 feat: edit org display names and descriptions (#13474) 2024-06-06 10:59:59 -06:00
Cian Johnston 1131772e79 feat(coderd): set full name from IDP name claim (#13468)
* Updates OIDC and GitHub OAuth login to fetch set name from relevant claim fields
* Adds CODER_OIDC_NAME_FIELD as configurable source of user name claim
* Adds httpapi function to normalize a username such that it will pass validation
* Adds firstName / lastName fields to dev OIDC setup
2024-06-06 13:37:08 +01:00
Colin Adler e743588843 docs: bump k8s install version (#13487) 2024-06-06 03:31:32 +00:00
Colin Adler 37676c46d5 chore(scripts): remove remaining gh_auth calls from release scripts (#13485) 2024-06-05 22:24:26 -05:00
Jon Ayers 7995d7c3d6 fix: only render tooltip when require_active_version enabled (#13484) 2024-06-06 02:52:49 +00:00
Colin Adler f1b42a15fa fix(site): show workspace start button when require active version is enabled (#13482) 2024-06-05 16:50:52 -05:00
Steven Masley 8f62311f00 chore: remove organization_id suffix from org_member roles in database (#13473)
Organization member's table is already scoped to an organization.
Rolename should avoid having the org_id appended.

Wipes all existing organization role assignments, which should not be used anyway.
2024-06-05 11:25:02 -05:00
Spike Curtis fade8ba759 fix: fix MeasureLatencyRecvTimeout to accept send=0 (#13477)
Fixes the flake seen here: https://github.com/coder/coder/runs/25832852690

Linux is not a real time operating system, and so there is no guarantee that subsequent `time.Now()` `time.Since()` calls will return a non-zero time.  This assert is mainly there to ensure we don't return `-1`.
2024-06-05 18:27:56 +04:00
Spike Curtis 775fc3f5e9 chore: add Now, Since, AfterFunc to clock; use clock for configmaps test (#13476)
* chore: add Now, Since, AfterFunc to clock; use clock for configmaps test

* chore: update flake.nix vendor hash

Signed-off-by: Spike Curtis <spike@coder.com>

---------

Signed-off-by: Spike Curtis <spike@coder.com>
2024-06-05 16:00:02 +04:00
Spike Curtis ffcfbb6c55 chore: add example test case for clock package (#13465) 2024-06-05 15:49:31 +04:00
Spike Curtis 9c3fd5dd26 chore: add explicit Wait() to clock.Advance() (#13464) 2024-06-05 15:37:16 +04:00
Spike Curtis 42324b386a chore: add clock pkg for testing time (#13461)
Adds a package for testing time/timer/ticker functions.  Implementation is limited to `NewTimer` and `NewContextTicker`, but will eventually be expanded to all `time` functions from the standard library as well as `context.WithTimeout()`, `context.WithDeadline()`.

Replaces `benbjohnson/clock` for the pubsub watchdog, as a proof of concept.

Eventually, as we expand functionality, we will replace most time-related functions with this library for testing.
2024-06-05 13:55:45 +04:00
Ethan a4bba520a2 feat(cli): add json output to coder speedtest (#13475) 2024-06-05 08:31:44 +00:00
Mathias Fredriksson 9a757f8e74 chore(scripts): fix release promote stable to set latest tag (#13471) 2024-06-04 23:01:26 +00:00
dependabot[bot] 83ac386533 chore: bump ejs from 3.1.9 to 3.1.10 in /site (#13447)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-04 23:52:59 +03:00
Kayla Washburn-Love 0ea89a3d41 chore: add cleanup callbacks to some useEffect calls (#13444) 2024-06-04 12:18:03 -06:00
Stephen Kirby 213848e2e3 chore(docs): rename banners and show usage of multiple (#13435)
* renamed banners in docs

* fmt

* Update appearance.md

Co-authored-by: Kayla Washburn-Love <mckayla@hey.com>

* fmt

---------

Co-authored-by: Kayla Washburn-Love <mckayla@hey.com>
Co-authored-by: Ben <me@bpmct.net>
2024-06-04 17:49:13 +00:00
Ben Potter 8435b70bea chore: update docs for v2.12 mainline and v2.11 stable (#13469)
* chore: update docs for v2.12 mainline and v2.11 stable

* remove broken link
2024-06-04 12:22:13 -05:00
Mathias Fredriksson 3b7f9534fb chore(scripts): fix dry run for autoversion in release.sh (#13470) 2024-06-04 20:10:15 +03:00
Steven Masley e3206612e1 chore: implement typed database for custom permissions (breaks existing custom roles) (#13457)
* chore: typed database custom permissions
* add migration to fix any custom roles out there
2024-06-04 09:27:44 -05:00
Cian Johnston 168d2d6ba0 chore(coderd): add update user profile test for members (#13463) 2024-06-04 14:17:17 +01:00
Marcin Tojek cd32c42699 fix(cli): inherit provisioner tags from last template version (#13462) 2024-06-04 11:59:54 +00:00
Muhammad Atif Ali e527bc6242 chore(dogfood): replace deprecated coder_workspace.owner_oidc_access_token and add order to agent metadata (#13456) 2024-06-04 09:21:01 +01:00
Mathias Fredriksson a51076a4cd chore(scripts): fix unbound variable in tag_version.sh (#13428) 2024-06-03 21:29:24 +00:00
Kayla Washburn-Love 78b8264a90 feat(site): add deployment menu to navbar (#13401) 2024-06-03 15:05:49 -06:00
Muhammad Atif Ali c7233eccec chore(dogfood): bump module versions (#13455) 2024-06-04 00:03:34 +03:00
Colin Adler 40390ecc30 chore: fix TestServer/Prometheus/DBMetricsDisabled test flake (#13453)
See: https://github.com/coder/coder/actions/runs/9352137263/job/25739550487#step:5:368
2024-06-03 15:38:59 -05:00
Kayla Washburn-Love 2806752c7d chore: add light mode snapshot to chromatic for WorkspaceBuildPageView (#13449) 2024-06-03 13:50:59 -06:00
Colin Adler e4ac691468 chore: fix (*coderdtest.WorkspaceAgentWaiter).Wait() flake (#13451) 2024-06-03 14:46:56 -05:00
Colin Adler 43ef00401c chore: linting fixes (#13450) 2024-06-03 14:33:37 -05:00
Steven Masley 27f26910b6 chore: external auth validate response "Forbidden" should return invalid, not an error (#13446)
* chore: add unit test to delete workspace from suspended user
* chore: account for forbidden as well as unauthorized response codes
2024-06-03 13:16:51 -05:00
dependabot[bot] 0b019cad77 chore: bump google.golang.org/api from 0.181.0 to 0.182.0 (#13439)
Bumps [google.golang.org/api](https://github.com/googleapis/google-api-go-client) from 0.181.0 to 0.182.0.
- [Release notes](https://github.com/googleapis/google-api-go-client/releases)
- [Changelog](https://github.com/googleapis/google-api-go-client/blob/main/CHANGES.md)
- [Commits](https://github.com/googleapis/google-api-go-client/compare/v0.181.0...v0.182.0)

---
updated-dependencies:
- dependency-name: google.golang.org/api
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-03 12:30:12 -05:00
Colin Adler 9d00a26a90 fix: add missing route for codersdk.PostLogSource (#13421) 2024-06-03 12:29:50 -05:00
dependabot[bot] 8cdd468107 chore: bump github.com/coder/terraform-provider-coder from 0.22.0 to 0.23.0 (#13440)
Bumps [github.com/coder/terraform-provider-coder](https://github.com/coder/terraform-provider-coder) from 0.22.0 to 0.23.0.
- [Release notes](https://github.com/coder/terraform-provider-coder/releases)
- [Changelog](https://github.com/coder/terraform-provider-coder/blob/main/.goreleaser.yml)
- [Commits](https://github.com/coder/terraform-provider-coder/compare/v0.22.0...v0.23.0)

---
updated-dependencies:
- dependency-name: github.com/coder/terraform-provider-coder
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-03 12:29:29 -05:00
Kayla Washburn-Love cb94dfb1f6 fix: fix build error background color (#13445) 2024-06-03 11:18:44 -06:00
Kayla Washburn-Love 79fd736387 chore(site): enable React's StrictMode (#13399) 2024-06-03 10:03:46 -06:00
Steven Masley 973cc2b875 chore: add edit organization role to cli (#13365)
Editing custom org roles from hidden org cli command.
2024-06-03 09:34:10 -05:00
Steven Masley 24ba81930b chore: return failed refresh errors on external auth as string (was boolean) (#13402)
* chore: return failed refresh errors on external auth

Failed refreshes should return errors. These errors are captured
as validate errors.
2024-06-03 09:33:49 -05:00
Marcin Tojek bf98b0dfe4 fix: correct swagger description for Insights API (#13442) 2024-06-03 15:48:31 +02:00
Colin Adler b723da9e91 chore: upgrade terraform to v1.8.5 (#13429) 2024-06-02 13:10:28 -04:00
1051 changed files with 63268 additions and 23988 deletions
+2 -2
View File
@@ -4,12 +4,12 @@ description: |
inputs:
version:
description: "The Go version to use."
default: "1.22.3"
default: "1.22.5"
runs:
using: "composite"
steps:
- name: Setup Go
uses: buildjet/setup-go@v5
uses: actions/setup-go@v5
with:
go-version: ${{ inputs.version }}
+3 -3
View File
@@ -13,11 +13,11 @@ runs:
- name: Install pnpm
uses: pnpm/action-setup@v3
with:
version: 8
version: 9.6
- name: Setup Node
uses: buildjet/setup-node@v4.0.1
uses: actions/setup-node@v4.0.3
with:
node-version: 18.19.0
node-version: 20.16.0
# See https://github.com/actions/setup-node#caching-global-packages-data
cache: "pnpm"
cache-dependency-path: ${{ inputs.directory }}/pnpm-lock.yaml
+1 -1
View File
@@ -7,5 +7,5 @@ runs:
- name: Install Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.8.4
terraform_version: 1.9.2
terraform_wrapper: false
+39 -31
View File
@@ -39,6 +39,10 @@ updates:
prefix: "chore"
labels: []
open-pull-requests-limit: 15
groups:
x:
patterns:
- "golang.org/x/*"
ignore:
# Ignore patch updates for all dependencies
- dependency-name: "*"
@@ -61,7 +65,9 @@ updates:
- dependency-name: "terraform"
- package-ecosystem: "npm"
directory: "/site/"
directories:
- "/site"
- "/offlinedocs"
schedule:
interval: "monthly"
time: "06:00"
@@ -71,6 +77,32 @@ updates:
commit-message:
prefix: "chore"
labels: []
groups:
xterm:
patterns:
- "@xterm*"
mui:
patterns:
- "@mui*"
react:
patterns:
- "react*"
- "@types/react*"
emotion:
patterns:
- "@emotion*"
eslint:
patterns:
- "eslint*"
- "@typescript-eslint*"
jest:
patterns:
- "jest*"
- "@types/jest"
vite:
patterns:
- "vite*"
- "@vitejs/plugin-react"
ignore:
# Ignore patch updates for all dependencies
- dependency-name: "*"
@@ -81,34 +113,10 @@ updates:
- dependency-name: "@types/node"
update-types:
- version-update:semver-major
# Ignore @storybook updates, run `pnpm dlx storybook@latest upgrade` to upgrade manually
- dependency-name: "*storybook*" # matches @storybook/* and storybook*
update-types:
- version-update:semver-major
- version-update:semver-minor
- version-update:semver-patch
open-pull-requests-limit: 15
groups:
site:
patterns:
- "*"
- package-ecosystem: "npm"
directory: "/offlinedocs/"
schedule:
interval: "monthly"
time: "06:00"
timezone: "America/Chicago"
reviewers:
- "coder/ts"
commit-message:
prefix: "chore"
labels: []
ignore:
# Ignore patch updates for all dependencies
- dependency-name: "*"
update-types:
- version-update:semver-patch
# Ignore major updates to Node.js types, because they need to
# correspond to the Node.js engine version
- dependency-name: "@types/node"
update-types:
- version-update:semver-major
groups:
offlinedocs:
patterns:
- "*"
+85 -67
View File
@@ -120,12 +120,14 @@ jobs:
update-flake:
needs: changes
if: needs.changes.outputs.gomod == 'true'
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 1
# See: https://github.com/stefanzweifel/git-auto-commit-action?tab=readme-ov-file#commits-made-by-this-action-do-not-trigger-new-workflow-runs
token: ${{ secrets.CDRCI_GITHUB_TOKEN }}
- name: Setup Go
uses: ./.github/actions/setup-go
@@ -133,13 +135,25 @@ jobs:
- name: Update Nix Flake SRI Hash
run: ./scripts/update-flake.sh
# auto update flake for dependabot
- uses: stefanzweifel/git-auto-commit-action@v5
if: github.actor == 'dependabot[bot]'
with:
# Allows dependabot to still rebase!
commit_message: "[dependabot skip] Update Nix Flake SRI Hash"
commit_user_name: "dependabot[bot]"
commit_user_email: "49699333+dependabot[bot]@users.noreply.github.com>"
commit_author: "dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>"
# require everyone else to update it themselves
- name: Ensure No Changes
if: github.actor != 'dependabot[bot]'
run: git diff --exit-code
lint:
needs: changes
if: needs.changes.outputs.offlinedocs-only == 'false' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -160,7 +174,7 @@ jobs:
echo "LINT_CACHE_DIR=$dir" >> $GITHUB_ENV
- name: golangci-lint cache
uses: buildjet/cache@v4
uses: actions/cache@v4
with:
path: |
${{ env.LINT_CACHE_DIR }}
@@ -170,7 +184,7 @@ jobs:
# Check for any typos
- name: Check for typos
uses: crate-ci/typos@v1.21.0
uses: crate-ci/typos@v1.23.5
with:
config: .github/workflows/typos.toml
@@ -191,9 +205,15 @@ jobs:
run: |
make --output-sync=line -j lint
- name: Check workflow files
run: |
bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash) 1.6.22
./actionlint -color -shellcheck= -ignore "set-output"
shell: bash
gen:
timeout-minutes: 8
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
needs: changes
if: needs.changes.outputs.docs-only == 'false' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
steps:
@@ -243,7 +263,7 @@ jobs:
fmt:
needs: changes
if: needs.changes.outputs.offlinedocs-only == 'false' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
timeout-minutes: 7
steps:
- name: Checkout
@@ -254,12 +274,9 @@ jobs:
- name: Setup Node
uses: ./.github/actions/setup-node
# Use default Go version
- name: Setup Go
uses: buildjet/setup-go@v5
with:
# This doesn't need caching. It's super fast anyways!
cache: false
go-version: 1.21.9
uses: ./.github/actions/setup-go
- name: Install shfmt
run: go install mvdan.cc/sh/v3/cmd/shfmt@v3.7.0
@@ -273,7 +290,7 @@ jobs:
run: ./scripts/check_unstaged.sh
test-go:
runs-on: ${{ matrix.os == 'ubuntu-latest' && github.repository_owner == 'coder' && 'buildjet-4vcpu-ubuntu-2204' || matrix.os == 'macos-latest' && github.repository_owner == 'coder' && 'macos-latest-xlarge' || matrix.os == 'windows-2022' && github.repository_owner == 'coder' && 'windows-latest-16-cores' || matrix.os }}
runs-on: ${{ matrix.os == 'ubuntu-latest' && github.repository_owner == 'coder' && 'depot-ubuntu-22.04-4' || matrix.os == 'macos-latest' && github.repository_owner == 'coder' && 'macos-latest-xlarge' || matrix.os == 'windows-2022' && github.repository_owner == 'coder' && 'windows-latest-16-cores' || matrix.os }}
needs: changes
if: needs.changes.outputs.go == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
timeout-minutes: 20
@@ -329,7 +346,7 @@ jobs:
api-key: ${{ secrets.DATADOG_API_KEY }}
test-go-pg:
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
needs:
- changes
if: needs.changes.outputs.go == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
@@ -351,8 +368,50 @@ jobs:
uses: ./.github/actions/setup-tf
- name: Test with PostgreSQL Database
env:
POSTGRES_VERSION: "13"
TS_DEBUG_DISCO: "true"
run: |
make test-postgres
- name: Upload test stats to Datadog
timeout-minutes: 1
continue-on-error: true
uses: ./.github/actions/upload-datadog
if: success() || failure()
with:
api-key: ${{ secrets.DATADOG_API_KEY }}
# NOTE: this could instead be defined as a matrix strategy, but we want to
# only block merging if tests on postgres 13 fail. Using a matrix strategy
# here makes the check in the above `required` job rather complicated.
test-go-pg-16:
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
needs:
- changes
if: needs.changes.outputs.go == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
# This timeout must be greater than the timeout set by `go test` in
# `make test-postgres` to ensure we receive a trace of running
# goroutines. Setting this to the timeout +5m should work quite well
# even if some of the preceding steps are slow.
timeout-minutes: 25
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Setup Go
uses: ./.github/actions/setup-go
- name: Setup Terraform
uses: ./.github/actions/setup-tf
- name: Test with PostgreSQL Database
env:
POSTGRES_VERSION: "16"
TS_DEBUG_DISCO: "true"
run: |
export TS_DEBUG_DISCO=true
make test-postgres
- name: Upload test stats to Datadog
@@ -364,7 +423,7 @@ jobs:
api-key: ${{ secrets.DATADOG_API_KEY }}
test-go-race:
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
needs: changes
if: needs.changes.outputs.go == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
timeout-minutes: 25
@@ -399,7 +458,7 @@ jobs:
# These tests are skipped in the main go test jobs because they require root
# and mess with networking.
test-go-tailnet-integration:
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
needs: changes
# Unnecessary to run on main for now
if: needs.changes.outputs.tailnet-integration == 'true' || needs.changes.outputs.ci == 'true'
@@ -421,7 +480,7 @@ jobs:
run: make test-tailnet-integration
test-js:
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
needs: changes
if: needs.changes.outputs.ts == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
timeout-minutes: 20
@@ -438,7 +497,7 @@ jobs:
working-directory: site
test-e2e:
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-16vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-16' || 'ubuntu-latest' }}
needs: changes
if: needs.changes.outputs.go == 'true' || needs.changes.outputs.ts == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
timeout-minutes: 20
@@ -582,7 +641,7 @@ jobs:
offlinedocs:
name: offlinedocs
needs: changes
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
if: needs.changes.outputs.offlinedocs == 'true' || needs.changes.outputs.ci == 'true' || needs.changes.outputs.docs == 'true'
steps:
@@ -650,7 +709,6 @@ jobs:
- test-e2e
- offlinedocs
- sqlc-vet
- dependency-license-review
# Allow this job to run even if the needed jobs fail, are skipped or
# cancelled.
if: always()
@@ -667,7 +725,6 @@ jobs:
echo "- test-js: ${{ needs.test-js.result }}"
echo "- test-e2e: ${{ needs.test-e2e.result }}"
echo "- offlinedocs: ${{ needs.offlinedocs.result }}"
echo "- dependency-license-review: ${{ needs.dependency-license-review.result }}"
echo
# We allow skipped jobs to pass, but not failed or cancelled jobs.
@@ -680,11 +737,10 @@ jobs:
build:
# This builds and publishes ghcr.io/coder/coder-preview:main for each commit
# to main branch. We are only building this for amd64 platform. (>95% pulls
# are for amd64)
# to main branch.
needs: changes
if: github.ref == 'refs/heads/main' && needs.changes.outputs.docs-only == 'false' && !github.event.pull_request.head.repo.fork
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
env:
DOCKER_CLI_EXPERIMENTAL: "enabled"
outputs:
@@ -744,13 +800,15 @@ jobs:
echo "tag=$tag" >> $GITHUB_OUTPUT
# build images for each architecture
make -j build/coder_"$version"_linux_{amd64,arm64,armv7}.tag
# note: omitting the -j argument to avoid race conditions when pushing
make build/coder_"$version"_linux_{amd64,arm64,armv7}.tag
# only push if we are on main branch
if [ "${{ github.ref }}" == "refs/heads/main" ]; then
# build and push multi-arch manifest, this depends on the other images
# being pushed so will automatically push them
make -j push/build/coder_"$version"_linux_{amd64,arm64,armv7}.tag
# note: omitting the -j argument to avoid race conditions when pushing
make push/build/coder_"$version"_linux_{amd64,arm64,armv7}.tag
# Define specific tags
tags=("$tag" "main" "latest")
@@ -890,7 +948,7 @@ jobs:
# runs sqlc-vet to ensure all queries are valid. This catches any mistakes
# in migrations or sqlc queries that makes a query unable to be prepared.
sqlc-vet:
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
needs: changes
if: needs.changes.outputs.db == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main'
steps:
@@ -908,43 +966,3 @@ jobs:
- name: Setup and run sqlc vet
run: |
make sqlc-vet
# dependency-license-review checks that no license-incompatible dependencies have been introduced.
# This action is not intended to do a vulnerability check since that is handled by a separate action.
dependency-license-review:
runs-on: ubuntu-latest
if: github.ref != 'refs/heads/main' && github.actor != 'dependabot[bot]'
steps:
- name: "Checkout Repository"
uses: actions/checkout@v4
- name: "Dependency Review"
id: review
uses: actions/dependency-review-action@v4.3.2
with:
allow-licenses: Apache-2.0, BSD-2-Clause, BSD-3-Clause, CC0-1.0, ISC, MIT, MIT-0, MPL-2.0
allow-dependencies-licenses: "pkg:golang/github.com/coder/wgtunnel@0.1.13-0.20240522110300-ade90dfb2da0"
license-check: true
vulnerability-check: false
- name: "Report"
# make sure this step runs even if the previous failed
if: always()
shell: bash
env:
VULNERABLE_CHANGES: ${{ steps.review.outputs.invalid-license-changes }}
run: |
fields=( "unlicensed" "unresolved" "forbidden" )
# This is unfortunate that we have to do this but the action does not support failing on
# an unknown license. The unknown dependency could easily have a GPL license which
# would be problematic for us.
# Track https://github.com/actions/dependency-review-action/issues/672 for when
# we can remove this brittle workaround.
for field in "${fields[@]}"; do
# Use jq to check if the array is not empty
if [[ $(echo "$VULNERABLE_CHANGES" | jq ".${field} | length") -ne 0 ]]; then
echo "Invalid or unknown licenses detected, contact @sreya to ensure your added dependency falls under one of our allowed licenses."
echo "$VULNERABLE_CHANGES" | jq
exit 1
fi
done
echo "No incompatible licenses detected"
+1
View File
@@ -19,6 +19,7 @@ on:
jobs:
build_image:
if: github.actor != 'dependabot[bot]' # Skip Dependabot PRs
runs-on: ubuntu-latest
steps:
- name: Checkout
+46
View File
@@ -0,0 +1,46 @@
# Workflow for serving the webapp locally & running Meticulous tests against it.
name: Meticulous
on:
push:
branches:
- main
paths:
- "site/**"
pull_request:
paths:
- "site/**"
# Meticulous needs the workflow to be triggered on workflow_dispatch events,
# so that Meticulous can run the workflow on the base commit to compare
# against if an existing workflow hasn't run.
workflow_dispatch:
permissions:
actions: write
contents: read
issues: write
pull-requests: write
statuses: read
jobs:
meticulous:
runs-on: ubuntu-latest
steps:
- name: "Checkout Repository"
uses: actions/checkout@v4
- name: Setup Node
uses: ./.github/actions/setup-node
- name: Build
working-directory: ./site
run: pnpm build
- name: Serve
working-directory: ./site
run: |
pnpm vite preview &
sleep 5
- name: Run Meticulous tests
uses: alwaysmeticulous/report-diffs-action/cloud-compute@v1
with:
api-token: ${{ secrets.METICULOUS_API_TOKEN }}
app-url: "http://127.0.0.1:4173/"
+2 -2
View File
@@ -11,7 +11,7 @@ jobs:
# While GitHub's toaster runners are likelier to flake, we want consistency
# between this environment and the regular test environment for DataDog
# statistics and to only show real workflow threats.
runs-on: "buildjet-8vcpu-ubuntu-2204"
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
# This runner costs 0.016 USD per minute,
# so 0.016 * 240 = 3.84 USD per run.
timeout-minutes: 240
@@ -40,7 +40,7 @@ jobs:
go-timing:
# We run these tests with p=1 so we don't need a lot of compute.
runs-on: "buildjet-2vcpu-ubuntu-2204"
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04' || 'ubuntu-latest' }}
timeout-minutes: 10
steps:
- name: Checkout
+1 -1
View File
@@ -14,4 +14,4 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Assign author
uses: toshimaru/auto-author-assign@v2.1.0
uses: toshimaru/auto-author-assign@v2.1.1
+3 -3
View File
@@ -101,7 +101,7 @@ jobs:
run: |
set -euo pipefail
mkdir -p ~/.kube
echo "${{ secrets.PR_DEPLOYMENTS_KUBECONFIG }}" > ~/.kube/config
echo "${{ secrets.PR_DEPLOYMENTS_KUBECONFIG_BASE64 }}" | base64 --decode > ~/.kube/config
chmod 644 ~/.kube/config
export KUBECONFIG=~/.kube/config
@@ -189,7 +189,7 @@ jobs:
needs: get_info
# Run build job only if there are changes in the files that we care about or if the workflow is manually triggered with --build flag
if: needs.get_info.outputs.BUILD == 'true'
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
# This concurrency only cancels build jobs if a new build is triggred. It will avoid cancelling the current deployemtn in case of docs chnages.
concurrency:
group: build-${{ github.workflow }}-${{ github.ref }}-${{ needs.get_info.outputs.BUILD }}
@@ -253,7 +253,7 @@ jobs:
run: |
set -euo pipefail
mkdir -p ~/.kube
echo "${{ secrets.PR_DEPLOYMENTS_KUBECONFIG }}" > ~/.kube/config
echo "${{ secrets.PR_DEPLOYMENTS_KUBECONFIG_BASE64 }}" | base64 --decode > ~/.kube/config
chmod 644 ~/.kube/config
export KUBECONFIG=~/.kube/config
+6 -6
View File
@@ -39,7 +39,7 @@ env:
jobs:
release:
name: Build and publish
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
env:
# Necessary for Docker manifest
DOCKER_CLI_EXPERIMENTAL: "enabled"
@@ -180,7 +180,7 @@ jobs:
- name: Test migrations from current ref to main
run: |
make test-migrations
POSTGRES_VERSION=13 make test-migrations
# Setup GCloud for signing Windows binaries.
- name: Authenticate to Google Cloud
@@ -297,7 +297,7 @@ jobs:
# build Docker images for each architecture
version="$(./scripts/version.sh)"
make -j build/coder_"$version"_linux_{amd64,arm64,armv7}.tag
make build/coder_"$version"_linux_{amd64,arm64,armv7}.tag
# we can't build multi-arch if the images aren't pushed, so quit now
# if dry-running
@@ -308,7 +308,7 @@ jobs:
# build and push multi-arch manifest, this depends on the other images
# being pushed so will automatically push them.
make -j push/build/coder_"$version"_linux.tag
make push/build/coder_"$version"_linux.tag
# if the current version is equal to the highest (according to semver)
# version in the repo, also create a multi-arch image as ":latest" and
@@ -396,14 +396,14 @@ jobs:
./build/*.rpm
retention-days: 7
- name: Start Packer builds
- name: Send repository-dispatch event
if: ${{ !inputs.dry_run }}
uses: peter-evans/repository-dispatch@v3
with:
token: ${{ secrets.CDRCI_GITHUB_TOKEN }}
repository: coder/packages
event-type: coder-release
client-payload: '{"coder_version": "${{ steps.version.outputs.version }}"}'
client-payload: '{"coder_version": "${{ steps.version.outputs.version }}", "release_channel": "${{ inputs.release_channel }}"}'
publish-homebrew:
name: Publish to Homebrew tap
+3 -3
View File
@@ -23,7 +23,7 @@ concurrency:
jobs:
codeql:
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -56,7 +56,7 @@ jobs:
"${{ secrets.SLACK_SECURITY_FAILURE_WEBHOOK_URL }}"
trivy:
runs-on: ${{ github.repository_owner == 'coder' && 'buildjet-8vcpu-ubuntu-2204' || 'ubuntu-latest' }}
runs-on: ${{ github.repository_owner == 'coder' && 'depot-ubuntu-22.04-8' || 'ubuntu-latest' }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -114,7 +114,7 @@ jobs:
echo "image=$(cat "$image_job")" >> $GITHUB_OUTPUT
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@fd25fed6972e341ff0007ddb61f77e88103953c2
uses: aquasecurity/trivy-action@6e7b7d1fd3e4fef0c5fa8cce1229c54b2c9bd0d8
with:
image-ref: ${{ steps.build.outputs.image }}
format: sarif
+8 -2
View File
@@ -14,8 +14,14 @@ darcula = "darcula"
Hashi = "Hashi"
trialer = "trialer"
encrypter = "encrypter"
hel = "hel" # as in helsinki
pn = "pn" # this is used as proto node
# as in helsinki
hel = "hel"
# this is used as proto node
pn = "pn"
# typos doesn't like the EDE in TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
EDE = "EDE"
# HELO is an SMTP command
HELO = "HELO"
[files]
extend-exclude = [
+3
View File
@@ -68,3 +68,6 @@ result
# Filebrowser.db
**/filebrowser.db
# pnpm
.pnpm-store/
+5
View File
@@ -195,6 +195,11 @@ linters-settings:
- name: var-naming
- name: waitgroup-by-value
# irrelevant as of Go v1.22: https://go.dev/blog/loopvar-preview
govet:
disable:
- loopclosure
issues:
# Rules listed here: https://github.com/securego/gosec#available-rules
exclude-rules:
+3
View File
@@ -71,6 +71,9 @@ result
# Filebrowser.db
**/filebrowser.db
# pnpm
.pnpm-store/
# .prettierignore.include:
# Helm templates contain variables that are invalid YAML and can't be formatted
# by Prettier.
+18 -7
View File
@@ -36,6 +36,7 @@ GOOS := $(shell go env GOOS)
GOARCH := $(shell go env GOARCH)
GOOS_BIN_EXT := $(if $(filter windows, $(GOOS)),.exe,)
VERSION := $(shell ./scripts/version.sh)
POSTGRES_VERSION ?= 16
# Use the highest ZSTD compression level in CI.
ifdef CI
@@ -447,8 +448,7 @@ lint/ts:
lint/go:
./scripts/check_enterprise_imports.sh
linter_ver=$(shell egrep -o 'GOLANGCI_LINT_VERSION=\S+' dogfood/Dockerfile | cut -d '=' -f 2)
go install github.com/golangci/golangci-lint/cmd/golangci-lint@v$$linter_ver
golangci-lint run
go run github.com/golangci/golangci-lint/cmd/golangci-lint@v$$linter_ver run
.PHONY: lint/go
lint/examples:
@@ -487,6 +487,7 @@ gen: \
site/src/api/typesGenerated.ts \
coderd/rbac/object_gen.go \
codersdk/rbacresources_gen.go \
site/src/api/rbacresources_gen.ts \
docs/admin/prometheus.md \
docs/cli.md \
docs/admin/audit-logs.md \
@@ -517,6 +518,8 @@ gen/mark-fresh:
$(DB_GEN_FILES) \
site/src/api/typesGenerated.ts \
coderd/rbac/object_gen.go \
codersdk/rbacresources_gen.go \
site/src/api/rbacresources_gen.ts \
docs/admin/prometheus.md \
docs/cli.md \
docs/admin/audit-logs.md \
@@ -615,12 +618,16 @@ site/src/theme/icons.json: $(wildcard scripts/gensite/*) $(wildcard site/static/
examples/examples.gen.json: scripts/examplegen/main.go examples/examples.go $(shell find ./examples/templates)
go run ./scripts/examplegen/main.go > examples/examples.gen.json
coderd/rbac/object_gen.go: scripts/rbacgen/main.go coderd/rbac/object.go
coderd/rbac/object_gen.go: scripts/rbacgen/rbacobject.gotmpl scripts/rbacgen/main.go coderd/rbac/object.go coderd/rbac/policy/policy.go
go run scripts/rbacgen/main.go rbac > coderd/rbac/object_gen.go
codersdk/rbacresources_gen.go: scripts/rbacgen/main.go coderd/rbac/object.go
codersdk/rbacresources_gen.go: scripts/rbacgen/codersdk.gotmpl scripts/rbacgen/main.go coderd/rbac/object.go coderd/rbac/policy/policy.go
go run scripts/rbacgen/main.go codersdk > codersdk/rbacresources_gen.go
site/src/api/rbacresources_gen.ts: scripts/rbacgen/codersdk.gotmpl scripts/rbacgen/main.go coderd/rbac/object.go coderd/rbac/policy/policy.go
go run scripts/rbacgen/main.go typescript > site/src/api/rbacresources_gen.ts
docs/admin/prometheus.md: scripts/metricsdocgen/main.go scripts/metricsdocgen/metrics
go run scripts/metricsdocgen/main.go
./scripts/pnpm_install.sh
@@ -814,7 +821,7 @@ test-migrations: test-postgres-docker
# NOTE: we set --memory to the same size as a GitHub runner.
test-postgres-docker:
docker rm -f test-postgres-docker || true
docker rm -f test-postgres-docker-${POSTGRES_VERSION} || true
docker run \
--env POSTGRES_PASSWORD=postgres \
--env POSTGRES_USER=postgres \
@@ -822,11 +829,11 @@ test-postgres-docker:
--env PGDATA=/tmp \
--tmpfs /tmp \
--publish 5432:5432 \
--name test-postgres-docker \
--name test-postgres-docker-${POSTGRES_VERSION} \
--restart no \
--detach \
--memory 16GB \
gcr.io/coder-dev-1/postgres:13 \
gcr.io/coder-dev-1/postgres:${POSTGRES_VERSION} \
-c shared_buffers=1GB \
-c work_mem=1GB \
-c effective_cache_size=1GB \
@@ -865,3 +872,7 @@ test-tailnet-integration:
test-clean:
go clean -testcache
.PHONY: test-clean
.PHONY: test-e2e
test-e2e:
cd ./site && DEBUG=pw:api pnpm playwright:test --forbid-only --workers 1
+16 -16
View File
@@ -20,17 +20,17 @@
<br>
<br>
[Quickstart](#quickstart) | [Docs](https://coder.com/docs) | [Why Coder](https://coder.com/why) | [Enterprise](https://coder.com/docs/v2/latest/enterprise)
[Quickstart](#quickstart) | [Docs](https://coder.com/docs) | [Why Coder](https://coder.com/why) | [Enterprise](https://coder.com/docs/enterprise)
[![discord](https://img.shields.io/discord/747933592273027093?label=discord)](https://discord.gg/coder)
[![release](https://img.shields.io/github/v/release/coder/coder)](https://github.com/coder/coder/releases/latest)
[![godoc](https://pkg.go.dev/badge/github.com/coder/coder.svg)](https://pkg.go.dev/github.com/coder/coder)
[![Go Report Card](https://goreportcard.com/badge/github.com/coder/coder)](https://goreportcard.com/report/github.com/coder/coder)
[![Go Report Card](https://goreportcard.com/badge/github.com/coder/coder/v2)](https://goreportcard.com/report/github.com/coder/coder/v2)
[![license](https://img.shields.io/github/license/coder/coder)](./LICENSE)
</div>
[Coder](https://coder.com) enables organizations to set up development environments in their public or private cloud infrastructure. Cloud development environments are defined with Terraform, connected through a secure high-speed Wireguard® tunnel, and are automatically shut down when not in use to save on costs. Coder gives engineering teams the flexibility to use the cloud for workloads that are most beneficial to them.
[Coder](https://coder.com) enables organizations to set up development environments in their public or private cloud infrastructure. Cloud development environments are defined with Terraform, connected through a secure high-speed Wireguard® tunnel, and automatically shut down when not used to save on costs. Coder gives engineering teams the flexibility to use the cloud for workloads most beneficial to them.
- Define cloud development environments in Terraform
- EC2 VMs, Kubernetes Pods, Docker Containers, etc.
@@ -53,7 +53,7 @@ curl -L https://coder.com/install.sh | sh
coder server
# Navigate to http://localhost:3000 to create your initial user,
# create a Docker template, and provision a workspace
# create a Docker template and provision a workspace
```
## Install
@@ -69,7 +69,7 @@ curl -L https://coder.com/install.sh | sh
You can run the install script with `--dry-run` to see the commands that will be used to install without executing them. Run the install script with `--help` for additional flags.
> See [install](https://coder.com/docs/v2/latest/install) for additional methods.
> See [install](https://coder.com/docs/install) for additional methods.
Once installed, you can start a production deployment with a single command:
@@ -81,27 +81,27 @@ coder server
coder server --postgres-url <url> --access-url <url>
```
Use `coder --help` to get a list of flags and environment variables. Use our [install guides](https://coder.com/docs/v2/latest/install) for a full walkthrough.
Use `coder --help` to get a list of flags and environment variables. Use our [install guides](https://coder.com/docs/install) for a complete walkthrough.
## Documentation
Browse our docs [here](https://coder.com/docs/v2) or visit a specific section below:
Browse our docs [here](https://coder.com/docs) or visit a specific section below:
- [**Templates**](https://coder.com/docs/v2/latest/templates): Templates are written in Terraform and describe the infrastructure for workspaces
- [**Workspaces**](https://coder.com/docs/v2/latest/workspaces): Workspaces contain the IDEs, dependencies, and configuration information needed for software development
- [**IDEs**](https://coder.com/docs/v2/latest/ides): Connect your existing editor to a workspace
- [**Administration**](https://coder.com/docs/v2/latest/admin): Learn how to operate Coder
- [**Enterprise**](https://coder.com/docs/v2/latest/enterprise): Learn about our paid features built for large teams
- [**Templates**](https://coder.com/docs/templates): Templates are written in Terraform and describe the infrastructure for workspaces
- [**Workspaces**](https://coder.com/docs/workspaces): Workspaces contain the IDEs, dependencies, and configuration information needed for software development
- [**IDEs**](https://coder.com/docs/ides): Connect your existing editor to a workspace
- [**Administration**](https://coder.com/docs/admin): Learn how to operate Coder
- [**Enterprise**](https://coder.com/docs/enterprise): Learn about our paid features built for large teams
## Support
Feel free to [open an issue](https://github.com/coder/coder/issues/new) if you have questions, run into bugs, or have a feature request.
[Join our Discord](https://discord.gg/coder) to provide feedback on in-progress features, and chat with the community using Coder!
[Join our Discord](https://discord.gg/coder) to provide feedback on in-progress features and chat with the community using Coder!
## Integrations
We are always working on new integrations. Feel free to open an issue to request an integration. Contributions are welcome in any official or community repositories.
We are always working on new integrations. Please feel free to open an issue and ask for an integration. Contributions are welcome in any official or community repositories.
### Official
@@ -120,9 +120,9 @@ We are always working on new integrations. Feel free to open an issue to request
## Contributing
We are always happy to see new contributors to Coder. If you are new to the Coder codebase, we have
[a guide on how to get started](https://coder.com/docs/v2/latest/CONTRIBUTING). We'd love to see your
[a guide on how to get started](https://coder.com/docs/CONTRIBUTING). We'd love to see your
contributions!
## Hiring
Apply [here](https://cdr.co/github-apply) if you're interested in joining our team.
Apply [here](https://jobs.ashbyhq.com/coder?utm_source=github&utm_medium=readme&utm_campaign=unknown) if you're interested in joining our team.
+4
View File
@@ -91,6 +91,7 @@ type Options struct {
ModifiedProcesses chan []*agentproc.Process
// ProcessManagementTick is used for testing process priority management.
ProcessManagementTick <-chan time.Time
BlockFileTransfer bool
}
type Client interface {
@@ -184,6 +185,7 @@ func New(options Options) Agent {
modifiedProcs: options.ModifiedProcesses,
processManagementTick: options.ProcessManagementTick,
logSender: agentsdk.NewLogSender(options.Logger),
blockFileTransfer: options.BlockFileTransfer,
prometheusRegistry: prometheusRegistry,
metrics: newAgentMetrics(prometheusRegistry),
@@ -239,6 +241,7 @@ type agent struct {
sessionToken atomic.Pointer[string]
sshServer *agentssh.Server
sshMaxTimeout time.Duration
blockFileTransfer bool
lifecycleUpdate chan struct{}
lifecycleReported chan codersdk.WorkspaceAgentLifecycle
@@ -277,6 +280,7 @@ func (a *agent) init() {
AnnouncementBanners: func() *[]codersdk.BannerConfig { return a.announcementBanners.Load() },
UpdateEnv: a.updateCommandEnv,
WorkingDirectory: func() string { return a.manifest.Load().Directory },
BlockFileTransfer: a.blockFileTransfer,
})
if err != nil {
panic(err)
+93
View File
@@ -970,6 +970,99 @@ func TestAgent_SCP(t *testing.T) {
require.NoError(t, err)
}
func TestAgent_FileTransferBlocked(t *testing.T) {
t.Parallel()
assertFileTransferBlocked := func(t *testing.T, errorMessage string) {
// NOTE: Checking content of the error message is flaky. Most likely there is a race condition, which results
// in stopping the client in different phases, and returning different errors:
// - client read the full error message: File transfer has been disabled.
// - client's stream was terminated before reading the error message: EOF
// - client just read the error code (Windows): Process exited with status 65
isErr := strings.Contains(errorMessage, agentssh.BlockedFileTransferErrorMessage) ||
strings.Contains(errorMessage, "EOF") ||
strings.Contains(errorMessage, "Process exited with status 65")
require.True(t, isErr, fmt.Sprintf("Message: "+errorMessage))
}
t.Run("SFTP", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
//nolint:dogsled
conn, _, _, _, _ := setupAgent(t, agentsdk.Manifest{}, 0, func(_ *agenttest.Client, o *agent.Options) {
o.BlockFileTransfer = true
})
sshClient, err := conn.SSHClient(ctx)
require.NoError(t, err)
defer sshClient.Close()
_, err = sftp.NewClient(sshClient)
require.Error(t, err)
assertFileTransferBlocked(t, err.Error())
})
t.Run("SCP with go-scp package", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
//nolint:dogsled
conn, _, _, _, _ := setupAgent(t, agentsdk.Manifest{}, 0, func(_ *agenttest.Client, o *agent.Options) {
o.BlockFileTransfer = true
})
sshClient, err := conn.SSHClient(ctx)
require.NoError(t, err)
defer sshClient.Close()
scpClient, err := scp.NewClientBySSH(sshClient)
require.NoError(t, err)
defer scpClient.Close()
tempFile := filepath.Join(t.TempDir(), "scp")
err = scpClient.CopyFile(context.Background(), strings.NewReader("hello world"), tempFile, "0755")
require.Error(t, err)
assertFileTransferBlocked(t, err.Error())
})
t.Run("Forbidden commands", func(t *testing.T) {
t.Parallel()
for _, c := range agentssh.BlockedFileTransferCommands {
t.Run(c, func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
//nolint:dogsled
conn, _, _, _, _ := setupAgent(t, agentsdk.Manifest{}, 0, func(_ *agenttest.Client, o *agent.Options) {
o.BlockFileTransfer = true
})
sshClient, err := conn.SSHClient(ctx)
require.NoError(t, err)
defer sshClient.Close()
session, err := sshClient.NewSession()
require.NoError(t, err)
defer session.Close()
stdout, err := session.StdoutPipe()
require.NoError(t, err)
//nolint:govet // we don't need `c := c` in Go 1.22
err = session.Start(c)
require.NoError(t, err)
defer session.Close()
msg, err := io.ReadAll(stdout)
require.NoError(t, err)
assertFileTransferBlocked(t, string(msg))
})
}
})
}
func TestAgent_EnvironmentVariables(t *testing.T) {
t.Parallel()
key := "EXAMPLE"
+1 -1
View File
@@ -349,7 +349,7 @@ func (r *Runner) run(ctx context.Context, script codersdk.WorkspaceAgentScript)
"This usually means a child process was started with references to stdout or stderr. As a result, this " +
"process may now have been terminated. Consider redirecting the output or using a separate " +
"\"coder_script\" for the process, see " +
"https://coder.com/docs/v2/latest/templates/troubleshooting#startup-script-issues for more information.",
"https://coder.com/docs/templates/troubleshooting#startup-script-issues for more information.",
)
// Inform the user by propagating the message via log writers.
_, _ = fmt.Fprintf(cmd.Stderr, "WARNING: %s. %s\n", message, details)
+53
View File
@@ -52,8 +52,16 @@ const (
// MagicProcessCmdlineJetBrains is a string in a process's command line that
// uniquely identifies it as JetBrains software.
MagicProcessCmdlineJetBrains = "idea.vendor.name=JetBrains"
// BlockedFileTransferErrorCode indicates that SSH server restricted the raw command from performing
// the file transfer.
BlockedFileTransferErrorCode = 65 // Error code: host not allowed to connect
BlockedFileTransferErrorMessage = "File transfer has been disabled."
)
// BlockedFileTransferCommands contains a list of restricted file transfer commands.
var BlockedFileTransferCommands = []string{"nc", "rsync", "scp", "sftp"}
// Config sets configuration parameters for the agent SSH server.
type Config struct {
// MaxTimeout sets the absolute connection timeout, none if empty. If set to
@@ -74,6 +82,8 @@ type Config struct {
// X11SocketDir is the directory where X11 sockets are created. Default is
// /tmp/.X11-unix.
X11SocketDir string
// BlockFileTransfer restricts use of file transfer applications.
BlockFileTransfer bool
}
type Server struct {
@@ -272,6 +282,18 @@ func (s *Server) sessionHandler(session ssh.Session) {
extraEnv = append(extraEnv, fmt.Sprintf("DISPLAY=:%d.0", x11.ScreenNumber))
}
if s.fileTransferBlocked(session) {
s.logger.Warn(ctx, "file transfer blocked", slog.F("session_subsystem", session.Subsystem()), slog.F("raw_command", session.RawCommand()))
if session.Subsystem() == "" { // sftp does not expect error, otherwise it fails with "package too long"
// Response format: <status_code><message body>\n
errorMessage := fmt.Sprintf("\x02%s\n", BlockedFileTransferErrorMessage)
_, _ = session.Write([]byte(errorMessage))
}
_ = session.Exit(BlockedFileTransferErrorCode)
return
}
switch ss := session.Subsystem(); ss {
case "":
case "sftp":
@@ -322,6 +344,37 @@ func (s *Server) sessionHandler(session ssh.Session) {
_ = session.Exit(0)
}
// fileTransferBlocked method checks if the file transfer commands should be blocked.
//
// Warning: consider this mechanism as "Do not trespass" sign, as a violator can still ssh to the host,
// smuggle the `scp` binary, or just manually send files outside with `curl` or `ftp`.
// If a user needs a more sophisticated and battle-proof solution, consider full endpoint security.
func (s *Server) fileTransferBlocked(session ssh.Session) bool {
if !s.config.BlockFileTransfer {
return false // file transfers are permitted
}
// File transfers are restricted.
if session.Subsystem() == "sftp" {
return true
}
cmd := session.Command()
if len(cmd) == 0 {
return false // no command?
}
c := cmd[0]
c = filepath.Base(c) // in case the binary is absolute path, /usr/sbin/scp
for _, cmd := range BlockedFileTransferCommands {
if cmd == c {
return true
}
}
return false
}
func (s *Server) sessionStart(logger slog.Logger, session ssh.Session, extraEnv []string) (retErr error) {
ctx := session.Context()
env := append(session.Environ(), extraEnv...)
+19 -6
View File
@@ -210,7 +210,12 @@ func (f *FakeAgentAPI) UpdateStats(ctx context.Context, req *agentproto.UpdateSt
f.logger.Debug(ctx, "update stats called", slog.F("req", req))
// empty request is sent to get the interval; but our tests don't want empty stats requests
if req.Stats != nil {
f.statsCh <- req.Stats
select {
case <-ctx.Done():
return nil, ctx.Err()
case f.statsCh <- req.Stats:
// OK!
}
}
return &agentproto.UpdateStatsResponse{ReportInterval: durationpb.New(statsInterval)}, nil
}
@@ -233,17 +238,25 @@ func (f *FakeAgentAPI) UpdateLifecycle(_ context.Context, req *agentproto.Update
func (f *FakeAgentAPI) BatchUpdateAppHealths(ctx context.Context, req *agentproto.BatchUpdateAppHealthRequest) (*agentproto.BatchUpdateAppHealthResponse, error) {
f.logger.Debug(ctx, "batch update app health", slog.F("req", req))
f.appHealthCh <- req
return &agentproto.BatchUpdateAppHealthResponse{}, nil
select {
case <-ctx.Done():
return nil, ctx.Err()
case f.appHealthCh <- req:
return &agentproto.BatchUpdateAppHealthResponse{}, nil
}
}
func (f *FakeAgentAPI) AppHealthCh() <-chan *agentproto.BatchUpdateAppHealthRequest {
return f.appHealthCh
}
func (f *FakeAgentAPI) UpdateStartup(_ context.Context, req *agentproto.UpdateStartupRequest) (*agentproto.Startup, error) {
f.startupCh <- req.GetStartup()
return req.GetStartup(), nil
func (f *FakeAgentAPI) UpdateStartup(ctx context.Context, req *agentproto.UpdateStartupRequest) (*agentproto.Startup, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case f.startupCh <- req.GetStartup():
return req.GetStartup(), nil
}
}
func (f *FakeAgentAPI) GetMetadata() map[string]agentsdk.Metadata {
+53 -59
View File
@@ -12,12 +12,9 @@ import (
"cdr.dev/slog"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/retry"
"github.com/coder/quartz"
)
// WorkspaceAgentApps fetches the workspace apps.
type WorkspaceAgentApps func(context.Context) ([]codersdk.WorkspaceApp, error)
// PostWorkspaceAgentAppHealth updates the workspace app health.
type PostWorkspaceAgentAppHealth func(context.Context, agentsdk.PostAppHealthsRequest) error
@@ -26,15 +23,26 @@ type WorkspaceAppHealthReporter func(ctx context.Context)
// NewWorkspaceAppHealthReporter creates a WorkspaceAppHealthReporter that reports app health to coderd.
func NewWorkspaceAppHealthReporter(logger slog.Logger, apps []codersdk.WorkspaceApp, postWorkspaceAgentAppHealth PostWorkspaceAgentAppHealth) WorkspaceAppHealthReporter {
return NewAppHealthReporterWithClock(logger, apps, postWorkspaceAgentAppHealth, quartz.NewReal())
}
// NewAppHealthReporterWithClock is only called directly by test code. Product code should call
// NewAppHealthReporter.
func NewAppHealthReporterWithClock(
logger slog.Logger,
apps []codersdk.WorkspaceApp,
postWorkspaceAgentAppHealth PostWorkspaceAgentAppHealth,
clk quartz.Clock,
) WorkspaceAppHealthReporter {
logger = logger.Named("apphealth")
runHealthcheckLoop := func(ctx context.Context) error {
return func(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// no need to run this loop if no apps for this workspace.
if len(apps) == 0 {
return nil
return
}
hasHealthchecksEnabled := false
@@ -49,7 +57,7 @@ func NewWorkspaceAppHealthReporter(logger slog.Logger, apps []codersdk.Workspace
// no need to run this loop if no health checks are configured.
if !hasHealthchecksEnabled {
return nil
return
}
// run a ticker for each app health check.
@@ -61,25 +69,29 @@ func NewWorkspaceAppHealthReporter(logger slog.Logger, apps []codersdk.Workspace
}
app := nextApp
go func() {
t := time.NewTicker(time.Duration(app.Healthcheck.Interval) * time.Second)
defer t.Stop()
_ = clk.TickerFunc(ctx, time.Duration(app.Healthcheck.Interval)*time.Second, func() error {
// We time out at the healthcheck interval to prevent getting too backed up, but
// set it 1ms early so that it's not simultaneous with the next tick in testing,
// which makes the test easier to understand.
//
// It would be idiomatic to use the http.Client.Timeout or a context.WithTimeout,
// but we are passing this off to the native http library, which is not aware
// of the clock library we are using. That means in testing, with a mock clock
// it will compare mocked times with real times, and we will get strange results.
// So, we just implement the timeout as a context we cancel with an AfterFunc
reqCtx, reqCancel := context.WithCancel(ctx)
timeout := clk.AfterFunc(
time.Duration(app.Healthcheck.Interval)*time.Second-time.Millisecond,
reqCancel,
"timeout", app.Slug)
defer timeout.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
// we set the http timeout to the healthcheck interval to prevent getting too backed up.
client := &http.Client{
Timeout: time.Duration(app.Healthcheck.Interval) * time.Second,
}
err := func() error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, app.Healthcheck.URL, nil)
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, app.Healthcheck.URL, nil)
if err != nil {
return err
}
res, err := client.Do(req)
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
@@ -118,54 +130,36 @@ func NewWorkspaceAppHealthReporter(logger slog.Logger, apps []codersdk.Workspace
mu.Unlock()
logger.Debug(ctx, "workspace app healthy", slog.F("id", app.ID.String()), slog.F("slug", app.Slug))
}
t.Reset(time.Duration(app.Healthcheck.Interval) * time.Second)
}
return nil
}, "healthcheck", app.Slug)
}()
}
mu.Lock()
lastHealth := copyHealth(health)
mu.Unlock()
reportTicker := time.NewTicker(time.Second)
defer reportTicker.Stop()
// every second we check if the health values of the apps have changed
// and if there is a change we will report the new values.
for {
select {
case <-ctx.Done():
reportTicker := clk.TickerFunc(ctx, time.Second, func() error {
mu.RLock()
changed := healthChanged(lastHealth, health)
mu.RUnlock()
if !changed {
return nil
case <-reportTicker.C:
mu.RLock()
changed := healthChanged(lastHealth, health)
mu.RUnlock()
if !changed {
continue
}
mu.Lock()
lastHealth = copyHealth(health)
mu.Unlock()
err := postWorkspaceAgentAppHealth(ctx, agentsdk.PostAppHealthsRequest{
Healths: lastHealth,
})
if err != nil {
logger.Error(ctx, "failed to report workspace app health", slog.Error(err))
} else {
logger.Debug(ctx, "sent workspace app health", slog.F("health", lastHealth))
}
}
}
}
return func(ctx context.Context) {
for r := retry.New(time.Second, 30*time.Second); r.Wait(ctx); {
err := runHealthcheckLoop(ctx)
if err == nil || xerrors.Is(err, context.Canceled) || xerrors.Is(err, context.DeadlineExceeded) {
return
mu.Lock()
lastHealth = copyHealth(health)
mu.Unlock()
err := postWorkspaceAgentAppHealth(ctx, agentsdk.PostAppHealthsRequest{
Healths: lastHealth,
})
if err != nil {
logger.Error(ctx, "failed to report workspace app health", slog.Error(err))
} else {
logger.Debug(ctx, "sent workspace app health", slog.F("health", lastHealth))
}
logger.Error(ctx, "failed running workspace app reporter", slog.Error(err))
}
return nil
}, "report")
_ = reportTicker.Wait() // only possible error is context done
}
}
+154 -113
View File
@@ -4,14 +4,12 @@ import (
"context"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"cdr.dev/slog"
@@ -23,19 +21,22 @@ import (
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/coder/v2/testutil"
"github.com/coder/quartz"
)
func TestAppHealth_Healthy(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
defer cancel()
apps := []codersdk.WorkspaceApp{
{
ID: uuid.UUID{1},
Slug: "app1",
Healthcheck: codersdk.Healthcheck{},
Health: codersdk.WorkspaceAppHealthDisabled,
},
{
ID: uuid.UUID{2},
Slug: "app2",
Healthcheck: codersdk.Healthcheck{
// URL: We don't set the URL for this test because the setup will
@@ -46,6 +47,7 @@ func TestAppHealth_Healthy(t *testing.T) {
Health: codersdk.WorkspaceAppHealthInitializing,
},
{
ID: uuid.UUID{3},
Slug: "app3",
Healthcheck: codersdk.Healthcheck{
Interval: 2,
@@ -54,36 +56,71 @@ func TestAppHealth_Healthy(t *testing.T) {
Health: codersdk.WorkspaceAppHealthInitializing,
},
}
checks2 := 0
checks3 := 0
handlers := []http.Handler{
nil,
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
checks2++
httpapi.Write(r.Context(), w, http.StatusOK, nil)
}),
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
checks3++
httpapi.Write(r.Context(), w, http.StatusOK, nil)
}),
}
getApps, closeFn := setupAppReporter(ctx, t, apps, handlers)
defer closeFn()
apps, err := getApps(ctx)
require.NoError(t, err)
require.EqualValues(t, codersdk.WorkspaceAppHealthDisabled, apps[0].Health)
require.Eventually(t, func() bool {
apps, err := getApps(ctx)
if err != nil {
return false
}
mClock := quartz.NewMock(t)
healthcheckTrap := mClock.Trap().TickerFunc("healthcheck")
defer healthcheckTrap.Close()
reportTrap := mClock.Trap().TickerFunc("report")
defer reportTrap.Close()
return apps[1].Health == codersdk.WorkspaceAppHealthHealthy && apps[2].Health == codersdk.WorkspaceAppHealthHealthy
}, testutil.WaitLong, testutil.IntervalSlow)
fakeAPI, closeFn := setupAppReporter(ctx, t, slices.Clone(apps), handlers, mClock)
defer closeFn()
healthchecksStarted := make([]string, 2)
for i := 0; i < 2; i++ {
c := healthcheckTrap.MustWait(ctx)
c.Release()
healthchecksStarted[i] = c.Tags[1]
}
slices.Sort(healthchecksStarted)
require.Equal(t, []string{"app2", "app3"}, healthchecksStarted)
// advance the clock 1ms before the report ticker starts, so that it's not
// simultaneous with the checks.
mClock.Advance(time.Millisecond).MustWait(ctx)
reportTrap.MustWait(ctx).Release()
mClock.Advance(999 * time.Millisecond).MustWait(ctx) // app2 is now healthy
mClock.Advance(time.Millisecond).MustWait(ctx) // report gets triggered
update := testutil.RequireRecvCtx(ctx, t, fakeAPI.AppHealthCh())
require.Len(t, update.GetUpdates(), 2)
applyUpdate(t, apps, update)
require.Equal(t, codersdk.WorkspaceAppHealthHealthy, apps[1].Health)
require.Equal(t, codersdk.WorkspaceAppHealthInitializing, apps[2].Health)
mClock.Advance(999 * time.Millisecond).MustWait(ctx) // app3 is now healthy
mClock.Advance(time.Millisecond).MustWait(ctx) // report gets triggered
update = testutil.RequireRecvCtx(ctx, t, fakeAPI.AppHealthCh())
require.Len(t, update.GetUpdates(), 2)
applyUpdate(t, apps, update)
require.Equal(t, codersdk.WorkspaceAppHealthHealthy, apps[1].Health)
require.Equal(t, codersdk.WorkspaceAppHealthHealthy, apps[2].Health)
// ensure we aren't spamming
require.Equal(t, 2, checks2)
require.Equal(t, 1, checks3)
}
func TestAppHealth_500(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
defer cancel()
apps := []codersdk.WorkspaceApp{
{
ID: uuid.UUID{2},
Slug: "app2",
Healthcheck: codersdk.Healthcheck{
// URL: We don't set the URL for this test because the setup will
@@ -99,59 +136,40 @@ func TestAppHealth_500(t *testing.T) {
httpapi.Write(r.Context(), w, http.StatusInternalServerError, nil)
}),
}
getApps, closeFn := setupAppReporter(ctx, t, apps, handlers)
defer closeFn()
require.Eventually(t, func() bool {
apps, err := getApps(ctx)
if err != nil {
return false
}
return apps[0].Health == codersdk.WorkspaceAppHealthUnhealthy
}, testutil.WaitLong, testutil.IntervalSlow)
mClock := quartz.NewMock(t)
healthcheckTrap := mClock.Trap().TickerFunc("healthcheck")
defer healthcheckTrap.Close()
reportTrap := mClock.Trap().TickerFunc("report")
defer reportTrap.Close()
fakeAPI, closeFn := setupAppReporter(ctx, t, slices.Clone(apps), handlers, mClock)
defer closeFn()
healthcheckTrap.MustWait(ctx).Release()
// advance the clock 1ms before the report ticker starts, so that it's not
// simultaneous with the checks.
mClock.Advance(time.Millisecond).MustWait(ctx)
reportTrap.MustWait(ctx).Release()
mClock.Advance(999 * time.Millisecond).MustWait(ctx) // check gets triggered
mClock.Advance(time.Millisecond).MustWait(ctx) // report gets triggered, but unsent since we are at the threshold
mClock.Advance(999 * time.Millisecond).MustWait(ctx) // 2nd check, crosses threshold
mClock.Advance(time.Millisecond).MustWait(ctx) // 2nd report, sends update
update := testutil.RequireRecvCtx(ctx, t, fakeAPI.AppHealthCh())
require.Len(t, update.GetUpdates(), 1)
applyUpdate(t, apps, update)
require.Equal(t, codersdk.WorkspaceAppHealthUnhealthy, apps[0].Health)
}
func TestAppHealth_Timeout(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
apps := []codersdk.WorkspaceApp{
{
Slug: "app2",
Healthcheck: codersdk.Healthcheck{
// URL: We don't set the URL for this test because the setup will
// create a httptest server for us and set it for us.
Interval: 1,
Threshold: 1,
},
Health: codersdk.WorkspaceAppHealthInitializing,
},
}
handlers := []http.Handler{
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// sleep longer than the interval to cause the health check to time out
time.Sleep(2 * time.Second)
httpapi.Write(r.Context(), w, http.StatusOK, nil)
}),
}
getApps, closeFn := setupAppReporter(ctx, t, apps, handlers)
defer closeFn()
require.Eventually(t, func() bool {
apps, err := getApps(ctx)
if err != nil {
return false
}
return apps[0].Health == codersdk.WorkspaceAppHealthUnhealthy
}, testutil.WaitLong, testutil.IntervalSlow)
}
func TestAppHealth_NotSpamming(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
defer cancel()
apps := []codersdk.WorkspaceApp{
{
ID: uuid.UUID{2},
Slug: "app2",
Healthcheck: codersdk.Healthcheck{
// URL: We don't set the URL for this test because the setup will
@@ -163,27 +181,65 @@ func TestAppHealth_NotSpamming(t *testing.T) {
},
}
counter := new(int32)
handlers := []http.Handler{
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(counter, 1)
http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
// allow the request to time out
<-r.Context().Done()
}),
}
_, closeFn := setupAppReporter(ctx, t, apps, handlers)
mClock := quartz.NewMock(t)
start := mClock.Now()
// for this test, it's easier to think in the number of milliseconds elapsed
// since start.
ms := func(n int) time.Time {
return start.Add(time.Duration(n) * time.Millisecond)
}
healthcheckTrap := mClock.Trap().TickerFunc("healthcheck")
defer healthcheckTrap.Close()
reportTrap := mClock.Trap().TickerFunc("report")
defer reportTrap.Close()
timeoutTrap := mClock.Trap().AfterFunc("timeout")
defer timeoutTrap.Close()
fakeAPI, closeFn := setupAppReporter(ctx, t, apps, handlers, mClock)
defer closeFn()
// Ensure we haven't made more than 2 (expected 1 + 1 for buffer) requests in the last second.
// if there is a bug where we are spamming the healthcheck route this will catch it.
time.Sleep(time.Second)
require.LessOrEqual(t, atomic.LoadInt32(counter), int32(2))
healthcheckTrap.MustWait(ctx).Release()
// advance the clock 1ms before the report ticker starts, so that it's not
// simultaneous with the checks.
mClock.Set(ms(1)).MustWait(ctx)
reportTrap.MustWait(ctx).Release()
w := mClock.Set(ms(1000)) // 1st check starts
timeoutTrap.MustWait(ctx).Release()
mClock.Set(ms(1001)).MustWait(ctx) // report tick, no change
mClock.Set(ms(1999)) // timeout pops
w.MustWait(ctx) // 1st check finished
w = mClock.Set(ms(2000)) // 2nd check starts
timeoutTrap.MustWait(ctx).Release()
mClock.Set(ms(2001)).MustWait(ctx) // report tick, no change
mClock.Set(ms(2999)) // timeout pops
w.MustWait(ctx) // 2nd check finished
// app is now unhealthy after 2 timeouts
mClock.Set(ms(3000)) // 3rd check starts
timeoutTrap.MustWait(ctx).Release()
mClock.Set(ms(3001)).MustWait(ctx) // report tick, sends changes
update := testutil.RequireRecvCtx(ctx, t, fakeAPI.AppHealthCh())
require.Len(t, update.GetUpdates(), 1)
applyUpdate(t, apps, update)
require.Equal(t, codersdk.WorkspaceAppHealthUnhealthy, apps[0].Health)
}
func setupAppReporter(ctx context.Context, t *testing.T, apps []codersdk.WorkspaceApp, handlers []http.Handler) (agent.WorkspaceAgentApps, func()) {
func setupAppReporter(
ctx context.Context, t *testing.T,
apps []codersdk.WorkspaceApp,
handlers []http.Handler,
clk quartz.Clock,
) (*agenttest.FakeAgentAPI, func()) {
closers := []func(){}
for i, app := range apps {
if app.ID == uuid.Nil {
app.ID = uuid.New()
apps[i] = app
}
for _, app := range apps {
require.NotEqual(t, uuid.Nil, app.ID, "all apps must have ID set")
}
for i, handler := range handlers {
if handler == nil {
@@ -196,14 +252,6 @@ func setupAppReporter(ctx context.Context, t *testing.T, apps []codersdk.Workspa
closers = append(closers, ts.Close)
}
var mu sync.Mutex
workspaceAgentApps := func(context.Context) ([]codersdk.WorkspaceApp, error) {
mu.Lock()
defer mu.Unlock()
var newApps []codersdk.WorkspaceApp
return append(newApps, apps...), nil
}
// We don't care about manifest or stats in this test since it's not using
// a full agent and these RPCs won't get called.
//
@@ -212,38 +260,31 @@ func setupAppReporter(ctx context.Context, t *testing.T, apps []codersdk.Workspa
// post function.
fakeAAPI := agenttest.NewFakeAgentAPI(t, slogtest.Make(t, nil), nil, nil)
// Process events from the channel and update the health of the apps.
go func() {
appHealthCh := fakeAAPI.AppHealthCh()
for {
select {
case <-ctx.Done():
return
case req := <-appHealthCh:
mu.Lock()
for _, update := range req.Updates {
updateID, err := uuid.FromBytes(update.Id)
assert.NoError(t, err)
updateHealth := codersdk.WorkspaceAppHealth(strings.ToLower(proto.AppHealth_name[int32(update.Health)]))
go agent.NewAppHealthReporterWithClock(
slogtest.Make(t, nil).Leveled(slog.LevelDebug),
apps, agentsdk.AppHealthPoster(fakeAAPI), clk,
)(ctx)
for i, app := range apps {
if app.ID != updateID {
continue
}
app.Health = updateHealth
apps[i] = app
}
}
mu.Unlock()
}
}
}()
go agent.NewWorkspaceAppHealthReporter(slogtest.Make(t, nil).Leveled(slog.LevelDebug), apps, agentsdk.AppHealthPoster(fakeAAPI))(ctx)
return workspaceAgentApps, func() {
return fakeAAPI, func() {
for _, closeFn := range closers {
closeFn()
}
}
}
func applyUpdate(t *testing.T, apps []codersdk.WorkspaceApp, req *proto.BatchUpdateAppHealthRequest) {
t.Helper()
for _, update := range req.Updates {
updateID, err := uuid.FromBytes(update.Id)
require.NoError(t, err)
updateHealth := codersdk.WorkspaceAppHealth(strings.ToLower(proto.AppHealth_name[int32(update.Health)]))
for i, app := range apps {
if app.ID != updateID {
continue
}
app.Health = updateHealth
apps[i] = app
}
}
}
+38
View File
@@ -0,0 +1,38 @@
package proto
import (
"context"
"storj.io/drpc"
)
// DRPCAgentClient20 is the Agent API at v2.0. Notably, it is missing GetAnnouncementBanners, but
// is useful when you want to be maximally compatible with Coderd Release Versions from 2.9+
type DRPCAgentClient20 interface {
DRPCConn() drpc.Conn
GetManifest(ctx context.Context, in *GetManifestRequest) (*Manifest, error)
GetServiceBanner(ctx context.Context, in *GetServiceBannerRequest) (*ServiceBanner, error)
UpdateStats(ctx context.Context, in *UpdateStatsRequest) (*UpdateStatsResponse, error)
UpdateLifecycle(ctx context.Context, in *UpdateLifecycleRequest) (*Lifecycle, error)
BatchUpdateAppHealths(ctx context.Context, in *BatchUpdateAppHealthRequest) (*BatchUpdateAppHealthResponse, error)
UpdateStartup(ctx context.Context, in *UpdateStartupRequest) (*Startup, error)
BatchUpdateMetadata(ctx context.Context, in *BatchUpdateMetadataRequest) (*BatchUpdateMetadataResponse, error)
BatchCreateLogs(ctx context.Context, in *BatchCreateLogsRequest) (*BatchCreateLogsResponse, error)
}
// DRPCAgentClient21 is the Agent API at v2.1. It is useful if you want to be maximally compatible
// with Coderd Release Versions from 2.12+
type DRPCAgentClient21 interface {
DRPCConn() drpc.Conn
GetManifest(ctx context.Context, in *GetManifestRequest) (*Manifest, error)
GetServiceBanner(ctx context.Context, in *GetServiceBannerRequest) (*ServiceBanner, error)
UpdateStats(ctx context.Context, in *UpdateStatsRequest) (*UpdateStatsResponse, error)
UpdateLifecycle(ctx context.Context, in *UpdateLifecycleRequest) (*Lifecycle, error)
BatchUpdateAppHealths(ctx context.Context, in *BatchUpdateAppHealthRequest) (*BatchUpdateAppHealthResponse, error)
UpdateStartup(ctx context.Context, in *UpdateStartupRequest) (*Startup, error)
BatchUpdateMetadata(ctx context.Context, in *BatchUpdateMetadataRequest) (*BatchUpdateMetadataResponse, error)
BatchCreateLogs(ctx context.Context, in *BatchCreateLogsRequest) (*BatchCreateLogsResponse, error)
GetAnnouncementBanners(ctx context.Context, in *GetAnnouncementBannersRequest) (*GetAnnouncementBannersResponse, error)
}
+1 -1
View File
@@ -26,7 +26,7 @@ type APIVersion struct {
}
func (v *APIVersion) WithBackwardCompat(majs ...int) *APIVersion {
v.additionalMajors = append(v.additionalMajors, majs[:]...)
v.additionalMajors = append(v.additionalMajors, majs...)
return v
}
+11
View File
@@ -27,6 +27,7 @@ import (
"cdr.dev/slog/sloggers/slogstackdriver"
"github.com/coder/coder/v2/agent"
"github.com/coder/coder/v2/agent/agentproc"
"github.com/coder/coder/v2/agent/agentssh"
"github.com/coder/coder/v2/agent/reaper"
"github.com/coder/coder/v2/buildinfo"
"github.com/coder/coder/v2/codersdk"
@@ -48,6 +49,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
slogHumanPath string
slogJSONPath string
slogStackdriverPath string
blockFileTransfer bool
)
cmd := &serpent.Command{
Use: "agent",
@@ -314,6 +316,8 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
// Intentionally set this to nil. It's mainly used
// for testing.
ModifiedProcesses: nil,
BlockFileTransfer: blockFileTransfer,
})
promHandler := agent.PrometheusMetricsHandler(prometheusRegistry, logger)
@@ -417,6 +421,13 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
Default: "",
Value: serpent.StringOf(&slogStackdriverPath),
},
{
Flag: "block-file-transfer",
Default: "false",
Env: "CODER_AGENT_BLOCK_FILE_TRANSFER",
Description: fmt.Sprintf("Block file transfer using known applications: %s.", strings.Join(agentssh.BlockedFileTransferCommands, ",")),
Value: serpent.BoolOf(&blockFileTransfer),
},
}
return cmd
+1 -1
View File
@@ -24,7 +24,7 @@ func TestAutoUpdate(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
require.Equal(t, codersdk.AutomaticUpdatesNever, workspace.AutomaticUpdates)
+1 -1
View File
@@ -195,7 +195,7 @@ func prepareTestData(t *testing.T) (*codersdk.Client, map[string]string) {
template := coderdtest.CreateTemplate(t, rootClient, firstUser.OrganizationID, version.ID, func(req *codersdk.CreateTemplateRequest) {
req.Name = "test-template"
})
workspace := coderdtest.CreateWorkspace(t, rootClient, firstUser.OrganizationID, template.ID, func(req *codersdk.CreateWorkspaceRequest) {
workspace := coderdtest.CreateWorkspace(t, rootClient, template.ID, func(req *codersdk.CreateWorkspaceRequest) {
req.Name = "test-workspace"
})
workspaceBuild := coderdtest.AwaitWorkspaceBuildJobCompleted(t, rootClient, workspace.LatestBuild.ID)
+15 -6
View File
@@ -116,7 +116,7 @@ func Agent(ctx context.Context, writer io.Writer, agentID uuid.UUID, opts AgentO
if agent.Status == codersdk.WorkspaceAgentTimeout {
now := time.Now()
sw.Log(now, codersdk.LogLevelInfo, "The workspace agent is having trouble connecting, wait for it to connect or restart your workspace.")
sw.Log(now, codersdk.LogLevelInfo, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates#agent-connection-issues"))
sw.Log(now, codersdk.LogLevelInfo, troubleshootingMessage(agent, "https://coder.com/docs/templates#agent-connection-issues"))
for agent.Status == codersdk.WorkspaceAgentTimeout {
if agent, err = fetch(); err != nil {
return xerrors.Errorf("fetch: %w", err)
@@ -132,11 +132,14 @@ func Agent(ctx context.Context, writer io.Writer, agentID uuid.UUID, opts AgentO
}
stage := "Running workspace agent startup scripts"
follow := opts.Wait
follow := opts.Wait && agent.LifecycleState.Starting()
if !follow {
stage += " (non-blocking)"
}
sw.Start(stage)
if follow {
sw.Log(time.Time{}, codersdk.LogLevelInfo, "==> ︎ To connect immediately, reconnect with --wait=no or CODER_SSH_WAIT=no, see --help for more information.")
}
err = func() error { // Use func because of defer in for loop.
logStream, logsCloser, err := opts.FetchLogs(ctx, agent.ID, 0, follow)
@@ -206,19 +209,25 @@ func Agent(ctx context.Context, writer io.Writer, agentID uuid.UUID, opts AgentO
case codersdk.WorkspaceAgentLifecycleReady:
sw.Complete(stage, safeDuration(sw, agent.ReadyAt, agent.StartedAt))
case codersdk.WorkspaceAgentLifecycleStartTimeout:
sw.Fail(stage, 0)
// Backwards compatibility: Avoid printing warning if
// coderd is old and doesn't set ReadyAt for timeouts.
if agent.ReadyAt == nil {
sw.Fail(stage, 0)
} else {
sw.Fail(stage, safeDuration(sw, agent.ReadyAt, agent.StartedAt))
}
sw.Log(time.Time{}, codersdk.LogLevelWarn, "Warning: A startup script timed out and your workspace may be incomplete.")
case codersdk.WorkspaceAgentLifecycleStartError:
sw.Fail(stage, safeDuration(sw, agent.ReadyAt, agent.StartedAt))
// Use zero time (omitted) to separate these from the startup logs.
sw.Log(time.Time{}, codersdk.LogLevelWarn, "Warning: A startup script exited with an error and your workspace may be incomplete.")
sw.Log(time.Time{}, codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates/troubleshooting#startup-script-exited-with-an-error"))
sw.Log(time.Time{}, codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/templates/troubleshooting#startup-script-exited-with-an-error"))
default:
switch {
case agent.LifecycleState.Starting():
// Use zero time (omitted) to separate these from the startup logs.
sw.Log(time.Time{}, codersdk.LogLevelWarn, "Notice: The startup scripts are still running and your workspace may be incomplete.")
sw.Log(time.Time{}, codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates/troubleshooting#your-workspace-may-be-incomplete"))
sw.Log(time.Time{}, codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/templates/troubleshooting#your-workspace-may-be-incomplete"))
// Note: We don't complete or fail the stage here, it's
// intentionally left open to indicate this stage didn't
// complete.
@@ -240,7 +249,7 @@ func Agent(ctx context.Context, writer io.Writer, agentID uuid.UUID, opts AgentO
stage := "The workspace agent lost connection"
sw.Start(stage)
sw.Log(time.Now(), codersdk.LogLevelWarn, "Wait for it to reconnect or restart your workspace.")
sw.Log(time.Now(), codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/v2/latest/templates/troubleshooting#agent-connection-issues"))
sw.Log(time.Now(), codersdk.LogLevelWarn, troubleshootingMessage(agent, "https://coder.com/docs/templates/troubleshooting#agent-connection-issues"))
disconnectedAt := agent.DisconnectedAt
for agent.Status == codersdk.WorkspaceAgentDisconnected {
+7 -2
View File
@@ -95,6 +95,8 @@ func TestAgent(t *testing.T) {
iter: []func(context.Context, *testing.T, *codersdk.WorkspaceAgent, <-chan string, chan []codersdk.WorkspaceAgentLog) error{
func(_ context.Context, _ *testing.T, agent *codersdk.WorkspaceAgent, _ <-chan string, _ chan []codersdk.WorkspaceAgentLog) error {
agent.Status = codersdk.WorkspaceAgentConnecting
agent.LifecycleState = codersdk.WorkspaceAgentLifecycleStarting
agent.StartedAt = ptr.Ref(time.Now())
return nil
},
func(_ context.Context, t *testing.T, agent *codersdk.WorkspaceAgent, output <-chan string, _ chan []codersdk.WorkspaceAgentLog) error {
@@ -104,6 +106,7 @@ func TestAgent(t *testing.T) {
agent.Status = codersdk.WorkspaceAgentConnected
agent.LifecycleState = codersdk.WorkspaceAgentLifecycleStartTimeout
agent.FirstConnectedAt = ptr.Ref(time.Now())
agent.ReadyAt = ptr.Ref(time.Now())
return nil
},
},
@@ -226,6 +229,7 @@ func TestAgent(t *testing.T) {
},
want: []string{
"⧗ Running workspace agent startup scripts",
"︎ To connect immediately, reconnect with --wait=no or CODER_SSH_WAIT=no, see --help for more information.",
"testing: Hello world",
"Bye now",
"✔ Running workspace agent startup scripts",
@@ -254,9 +258,9 @@ func TestAgent(t *testing.T) {
},
},
want: []string{
"⧗ Running workspace agent startup scripts",
"⧗ Running workspace agent startup scripts (non-blocking)",
"Hello world",
"✘ Running workspace agent startup scripts",
"✘ Running workspace agent startup scripts (non-blocking)",
"Warning: A startup script exited with an error and your workspace may be incomplete.",
"For more information and troubleshooting, see",
},
@@ -306,6 +310,7 @@ func TestAgent(t *testing.T) {
},
want: []string{
"⧗ Running workspace agent startup scripts",
"︎ To connect immediately, reconnect with --wait=no or CODER_SSH_WAIT=no, see --help for more information.",
"Hello world",
"✔ Running workspace agent startup scripts",
},
+6 -1
View File
@@ -7,6 +7,7 @@ import (
"reflect"
"strings"
"github.com/jedib0t/go-pretty/v6/table"
"golang.org/x/xerrors"
"github.com/coder/serpent"
@@ -143,7 +144,11 @@ func (f *tableFormat) AttachOptions(opts *serpent.OptionSet) {
// Format implements OutputFormat.
func (f *tableFormat) Format(_ context.Context, data any) (string, error) {
return DisplayTable(data, f.sort, f.columns)
headers := make(table.Row, len(f.allColumns))
for i, header := range f.allColumns {
headers[i] = header
}
return renderTable(data, f.sort, headers, f.columns)
}
type jsonFormat struct{}
+4 -1
View File
@@ -43,7 +43,10 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
return "", err
}
values, err := MultiSelect(inv, options)
values, err := MultiSelect(inv, MultiSelectOptions{
Options: options,
Defaults: options,
})
if err == nil {
v, err := json.Marshal(&values)
if err != nil {
+13 -42
View File
@@ -14,48 +14,11 @@ import (
"github.com/coder/serpent"
)
func init() {
survey.SelectQuestionTemplate = `
{{- define "option"}}
{{- " " }}{{- if eq .SelectedIndex .CurrentIndex }}{{color "green" }}{{ .Config.Icons.SelectFocus.Text }} {{else}}{{color "default"}} {{end}}
{{- .CurrentOpt.Value}}
{{- color "reset"}}
{{end}}
{{- if not .ShowAnswer }}
{{- if .Config.Icons.Help.Text }}
{{- if .FilterMessage }}{{ "Search:" }}{{ .FilterMessage }}
{{- else }}
{{- color "black+h"}}{{- "Type to search" }}{{color "reset"}}
{{- end }}
{{- "\n" }}
{{- end }}
{{- "\n" }}
{{- range $ix, $option := .PageEntries}}
{{- template "option" $.IterateOption $ix $option}}
{{- end}}
{{- end }}`
survey.MultiSelectQuestionTemplate = `
{{- define "option"}}
{{- if eq .SelectedIndex .CurrentIndex }}{{color .Config.Icons.SelectFocus.Format }}{{ .Config.Icons.SelectFocus.Text }}{{color "reset"}}{{else}} {{end}}
{{- if index .Checked .CurrentOpt.Index }}{{color .Config.Icons.MarkedOption.Format }} {{ .Config.Icons.MarkedOption.Text }} {{else}}{{color .Config.Icons.UnmarkedOption.Format }} {{ .Config.Icons.UnmarkedOption.Text }} {{end}}
{{- color "reset"}}
{{- " "}}{{- .CurrentOpt.Value}}
{{end}}
{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}}
{{- if not .ShowAnswer }}
{{- "\n"}}
{{- range $ix, $option := .PageEntries}}
{{- template "option" $.IterateOption $ix $option}}
{{- end}}
{{- end}}`
}
type SelectOptions struct {
Options []string
// Default will be highlighted first if it's a valid option.
Default string
Message string
Size int
HideSearch bool
}
@@ -122,6 +85,7 @@ func Select(inv *serpent.Invocation, opts SelectOptions) (string, error) {
Options: opts.Options,
Default: defaultOption,
PageSize: opts.Size,
Message: opts.Message,
}, &value, survey.WithIcons(func(is *survey.IconSet) {
is.Help.Text = "Type to search"
if opts.HideSearch {
@@ -138,15 +102,22 @@ func Select(inv *serpent.Invocation, opts SelectOptions) (string, error) {
return value, err
}
func MultiSelect(inv *serpent.Invocation, items []string) ([]string, error) {
type MultiSelectOptions struct {
Message string
Options []string
Defaults []string
}
func MultiSelect(inv *serpent.Invocation, opts MultiSelectOptions) ([]string, error) {
// Similar hack is applied to Select()
if flag.Lookup("test.v") != nil {
return items, nil
return opts.Defaults, nil
}
prompt := &survey.MultiSelect{
Options: items,
Default: items,
Options: opts.Options,
Default: opts.Defaults,
Message: opts.Message,
}
var values []string
+4 -1
View File
@@ -107,7 +107,10 @@ func newMultiSelect(ptty *ptytest.PTY, items []string) ([]string, error) {
var values []string
cmd := &serpent.Command{
Handler: func(inv *serpent.Invocation) error {
selectedItems, err := cliui.MultiSelect(inv, items)
selectedItems, err := cliui.MultiSelect(inv, cliui.MultiSelectOptions{
Options: items,
Defaults: items,
})
if err == nil {
values = selectedItems
}
+74 -18
View File
@@ -22,6 +22,13 @@ func Table() table.Writer {
return tableWriter
}
// This type can be supplied as part of a slice to DisplayTable
// or to a `TableFormat` `Format` call to render a separator.
// Leading separators are not supported and trailing separators
// are ignored by the table formatter.
// e.g. `[]any{someRow, TableSeparator, someRow}`
type TableSeparator struct{}
// filterTableColumns returns configurations to hide columns
// that are not provided in the array. If the array is empty,
// no filtering will occur!
@@ -47,8 +54,12 @@ func filterTableColumns(header table.Row, columns []string) []table.ColumnConfig
return columnConfigs
}
// DisplayTable renders a table as a string. The input argument must be a slice
// of structs. At least one field in the struct must have a `table:""` tag
// DisplayTable renders a table as a string. The input argument can be:
// - a struct slice.
// - an interface slice, where the first element is a struct,
// and all other elements are of the same type, or a TableSeparator.
//
// At least one field in the struct must have a `table:""` tag
// containing the name of the column in the outputted table.
//
// If `sort` is not specified, the field with the `table:"$NAME,default_sort"`
@@ -66,11 +77,20 @@ func DisplayTable(out any, sort string, filterColumns []string) (string, error)
v := reflect.Indirect(reflect.ValueOf(out))
if v.Kind() != reflect.Slice {
return "", xerrors.Errorf("DisplayTable called with a non-slice type")
return "", xerrors.New("DisplayTable called with a non-slice type")
}
var tableType reflect.Type
if v.Type().Elem().Kind() == reflect.Interface {
if v.Len() == 0 {
return "", xerrors.New("DisplayTable called with empty interface slice")
}
tableType = reflect.Indirect(reflect.ValueOf(v.Index(0).Interface())).Type()
} else {
tableType = v.Type().Elem()
}
// Get the list of table column headers.
headersRaw, defaultSort, err := typeToTableHeaders(v.Type().Elem(), true)
headersRaw, defaultSort, err := typeToTableHeaders(tableType, true)
if err != nil {
return "", xerrors.Errorf("get table headers recursively for type %q: %w", v.Type().Elem().String(), err)
}
@@ -82,9 +102,8 @@ func DisplayTable(out any, sort string, filterColumns []string) (string, error)
}
headers := make(table.Row, len(headersRaw))
for i, header := range headersRaw {
headers[i] = header
headers[i] = strings.ReplaceAll(header, "_", " ")
}
// Verify that the given sort column and filter columns are valid.
if sort != "" || len(filterColumns) != 0 {
headersMap := make(map[string]string, len(headersRaw))
@@ -130,6 +149,11 @@ func DisplayTable(out any, sort string, filterColumns []string) (string, error)
return "", xerrors.Errorf("specified sort column %q not found in table headers, available columns are %q", sort, strings.Join(headersRaw, `", "`))
}
}
return renderTable(out, sort, headers, filterColumns)
}
func renderTable(out any, sort string, headers table.Row, filterColumns []string) (string, error) {
v := reflect.Indirect(reflect.ValueOf(out))
// Setup the table formatter.
tw := Table()
@@ -143,15 +167,22 @@ func DisplayTable(out any, sort string, filterColumns []string) (string, error)
// Write each struct to the table.
for i := 0; i < v.Len(); i++ {
cur := v.Index(i).Interface()
_, ok := cur.(TableSeparator)
if ok {
tw.AppendSeparator()
continue
}
// Format the row as a slice.
rowMap, err := valueToTableMap(v.Index(i))
// ValueToTableMap does what `reflect.Indirect` does
rowMap, err := valueToTableMap(reflect.ValueOf(cur))
if err != nil {
return "", xerrors.Errorf("get table row map %v: %w", i, err)
}
rowSlice := make([]any, len(headers))
for i, h := range headersRaw {
v, ok := rowMap[h]
for i, h := range headers {
v, ok := rowMap[h.(string)]
if !ok {
v = nil
}
@@ -174,6 +205,24 @@ func DisplayTable(out any, sort string, filterColumns []string) (string, error)
}
}
// Guard against nil dereferences
if v != nil {
rt := reflect.TypeOf(v)
switch rt.Kind() {
case reflect.Slice:
// By default, the behavior is '%v', which just returns a string like
// '[a b c]'. This will add commas in between each value.
strs := make([]string, 0)
vt := reflect.ValueOf(v)
for i := 0; i < vt.Len(); i++ {
strs = append(strs, fmt.Sprintf("%v", vt.Index(i).Interface()))
}
v = "[" + strings.Join(strs, ", ") + "]"
default:
// Leave it as it is
}
}
rowSlice[i] = v
}
@@ -188,25 +237,28 @@ func DisplayTable(out any, sort string, filterColumns []string) (string, error)
// returned. If the table tag is malformed, an error is returned.
//
// The returned name is transformed from "snake_case" to "normal text".
func parseTableStructTag(field reflect.StructField) (name string, defaultSort, recursive bool, skipParentName bool, err error) {
func parseTableStructTag(field reflect.StructField) (name string, defaultSort, noSortOpt, recursive, skipParentName bool, err error) {
tags, err := structtag.Parse(string(field.Tag))
if err != nil {
return "", false, false, false, xerrors.Errorf("parse struct field tag %q: %w", string(field.Tag), err)
return "", false, false, false, false, xerrors.Errorf("parse struct field tag %q: %w", string(field.Tag), err)
}
tag, err := tags.Get("table")
if err != nil || tag.Name == "-" {
// tags.Get only returns an error if the tag is not found.
return "", false, false, false, nil
return "", false, false, false, false, nil
}
defaultSortOpt := false
noSortOpt = false
recursiveOpt := false
skipParentNameOpt := false
for _, opt := range tag.Options {
switch opt {
case "default_sort":
defaultSortOpt = true
case "nosort":
noSortOpt = true
case "recursive":
recursiveOpt = true
case "recursive_inline":
@@ -216,11 +268,11 @@ func parseTableStructTag(field reflect.StructField) (name string, defaultSort, r
recursiveOpt = true
skipParentNameOpt = true
default:
return "", false, false, false, xerrors.Errorf("unknown option %q in struct field tag", opt)
return "", false, false, false, false, xerrors.Errorf("unknown option %q in struct field tag", opt)
}
}
return strings.ReplaceAll(tag.Name, "_", " "), defaultSortOpt, recursiveOpt, skipParentNameOpt, nil
return strings.ReplaceAll(tag.Name, "_", " "), defaultSortOpt, noSortOpt, recursiveOpt, skipParentNameOpt, nil
}
func isStructOrStructPointer(t reflect.Type) bool {
@@ -244,12 +296,16 @@ func typeToTableHeaders(t reflect.Type, requireDefault bool) ([]string, string,
headers := []string{}
defaultSortName := ""
noSortOpt := false
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
name, defaultSort, recursive, skip, err := parseTableStructTag(field)
name, defaultSort, noSort, recursive, skip, err := parseTableStructTag(field)
if err != nil {
return nil, "", xerrors.Errorf("parse struct tags for field %q in type %q: %w", field.Name, t.String(), err)
}
if requireDefault && noSort {
noSortOpt = true
}
if name == "" && (recursive && skip) {
return nil, "", xerrors.Errorf("a name is required for the field %q. "+
@@ -292,8 +348,8 @@ func typeToTableHeaders(t reflect.Type, requireDefault bool) ([]string, string,
headers = append(headers, name)
}
if defaultSortName == "" && requireDefault {
return nil, "", xerrors.Errorf("no field marked as default_sort in type %q", t.String())
if defaultSortName == "" && requireDefault && !noSortOpt {
return nil, "", xerrors.Errorf("no field marked as default_sort or nosort in type %q", t.String())
}
return headers, defaultSortName, nil
@@ -320,7 +376,7 @@ func valueToTableMap(val reflect.Value) (map[string]any, error) {
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
fieldVal := val.Field(i)
name, _, recursive, skip, err := parseTableStructTag(field)
name, _, _, recursive, skip, err := parseTableStructTag(field)
if err != nil {
return nil, xerrors.Errorf("parse struct tags for field %q in type %T: %w", field.Name, val, err)
}
+44 -16
View File
@@ -138,10 +138,10 @@ func Test_DisplayTable(t *testing.T) {
t.Parallel()
expected := `
NAME AGE ROLES SUB 1 NAME SUB 1 AGE SUB 2 NAME SUB 2 AGE SUB 3 INNER NAME SUB 3 INNER AGE SUB 4 TIME TIME PTR
bar 20 [a] bar1 21 <nil> <nil> bar3 23 {bar4 24 } 2022-08-02T15:49:10Z <nil>
baz 30 [] baz1 31 <nil> <nil> baz3 33 {baz4 34 } 2022-08-02T15:49:10Z <nil>
foo 10 [a b c] foo1 11 foo2 12 foo3 13 {foo4 14 } 2022-08-02T15:49:10Z 2022-08-02T15:49:10Z
NAME AGE ROLES SUB 1 NAME SUB 1 AGE SUB 2 NAME SUB 2 AGE SUB 3 INNER NAME SUB 3 INNER AGE SUB 4 TIME TIME PTR
bar 20 [a] bar1 21 <nil> <nil> bar3 23 {bar4 24 } 2022-08-02T15:49:10Z <nil>
baz 30 [] baz1 31 <nil> <nil> baz3 33 {baz4 34 } 2022-08-02T15:49:10Z <nil>
foo 10 [a, b, c] foo1 11 foo2 12 foo3 13 {foo4 14 } 2022-08-02T15:49:10Z 2022-08-02T15:49:10Z
`
// Test with non-pointer values.
@@ -165,10 +165,10 @@ foo 10 [a b c] foo1 11 foo2 12 foo3
t.Parallel()
expected := `
NAME AGE ROLES SUB 1 NAME SUB 1 AGE SUB 2 NAME SUB 2 AGE SUB 3 INNER NAME SUB 3 INNER AGE SUB 4 TIME TIME PTR
foo 10 [a b c] foo1 11 foo2 12 foo3 13 {foo4 14 } 2022-08-02T15:49:10Z 2022-08-02T15:49:10Z
bar 20 [a] bar1 21 <nil> <nil> bar3 23 {bar4 24 } 2022-08-02T15:49:10Z <nil>
baz 30 [] baz1 31 <nil> <nil> baz3 33 {baz4 34 } 2022-08-02T15:49:10Z <nil>
NAME AGE ROLES SUB 1 NAME SUB 1 AGE SUB 2 NAME SUB 2 AGE SUB 3 INNER NAME SUB 3 INNER AGE SUB 4 TIME TIME PTR
foo 10 [a, b, c] foo1 11 foo2 12 foo3 13 {foo4 14 } 2022-08-02T15:49:10Z 2022-08-02T15:49:10Z
bar 20 [a] bar1 21 <nil> <nil> bar3 23 {bar4 24 } 2022-08-02T15:49:10Z <nil>
baz 30 [] baz1 31 <nil> <nil> baz3 33 {baz4 34 } 2022-08-02T15:49:10Z <nil>
`
out, err := cliui.DisplayTable(in, "age", nil)
@@ -218,6 +218,42 @@ Alice 25
compareTables(t, expected, out)
})
// This test ensures we can display dynamically typed slices
t.Run("Interfaces", func(t *testing.T) {
t.Parallel()
in := []any{tableTest1{}}
out, err := cliui.DisplayTable(in, "", nil)
t.Log("rendered table:\n" + out)
require.NoError(t, err)
other := []tableTest1{{}}
expected, err := cliui.DisplayTable(other, "", nil)
require.NoError(t, err)
compareTables(t, expected, out)
})
t.Run("WithSeparator", func(t *testing.T) {
t.Parallel()
expected := `
NAME AGE ROLES SUB 1 NAME SUB 1 AGE SUB 2 NAME SUB 2 AGE SUB 3 INNER NAME SUB 3 INNER AGE SUB 4 TIME TIME PTR
bar 20 [a] bar1 21 <nil> <nil> bar3 23 {bar4 24 } 2022-08-02T15:49:10Z <nil>
---------------------------------------------------------------------------------------------------------------------------------------------------------------
baz 30 [] baz1 31 <nil> <nil> baz3 33 {baz4 34 } 2022-08-02T15:49:10Z <nil>
---------------------------------------------------------------------------------------------------------------------------------------------------------------
foo 10 [a, b, c] foo1 11 foo2 12 foo3 13 {foo4 14 } 2022-08-02T15:49:10Z 2022-08-02T15:49:10Z
`
var inlineIn []any
for _, v := range in {
inlineIn = append(inlineIn, v)
inlineIn = append(inlineIn, cliui.TableSeparator{})
}
out, err := cliui.DisplayTable(inlineIn, "", nil)
t.Log("rendered table:\n" + out)
require.NoError(t, err)
compareTables(t, expected, out)
})
// This test ensures that safeties against invalid use of `table` tags
// causes errors (even without data).
t.Run("Errors", func(t *testing.T) {
@@ -255,14 +291,6 @@ Alice 25
_, err := cliui.DisplayTable(in, "", nil)
require.Error(t, err)
})
t.Run("WithData", func(t *testing.T) {
t.Parallel()
in := []any{tableTest1{}}
_, err := cliui.DisplayTable(in, "", nil)
require.Error(t, err)
})
})
t.Run("NotStruct", func(t *testing.T) {
+37 -34
View File
@@ -54,6 +54,7 @@ type sshConfigOptions struct {
disableAutostart bool
header []string
headerCommand string
removedKeys map[string]bool
}
// addOptions expects options in the form of "option=value" or "option value".
@@ -74,30 +75,20 @@ func (o *sshConfigOptions) addOption(option string) error {
if err != nil {
return err
}
for i, existing := range o.sshOptions {
// Override existing option if they share the same key.
// This is case-insensitive. Parsing each time might be a little slow,
// but it is ok.
existingKey, _, err := codersdk.ParseSSHConfigOption(existing)
if err != nil {
// Don't mess with original values if there is an error.
// This could have come from the user's manual edits.
continue
}
if strings.EqualFold(existingKey, key) {
if value == "" {
// Delete existing option.
o.sshOptions = append(o.sshOptions[:i], o.sshOptions[i+1:]...)
} else {
// Override existing option.
o.sshOptions[i] = option
}
return nil
}
lowerKey := strings.ToLower(key)
if o.removedKeys != nil && o.removedKeys[lowerKey] {
// Key marked as removed, skip.
return nil
}
// Only append the option if it is not empty.
// Only append the option if it is not empty
// (we interpret empty as removal).
if value != "" {
o.sshOptions = append(o.sshOptions, option)
} else {
if o.removedKeys == nil {
o.removedKeys = make(map[string]bool)
}
o.removedKeys[lowerKey] = true
}
return nil
}
@@ -245,6 +236,8 @@ func (r *RootCmd) configSSH() *serpent.Command {
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
if sshConfigOpts.waitEnum != "auto" && skipProxyCommand {
// The wait option is applied to the ProxyCommand. If the user
// specifies skip-proxy-command, then wait cannot be applied.
@@ -253,7 +246,14 @@ func (r *RootCmd) configSSH() *serpent.Command {
sshConfigOpts.header = r.header
sshConfigOpts.headerCommand = r.headerCommand
recvWorkspaceConfigs := sshPrepareWorkspaceConfigs(inv.Context(), client)
// Talk to the API early to prevent the version mismatch
// warning from being printed in the middle of a prompt.
// This is needed because the asynchronous requests issued
// by sshPrepareWorkspaceConfigs may otherwise trigger the
// warning at any time.
_, _ = client.BuildInfo(ctx)
recvWorkspaceConfigs := sshPrepareWorkspaceConfigs(ctx, client)
out := inv.Stdout
if dryRun {
@@ -375,7 +375,7 @@ func (r *RootCmd) configSSH() *serpent.Command {
return xerrors.Errorf("fetch workspace configs failed: %w", err)
}
coderdConfig, err := client.SSHConfiguration(inv.Context())
coderdConfig, err := client.SSHConfiguration(ctx)
if err != nil {
// If the error is 404, this deployment does not support
// this endpoint yet. Do not error, just assume defaults.
@@ -440,13 +440,17 @@ func (r *RootCmd) configSSH() *serpent.Command {
configOptions := sshConfigOpts
configOptions.sshOptions = nil
// Add standard options.
err := configOptions.addOptions(defaultOptions...)
if err != nil {
return err
// User options first (SSH only uses the first
// option unless it can be given multiple times)
for _, opt := range sshConfigOpts.sshOptions {
err := configOptions.addOptions(opt)
if err != nil {
return xerrors.Errorf("add flag config option %q: %w", opt, err)
}
}
// Override with deployment options
// Deployment options second, allow them to
// override standard options.
for k, v := range coderdConfig.SSHConfigOptions {
opt := fmt.Sprintf("%s %s", k, v)
err := configOptions.addOptions(opt)
@@ -454,12 +458,11 @@ func (r *RootCmd) configSSH() *serpent.Command {
return xerrors.Errorf("add coderd config option %q: %w", opt, err)
}
}
// Override with flag options
for _, opt := range sshConfigOpts.sshOptions {
err := configOptions.addOptions(opt)
if err != nil {
return xerrors.Errorf("add flag config option %q: %w", opt, err)
}
// Finally, add the standard options.
err := configOptions.addOptions(defaultOptions...)
if err != nil {
return err
}
hostBlock := []string{
+4 -4
View File
@@ -272,24 +272,25 @@ func Test_sshConfigOptions_addOption(t *testing.T) {
},
},
{
Name: "Replace",
Name: "AddTwo",
Start: []string{
"foo bar",
},
Add: []string{"Foo baz"},
Expect: []string{
"foo bar",
"Foo baz",
},
},
{
Name: "AddAndReplace",
Name: "AddAndRemove",
Start: []string{
"a b",
"foo bar",
"buzz bazz",
},
Add: []string{
"b c",
"a ", // Empty value, means remove all following entries that start with "a", i.e. next line.
"A hello",
"hello world",
},
@@ -297,7 +298,6 @@ func Test_sshConfigOptions_addOption(t *testing.T) {
"foo bar",
"buzz bazz",
"b c",
"A hello",
"hello world",
},
},
+14 -1
View File
@@ -65,7 +65,7 @@ func TestConfigSSH(t *testing.T) {
const hostname = "test-coder."
const expectedKey = "ConnectionAttempts"
const removeKey = "ConnectionTimeout"
const removeKey = "ConnectTimeout"
client, db := coderdtest.NewWithDatabase(t, &coderdtest.Options{
ConfigSSH: codersdk.SSHConfigResponse{
HostnamePrefix: hostname,
@@ -620,6 +620,19 @@ func TestConfigSSH_FileWriteAndOptionsFlow(t *testing.T) {
regexMatch: `ProxyCommand .* --header-command "printf h1=v1 h2='v2'" ssh`,
},
},
{
name: "Multiple remote forwards",
args: []string{
"--yes",
"--ssh-option", "RemoteForward 2222 192.168.11.1:2222",
"--ssh-option", "RemoteForward 2223 192.168.11.1:2223",
},
wantErr: false,
hasAgent: true,
wantConfig: wantConfig{
regexMatch: "RemoteForward 2222 192.168.11.1:2222.*\n.*RemoteForward 2223 192.168.11.1:2223",
},
},
}
for _, tt := range tests {
tt := tt
+77 -9
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"strings"
"time"
"github.com/google/uuid"
@@ -29,6 +30,9 @@ func (r *RootCmd) create() *serpent.Command {
parameterFlags workspaceParameterFlags
autoUpdates string
copyParametersFrom string
// Organization context is only required if more than 1 template
// shares the same name across multiple organizations.
orgContext = NewOrganizationContext()
)
client := new(codersdk.Client)
cmd := &serpent.Command{
@@ -43,11 +47,7 @@ func (r *RootCmd) create() *serpent.Command {
),
Middleware: serpent.Chain(r.InitClient(client)),
Handler: func(inv *serpent.Invocation) error {
organization, err := CurrentOrganization(r, inv, client)
if err != nil {
return err
}
var err error
workspaceOwner := codersdk.Me
if len(inv.Args) >= 1 {
workspaceOwner, workspaceName, err = splitNamedWorkspace(inv.Args[0])
@@ -98,7 +98,7 @@ func (r *RootCmd) create() *serpent.Command {
if templateName == "" {
_, _ = fmt.Fprintln(inv.Stdout, pretty.Sprint(cliui.DefaultStyles.Wrap, "Select a template below to preview the provisioned infrastructure:"))
templates, err := client.TemplatesByOrganization(inv.Context(), organization.ID)
templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{})
if err != nil {
return err
}
@@ -110,13 +110,28 @@ func (r *RootCmd) create() *serpent.Command {
templateNames := make([]string, 0, len(templates))
templateByName := make(map[string]codersdk.Template, len(templates))
// If more than 1 organization exists in the list of templates,
// then include the organization name in the select options.
uniqueOrganizations := make(map[uuid.UUID]bool)
for _, template := range templates {
uniqueOrganizations[template.OrganizationID] = true
}
for _, template := range templates {
templateName := template.Name
if len(uniqueOrganizations) > 1 {
templateName += cliui.Placeholder(
fmt.Sprintf(
" (%s)",
template.OrganizationName,
),
)
}
if template.ActiveUserCount > 0 {
templateName += cliui.Placeholder(
fmt.Sprintf(
" (used by %s)",
" used by %s",
formatActiveDevelopers(template.ActiveUserCount),
),
)
@@ -144,13 +159,65 @@ func (r *RootCmd) create() *serpent.Command {
}
templateVersionID = sourceWorkspace.LatestBuild.TemplateVersionID
} else {
template, err = client.TemplateByName(inv.Context(), organization.ID, templateName)
templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{
ExactName: templateName,
})
if err != nil {
return xerrors.Errorf("get template by name: %w", err)
}
if len(templates) == 0 {
return xerrors.Errorf("no template found with the name %q", templateName)
}
if len(templates) > 1 {
templateOrgs := []string{}
for _, tpl := range templates {
templateOrgs = append(templateOrgs, tpl.OrganizationName)
}
selectedOrg, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("multiple templates found with the name %q, use `--org=<organization_name>` to specify which template by that name to use. Organizations available: %s", templateName, strings.Join(templateOrgs, ", "))
}
index := slices.IndexFunc(templates, func(i codersdk.Template) bool {
return i.OrganizationID == selectedOrg.ID
})
if index == -1 {
return xerrors.Errorf("no templates found with the name %q in the organization %q. Templates by that name exist in organizations: %s. Use --org=<organization_name> to select one.", templateName, selectedOrg.Name, strings.Join(templateOrgs, ", "))
}
// remake the list with the only template selected
templates = []codersdk.Template{templates[index]}
}
template = templates[0]
templateVersionID = template.ActiveVersionID
}
// If the user specified an organization via a flag or env var, the template **must**
// be in that organization. Otherwise, we should throw an error.
orgValue, orgValueSource := orgContext.ValueSource(inv)
if orgValue != "" && !(orgValueSource == serpent.ValueSourceDefault || orgValueSource == serpent.ValueSourceNone) {
selectedOrg, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
if template.OrganizationID != selectedOrg.ID {
orgNameFormat := "'--org=%q'"
if orgValueSource == serpent.ValueSourceEnv {
orgNameFormat = "CODER_ORGANIZATION=%q"
}
return xerrors.Errorf("template is in organization %q, but %s was specified. Use %s to use this template",
template.OrganizationName,
fmt.Sprintf(orgNameFormat, selectedOrg.Name),
fmt.Sprintf(orgNameFormat, template.OrganizationName),
)
}
}
var schedSpec *string
if startAt != "" {
sched, err := parseCLISchedule(startAt)
@@ -206,7 +273,7 @@ func (r *RootCmd) create() *serpent.Command {
ttlMillis = ptr.Ref(stopAfter.Milliseconds())
}
workspace, err := client.CreateWorkspace(inv.Context(), organization.ID, workspaceOwner, codersdk.CreateWorkspaceRequest{
workspace, err := client.CreateWorkspace(inv.Context(), template.OrganizationID, workspaceOwner, codersdk.CreateWorkspaceRequest{
TemplateVersionID: templateVersionID,
Name: workspaceName,
AutostartSchedule: schedSpec,
@@ -269,6 +336,7 @@ func (r *RootCmd) create() *serpent.Command {
)
cmd.Options = append(cmd.Options, parameterFlags.cliParameters()...)
cmd.Options = append(cmd.Options, parameterFlags.cliParameterDefaults()...)
orgContext.AttachOptions(cmd)
return cmd
}
+4 -5
View File
@@ -27,7 +27,7 @@ func TestDelete(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
inv, root := clitest.New(t, "delete", workspace.Name, "-y")
clitest.SetupConfig(t, member, root)
@@ -52,7 +52,7 @@ func TestDelete(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
inv, root := clitest.New(t, "delete", workspace.Name, "-y", "--orphan")
@@ -86,8 +86,7 @@ func TestDelete(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, deleteMeClient, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, deleteMeClient, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, deleteMeClient, workspace.LatestBuild.ID)
// The API checks if the user has any workspaces, so we cannot delete a user
@@ -128,7 +127,7 @@ func TestDelete(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, adminClient, orgID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, adminClient, version.ID)
template := coderdtest.CreateTemplate(t, adminClient, orgID, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, orgID, template.ID)
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
inv, root := clitest.New(t, "delete", user.Username+"/"+workspace.Name, "-y")
+1 -1
View File
@@ -204,7 +204,7 @@ func (r *RootCmd) dotfiles() *serpent.Command {
}
if fi.Mode()&0o111 == 0 {
return xerrors.Errorf("script %q is not executable. See https://coder.com/docs/v2/latest/dotfiles for information on how to resolve the issue.", script)
return xerrors.Errorf("script %q is not executable. See https://coder.com/docs/dotfiles for information on how to resolve the issue.", script)
}
// it is safe to use a variable command here because it's from
+1
View File
@@ -13,6 +13,7 @@ func (r *RootCmd) expCmd() *serpent.Command {
Children: []*serpent.Command{
r.scaletestCmd(),
r.errorExample(),
r.promptExample(),
},
}
return cmd
+32 -27
View File
@@ -6,6 +6,7 @@ import (
"strconv"
"time"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
@@ -22,19 +23,21 @@ type workspaceListRow struct {
codersdk.Workspace `table:"-"`
// For table format:
Favorite bool `json:"-" table:"favorite"`
WorkspaceName string `json:"-" table:"workspace,default_sort"`
Template string `json:"-" table:"template"`
Status string `json:"-" table:"status"`
Healthy string `json:"-" table:"healthy"`
LastBuilt string `json:"-" table:"last built"`
CurrentVersion string `json:"-" table:"current version"`
Outdated bool `json:"-" table:"outdated"`
StartsAt string `json:"-" table:"starts at"`
StartsNext string `json:"-" table:"starts next"`
StopsAfter string `json:"-" table:"stops after"`
StopsNext string `json:"-" table:"stops next"`
DailyCost string `json:"-" table:"daily cost"`
Favorite bool `json:"-" table:"favorite"`
WorkspaceName string `json:"-" table:"workspace,default_sort"`
OrganizationID uuid.UUID `json:"-" table:"organization id"`
OrganizationName string `json:"-" table:"organization name"`
Template string `json:"-" table:"template"`
Status string `json:"-" table:"status"`
Healthy string `json:"-" table:"healthy"`
LastBuilt string `json:"-" table:"last built"`
CurrentVersion string `json:"-" table:"current version"`
Outdated bool `json:"-" table:"outdated"`
StartsAt string `json:"-" table:"starts at"`
StartsNext string `json:"-" table:"starts next"`
StopsAfter string `json:"-" table:"stops after"`
StopsNext string `json:"-" table:"stops next"`
DailyCost string `json:"-" table:"daily cost"`
}
func workspaceListRowFromWorkspace(now time.Time, workspace codersdk.Workspace) workspaceListRow {
@@ -53,20 +56,22 @@ func workspaceListRowFromWorkspace(now time.Time, workspace codersdk.Workspace)
}
workspaceName := favIco + " " + workspace.OwnerName + "/" + workspace.Name
return workspaceListRow{
Favorite: workspace.Favorite,
Workspace: workspace,
WorkspaceName: workspaceName,
Template: workspace.TemplateName,
Status: status,
Healthy: healthy,
LastBuilt: durationDisplay(lastBuilt),
CurrentVersion: workspace.LatestBuild.TemplateVersionName,
Outdated: workspace.Outdated,
StartsAt: schedRow.StartsAt,
StartsNext: schedRow.StartsNext,
StopsAfter: schedRow.StopsAfter,
StopsNext: schedRow.StopsNext,
DailyCost: strconv.Itoa(int(workspace.LatestBuild.DailyCost)),
Favorite: workspace.Favorite,
Workspace: workspace,
WorkspaceName: workspaceName,
OrganizationID: workspace.OrganizationID,
OrganizationName: workspace.OrganizationName,
Template: workspace.TemplateName,
Status: status,
Healthy: healthy,
LastBuilt: durationDisplay(lastBuilt),
CurrentVersion: workspace.LatestBuild.TemplateVersionName,
Outdated: workspace.Outdated,
StartsAt: schedRow.StartsAt,
StartsNext: schedRow.StartsNext,
StopsAfter: schedRow.StopsAfter,
StopsNext: schedRow.StopsNext,
DailyCost: strconv.Itoa(int(workspace.LatestBuild.DailyCost)),
}
}
+29 -1
View File
@@ -58,6 +58,21 @@ func promptFirstUsername(inv *serpent.Invocation) (string, error) {
return username, nil
}
func promptFirstName(inv *serpent.Invocation) (string, error) {
name, err := cliui.Prompt(inv, cliui.PromptOptions{
Text: "(Optional) What " + pretty.Sprint(cliui.DefaultStyles.Field, "name") + " would you like?",
Default: "",
})
if err != nil {
if errors.Is(err, cliui.Canceled) {
return "", nil
}
return "", err
}
return name, nil
}
func promptFirstPassword(inv *serpent.Invocation) (string, error) {
retry:
password, err := cliui.Prompt(inv, cliui.PromptOptions{
@@ -130,6 +145,7 @@ func (r *RootCmd) login() *serpent.Command {
var (
email string
username string
name string
password string
trial bool
useTokenForSession bool
@@ -191,6 +207,7 @@ func (r *RootCmd) login() *serpent.Command {
_, _ = fmt.Fprintf(inv.Stdout, "Attempting to authenticate with %s URL: '%s'\n", urlSource, serverURL)
// nolint: nestif
if !hasFirstUser {
_, _ = fmt.Fprintf(inv.Stdout, Caret+"Your Coder deployment hasn't been set up!\n")
@@ -212,6 +229,10 @@ func (r *RootCmd) login() *serpent.Command {
if err != nil {
return err
}
name, err = promptFirstName(inv)
if err != nil {
return err
}
}
if email == "" {
@@ -239,7 +260,7 @@ func (r *RootCmd) login() *serpent.Command {
if !inv.ParsedFlags().Changed("first-user-trial") && os.Getenv(firstUserTrialEnv) == "" {
v, _ := cliui.Prompt(inv, cliui.PromptOptions{
Text: "Start a 30-day trial of Enterprise?",
Text: "Start a trial of Enterprise?",
IsConfirm: true,
Default: "yes",
})
@@ -249,6 +270,7 @@ func (r *RootCmd) login() *serpent.Command {
_, err = client.CreateFirstUser(ctx, codersdk.CreateFirstUserRequest{
Email: email,
Username: username,
Name: name,
Password: password,
Trial: trial,
})
@@ -353,6 +375,12 @@ func (r *RootCmd) login() *serpent.Command {
Description: "Specifies a username to use if creating the first user for the deployment.",
Value: serpent.StringOf(&username),
},
{
Flag: "first-user-full-name",
Env: "CODER_FIRST_USER_FULL_NAME",
Description: "Specifies a human-readable name for the first user of the deployment.",
Value: serpent.StringOf(&name),
},
{
Flag: "first-user-password",
Env: "CODER_FIRST_USER_PASSWORD",
+154 -16
View File
@@ -18,6 +18,7 @@ import (
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/pty/ptytest"
"github.com/coder/coder/v2/testutil"
)
func TestLogin(t *testing.T) {
@@ -89,10 +90,11 @@ func TestLogin(t *testing.T) {
matches := []string{
"first user?", "yes",
"username", "testuser",
"email", "user@coder.com",
"password", "SomeSecurePassword!",
"password", "SomeSecurePassword!", // Confirm.
"username", coderdtest.FirstUserParams.Username,
"name", coderdtest.FirstUserParams.Name,
"email", coderdtest.FirstUserParams.Email,
"password", coderdtest.FirstUserParams.Password,
"password", coderdtest.FirstUserParams.Password, // confirm
"trial", "yes",
}
for i := 0; i < len(matches); i += 2 {
@@ -103,6 +105,64 @@ func TestLogin(t *testing.T) {
}
pty.ExpectMatch("Welcome to Coder")
<-doneChan
ctx := testutil.Context(t, testutil.WaitShort)
resp, err := client.LoginWithPassword(ctx, codersdk.LoginWithPasswordRequest{
Email: coderdtest.FirstUserParams.Email,
Password: coderdtest.FirstUserParams.Password,
})
require.NoError(t, err)
client.SetSessionToken(resp.SessionToken)
me, err := client.User(ctx, codersdk.Me)
require.NoError(t, err)
assert.Equal(t, coderdtest.FirstUserParams.Username, me.Username)
assert.Equal(t, coderdtest.FirstUserParams.Name, me.Name)
assert.Equal(t, coderdtest.FirstUserParams.Email, me.Email)
})
t.Run("InitialUserTTYNameOptional", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
// The --force-tty flag is required on Windows, because the `isatty` library does not
// accurately detect Windows ptys when they are not attached to a process:
// https://github.com/mattn/go-isatty/issues/59
doneChan := make(chan struct{})
root, _ := clitest.New(t, "login", "--force-tty", client.URL.String())
pty := ptytest.New(t).Attach(root)
go func() {
defer close(doneChan)
err := root.Run()
assert.NoError(t, err)
}()
matches := []string{
"first user?", "yes",
"username", coderdtest.FirstUserParams.Username,
"name", "",
"email", coderdtest.FirstUserParams.Email,
"password", coderdtest.FirstUserParams.Password,
"password", coderdtest.FirstUserParams.Password, // confirm
"trial", "yes",
}
for i := 0; i < len(matches); i += 2 {
match := matches[i]
value := matches[i+1]
pty.ExpectMatch(match)
pty.WriteLine(value)
}
pty.ExpectMatch("Welcome to Coder")
<-doneChan
ctx := testutil.Context(t, testutil.WaitShort)
resp, err := client.LoginWithPassword(ctx, codersdk.LoginWithPasswordRequest{
Email: coderdtest.FirstUserParams.Email,
Password: coderdtest.FirstUserParams.Password,
})
require.NoError(t, err)
client.SetSessionToken(resp.SessionToken)
me, err := client.User(ctx, codersdk.Me)
require.NoError(t, err)
assert.Equal(t, coderdtest.FirstUserParams.Username, me.Username)
assert.Equal(t, coderdtest.FirstUserParams.Email, me.Email)
assert.Empty(t, me.Name)
})
t.Run("InitialUserTTYFlag", func(t *testing.T) {
@@ -119,10 +179,11 @@ func TestLogin(t *testing.T) {
pty.ExpectMatch(fmt.Sprintf("Attempting to authenticate with flag URL: '%s'", client.URL.String()))
matches := []string{
"first user?", "yes",
"username", "testuser",
"email", "user@coder.com",
"password", "SomeSecurePassword!",
"password", "SomeSecurePassword!", // Confirm.
"username", coderdtest.FirstUserParams.Username,
"name", coderdtest.FirstUserParams.Name,
"email", coderdtest.FirstUserParams.Email,
"password", coderdtest.FirstUserParams.Password,
"password", coderdtest.FirstUserParams.Password, // confirm
"trial", "yes",
}
for i := 0; i < len(matches); i += 2 {
@@ -132,6 +193,18 @@ func TestLogin(t *testing.T) {
pty.WriteLine(value)
}
pty.ExpectMatch("Welcome to Coder")
ctx := testutil.Context(t, testutil.WaitShort)
resp, err := client.LoginWithPassword(ctx, codersdk.LoginWithPasswordRequest{
Email: coderdtest.FirstUserParams.Email,
Password: coderdtest.FirstUserParams.Password,
})
require.NoError(t, err)
client.SetSessionToken(resp.SessionToken)
me, err := client.User(ctx, codersdk.Me)
require.NoError(t, err)
assert.Equal(t, coderdtest.FirstUserParams.Username, me.Username)
assert.Equal(t, coderdtest.FirstUserParams.Name, me.Name)
assert.Equal(t, coderdtest.FirstUserParams.Email, me.Email)
})
t.Run("InitialUserFlags", func(t *testing.T) {
@@ -139,13 +212,56 @@ func TestLogin(t *testing.T) {
client := coderdtest.New(t, nil)
inv, _ := clitest.New(
t, "login", client.URL.String(),
"--first-user-username", "testuser", "--first-user-email", "user@coder.com",
"--first-user-password", "SomeSecurePassword!", "--first-user-trial",
"--first-user-username", coderdtest.FirstUserParams.Username,
"--first-user-full-name", coderdtest.FirstUserParams.Name,
"--first-user-email", coderdtest.FirstUserParams.Email,
"--first-user-password", coderdtest.FirstUserParams.Password,
"--first-user-trial",
)
pty := ptytest.New(t).Attach(inv)
w := clitest.StartWithWaiter(t, inv)
pty.ExpectMatch("Welcome to Coder")
w.RequireSuccess()
ctx := testutil.Context(t, testutil.WaitShort)
resp, err := client.LoginWithPassword(ctx, codersdk.LoginWithPasswordRequest{
Email: coderdtest.FirstUserParams.Email,
Password: coderdtest.FirstUserParams.Password,
})
require.NoError(t, err)
client.SetSessionToken(resp.SessionToken)
me, err := client.User(ctx, codersdk.Me)
require.NoError(t, err)
assert.Equal(t, coderdtest.FirstUserParams.Username, me.Username)
assert.Equal(t, coderdtest.FirstUserParams.Name, me.Name)
assert.Equal(t, coderdtest.FirstUserParams.Email, me.Email)
})
t.Run("InitialUserFlagsNameOptional", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
inv, _ := clitest.New(
t, "login", client.URL.String(),
"--first-user-username", coderdtest.FirstUserParams.Username,
"--first-user-email", coderdtest.FirstUserParams.Email,
"--first-user-password", coderdtest.FirstUserParams.Password,
"--first-user-trial",
)
pty := ptytest.New(t).Attach(inv)
w := clitest.StartWithWaiter(t, inv)
pty.ExpectMatch("Welcome to Coder")
w.RequireSuccess()
ctx := testutil.Context(t, testutil.WaitShort)
resp, err := client.LoginWithPassword(ctx, codersdk.LoginWithPasswordRequest{
Email: coderdtest.FirstUserParams.Email,
Password: coderdtest.FirstUserParams.Password,
})
require.NoError(t, err)
client.SetSessionToken(resp.SessionToken)
me, err := client.User(ctx, codersdk.Me)
require.NoError(t, err)
assert.Equal(t, coderdtest.FirstUserParams.Username, me.Username)
assert.Equal(t, coderdtest.FirstUserParams.Email, me.Email)
assert.Empty(t, me.Name)
})
t.Run("InitialUserTTYConfirmPasswordFailAndReprompt", func(t *testing.T) {
@@ -167,10 +283,11 @@ func TestLogin(t *testing.T) {
matches := []string{
"first user?", "yes",
"username", "testuser",
"email", "user@coder.com",
"password", "MyFirstSecurePassword!",
"password", "MyNonMatchingSecurePassword!", // Confirm.
"username", coderdtest.FirstUserParams.Username,
"name", coderdtest.FirstUserParams.Name,
"email", coderdtest.FirstUserParams.Email,
"password", coderdtest.FirstUserParams.Password,
"password", "something completely different",
}
for i := 0; i < len(matches); i += 2 {
match := matches[i]
@@ -183,9 +300,9 @@ func TestLogin(t *testing.T) {
pty.ExpectMatch("Passwords do not match")
pty.ExpectMatch("Enter a " + pretty.Sprint(cliui.DefaultStyles.Field, "password"))
pty.WriteLine("SomeSecurePassword!")
pty.WriteLine(coderdtest.FirstUserParams.Password)
pty.ExpectMatch("Confirm")
pty.WriteLine("SomeSecurePassword!")
pty.WriteLine(coderdtest.FirstUserParams.Password)
pty.ExpectMatch("trial")
pty.WriteLine("yes")
pty.ExpectMatch("Welcome to Coder")
@@ -304,4 +421,25 @@ func TestLogin(t *testing.T) {
// This **should not be equal** to the token we passed in.
require.NotEqual(t, client.SessionToken(), sessionFile)
})
t.Run("KeepOrganizationContext", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
first := coderdtest.CreateFirstUser(t, client)
root, cfg := clitest.New(t, "login", client.URL.String(), "--token", client.SessionToken())
err := cfg.Organization().Write(first.OrganizationID.String())
require.NoError(t, err, "write bad org to config")
err = root.Run()
require.NoError(t, err)
sessionFile, err := cfg.Session().Read()
require.NoError(t, err)
require.NotEqual(t, client.SessionToken(), sessionFile)
// Organization config should be deleted since the org does not exist
selected, err := cfg.Organization().Read()
require.NoError(t, err)
require.Equal(t, selected, first.OrganizationID.String())
})
}
+13 -2
View File
@@ -10,6 +10,7 @@ import (
"github.com/coder/coder/v2/coderd/healthcheck/derphealth"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/healthsdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/serpent"
)
@@ -34,11 +35,21 @@ func (r *RootCmd) netcheck() *serpent.Command {
_, _ = fmt.Fprint(inv.Stderr, "Gathering a network report. This may take a few seconds...\n\n")
var report derphealth.Report
report.Run(ctx, &derphealth.ReportOptions{
var derpReport derphealth.Report
derpReport.Run(ctx, &derphealth.ReportOptions{
DERPMap: connInfo.DERPMap,
})
ifReport, err := healthsdk.RunInterfacesReport()
if err != nil {
return xerrors.Errorf("failed to run interfaces report: %w", err)
}
report := healthsdk.ClientNetcheckReport{
DERP: healthsdk.DERPHealthReport(derpReport),
Interfaces: ifReport,
}
raw, err := json.MarshalIndent(report, "", " ")
if err != nil {
return err
+5 -5
View File
@@ -5,7 +5,6 @@ import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli/clitest"
@@ -27,12 +26,13 @@ func TestNetcheck(t *testing.T) {
b := out.Bytes()
t.Log(string(b))
var report healthsdk.DERPHealthReport
var report healthsdk.ClientNetcheckReport
require.NoError(t, json.Unmarshal(b, &report))
assert.True(t, report.Healthy)
require.Len(t, report.Regions, 1+1) // 1 built-in region + 1 test-managed STUN region
for _, v := range report.Regions {
// We do not assert that the report is healthy, just that
// it has the expected number of reports per region.
require.Len(t, report.DERP.Regions, 1+1) // 1 built-in region + 1 test-managed STUN region
for _, v := range report.DERP.Regions {
require.Len(t, v.NodeReports, len(v.Region.Nodes))
}
}
+85
View File
@@ -0,0 +1,85 @@
package cli
import (
"fmt"
"golang.org/x/xerrors"
"github.com/coder/serpent"
"github.com/coder/coder/v2/codersdk"
)
func (r *RootCmd) notifications() *serpent.Command {
cmd := &serpent.Command{
Use: "notifications",
Short: "Manage Coder notifications",
Long: "Administrators can use these commands to change notification settings.\n" + FormatExamples(
Example{
Description: "Pause Coder notifications. Administrators can temporarily stop notifiers from dispatching messages in case of the target outage (for example: unavailable SMTP server or Webhook not responding).",
Command: "coder notifications pause",
},
Example{
Description: "Resume Coder notifications",
Command: "coder notifications resume",
},
),
Aliases: []string{"notification"},
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Children: []*serpent.Command{
r.pauseNotifications(),
r.resumeNotifications(),
},
}
return cmd
}
func (r *RootCmd) pauseNotifications() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "pause",
Short: "Pause notifications",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
err := client.PutNotificationsSettings(inv.Context(), codersdk.NotificationsSettings{
NotifierPaused: true,
})
if err != nil {
return xerrors.Errorf("unable to pause notifications: %w", err)
}
_, _ = fmt.Fprintln(inv.Stderr, "Notifications are now paused.")
return nil
},
}
return cmd
}
func (r *RootCmd) resumeNotifications() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "resume",
Short: "Resume notifications",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
err := client.PutNotificationsSettings(inv.Context(), codersdk.NotificationsSettings{
NotifierPaused: false,
})
if err != nil {
return xerrors.Errorf("unable to resume notifications: %w", err)
}
_, _ = fmt.Fprintln(inv.Stderr, "Notifications are now resumed.")
return nil
},
}
return cmd
}
+102
View File
@@ -0,0 +1,102 @@
package cli_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)
func TestNotifications(t *testing.T) {
t.Parallel()
tests := []struct {
name string
command string
expectPaused bool
}{
{
name: "PauseNotifications",
command: "pause",
expectPaused: true,
},
{
name: "ResumeNotifications",
command: "resume",
expectPaused: false,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
// given
ownerClient, db := coderdtest.NewWithDatabase(t, nil)
_ = coderdtest.CreateFirstUser(t, ownerClient)
// when
inv, root := clitest.New(t, "notifications", tt.command)
clitest.SetupConfig(t, ownerClient, root)
var buf bytes.Buffer
inv.Stdout = &buf
err := inv.Run()
require.NoError(t, err)
// then
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
t.Cleanup(cancel)
settingsJSON, err := db.GetNotificationsSettings(ctx)
require.NoError(t, err)
var settings codersdk.NotificationsSettings
err = json.Unmarshal([]byte(settingsJSON), &settings)
require.NoError(t, err)
require.Equal(t, tt.expectPaused, settings.NotifierPaused)
})
}
}
func TestPauseNotifications_RegularUser(t *testing.T) {
t.Parallel()
// given
ownerClient, db := coderdtest.NewWithDatabase(t, nil)
owner := coderdtest.CreateFirstUser(t, ownerClient)
anotherClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
// when
inv, root := clitest.New(t, "notifications", "pause")
clitest.SetupConfig(t, anotherClient, root)
var buf bytes.Buffer
inv.Stdout = &buf
err := inv.Run()
var sdkError *codersdk.Error
require.Error(t, err)
require.ErrorAsf(t, err, &sdkError, "error should be of type *codersdk.Error")
assert.Equal(t, http.StatusForbidden, sdkError.StatusCode())
assert.Contains(t, sdkError.Message, "Insufficient permissions to update notifications settings.")
// then
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort)
t.Cleanup(cancel)
settingsJSON, err := db.GetNotificationsSettings(ctx)
require.NoError(t, err)
var settings codersdk.NotificationsSettings
err = json.Unmarshal([]byte(settingsJSON), &settings)
require.NoError(t, err)
require.False(t, settings.NotifierPaused) // still running
}
+37 -189
View File
@@ -1,213 +1,40 @@
package cli
import (
"errors"
"fmt"
"os"
"slices"
"strings"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/cli/config"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/pretty"
"github.com/coder/serpent"
)
func (r *RootCmd) organizations() *serpent.Command {
orgContext := NewOrganizationContext()
cmd := &serpent.Command{
Annotations: workspaceCommand,
Use: "organizations [subcommand]",
Short: "Organization related commands",
Aliases: []string{"organization", "org", "orgs"},
Hidden: true, // Hidden until these commands are complete.
Use: "organizations [subcommand]",
Short: "Organization related commands",
Aliases: []string{"organization", "org", "orgs"},
Hidden: true, // Hidden until these commands are complete.
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Children: []*serpent.Command{
r.currentOrganization(),
r.switchOrganization(),
r.showOrganization(orgContext),
r.createOrganization(),
r.organizationRoles(),
r.organizationMembers(orgContext),
r.organizationRoles(orgContext),
},
}
cmd.Options = serpent.OptionSet{}
orgContext.AttachOptions(cmd)
return cmd
}
func (r *RootCmd) switchOrganization() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "set <organization name | ID>",
Short: "set the organization used by the CLI. Pass an empty string to reset to the default organization.",
Long: "set the organization used by the CLI. Pass an empty string to reset to the default organization.\n" + FormatExamples(
Example{
Description: "Remove the current organization and defer to the default.",
Command: "coder organizations set ''",
},
Example{
Description: "Switch to a custom organization.",
Command: "coder organizations set my-org",
},
),
Middleware: serpent.Chain(
r.InitClient(client),
serpent.RequireRangeArgs(0, 1),
),
Options: serpent.OptionSet{},
Handler: func(inv *serpent.Invocation) error {
conf := r.createConfig()
orgs, err := client.OrganizationsByUser(inv.Context(), codersdk.Me)
if err != nil {
return xerrors.Errorf("failed to get organizations: %w", err)
}
// Keep the list of orgs sorted
slices.SortFunc(orgs, func(a, b codersdk.Organization) int {
return strings.Compare(a.Name, b.Name)
})
var switchToOrg string
if len(inv.Args) == 0 {
// Pull switchToOrg from a prompt selector, rather than command line
// args.
switchToOrg, err = promptUserSelectOrg(inv, conf, orgs)
if err != nil {
return err
}
} else {
switchToOrg = inv.Args[0]
}
// If the user passes an empty string, we want to remove the organization
// from the config file. This will defer to default behavior.
if switchToOrg == "" {
err := conf.Organization().Delete()
if err != nil && !errors.Is(err, os.ErrNotExist) {
return xerrors.Errorf("failed to unset organization: %w", err)
}
_, _ = fmt.Fprintf(inv.Stdout, "Organization unset\n")
} else {
// Find the selected org in our list.
index := slices.IndexFunc(orgs, func(org codersdk.Organization) bool {
return org.Name == switchToOrg || org.ID.String() == switchToOrg
})
if index < 0 {
// Using this error for better error message formatting
err := &codersdk.Error{
Response: codersdk.Response{
Message: fmt.Sprintf("Organization %q not found. Is the name correct, and are you a member of it?", switchToOrg),
Detail: "Ensure the organization argument is correct and you are a member of it.",
},
Helper: fmt.Sprintf("Valid organizations you can switch to: %s", strings.Join(orgNames(orgs), ", ")),
}
return err
}
// Always write the uuid to the config file. Names can change.
err := conf.Organization().Write(orgs[index].ID.String())
if err != nil {
return xerrors.Errorf("failed to write organization to config file: %w", err)
}
}
// Verify it worked.
current, err := CurrentOrganization(r, inv, client)
if err != nil {
// An SDK error could be a permission error. So offer the advice to unset the org
// and reset the context.
var sdkError *codersdk.Error
if errors.As(err, &sdkError) {
if sdkError.Helper == "" && sdkError.StatusCode() != 500 {
sdkError.Helper = `If this error persists, try unsetting your org with 'coder organizations set ""'`
}
return sdkError
}
return xerrors.Errorf("failed to get current organization: %w", err)
}
_, _ = fmt.Fprintf(inv.Stdout, "Current organization context set to %s (%s)\n", current.Name, current.ID.String())
return nil
},
}
return cmd
}
// promptUserSelectOrg will prompt the user to select an organization from a list
// of their organizations.
func promptUserSelectOrg(inv *serpent.Invocation, conf config.Root, orgs []codersdk.Organization) (string, error) {
// Default choice
var defaultOrg string
// Comes from config file
if conf.Organization().Exists() {
defaultOrg, _ = conf.Organization().Read()
}
// No config? Comes from default org in the list
if defaultOrg == "" {
defIndex := slices.IndexFunc(orgs, func(org codersdk.Organization) bool {
return org.IsDefault
})
if defIndex >= 0 {
defaultOrg = orgs[defIndex].Name
}
}
// Defer to first org
if defaultOrg == "" && len(orgs) > 0 {
defaultOrg = orgs[0].Name
}
// Ensure the `defaultOrg` value is an org name, not a uuid.
// If it is a uuid, change it to the org name.
index := slices.IndexFunc(orgs, func(org codersdk.Organization) bool {
return org.ID.String() == defaultOrg || org.Name == defaultOrg
})
if index >= 0 {
defaultOrg = orgs[index].Name
}
// deselectOption is the option to delete the organization config file and defer
// to default behavior.
const deselectOption = "[Default]"
if defaultOrg == "" {
defaultOrg = deselectOption
}
// Pull value from a prompt
_, _ = fmt.Fprintln(inv.Stdout, pretty.Sprint(cliui.DefaultStyles.Wrap, "Select an organization below to set the current CLI context to:"))
value, err := cliui.Select(inv, cliui.SelectOptions{
Options: append([]string{deselectOption}, orgNames(orgs)...),
Default: defaultOrg,
Size: 10,
HideSearch: false,
})
if err != nil {
return "", err
}
// Deselect is an alias for ""
if value == deselectOption {
value = ""
}
return value, nil
}
// orgNames is a helper function to turn a list of organizations into a list of
// their names as strings.
func orgNames(orgs []codersdk.Organization) []string {
names := make([]string, 0, len(orgs))
for _, org := range orgs {
names = append(names, org.Name)
}
return names
}
func (r *RootCmd) currentOrganization() *serpent.Command {
func (r *RootCmd) showOrganization(orgContext *OrganizationContext) *serpent.Command {
var (
stringFormat func(orgs []codersdk.Organization) (string, error)
client = new(codersdk.Client)
@@ -226,8 +53,29 @@ func (r *RootCmd) currentOrganization() *serpent.Command {
onlyID = false
)
cmd := &serpent.Command{
Use: "show [current|me|uuid]",
Short: "Show the organization, if no argument is given, the organization currently in use will be shown.",
Use: "show [\"selected\"|\"me\"|uuid|org_name]",
Short: "Show the organization. " +
"Using \"selected\" will show the selected organization from the \"--org\" flag. " +
"Using \"me\" will show all organizations you are a member of.",
Long: FormatExamples(
Example{
Description: "coder org show selected",
Command: "Shows the organizations selected with '--org=<org_name>'. " +
"This organization is the organization used by the cli.",
},
Example{
Description: "coder org show me",
Command: "List of all organizations you are a member of.",
},
Example{
Description: "coder org show developers",
Command: "Show organization with name 'developers'",
},
Example{
Description: "coder org show 90ee1875-3db5-43b3-828e-af3687522e43",
Command: "Show organization with the given ID.",
},
),
Middleware: serpent.Chain(
r.InitClient(client),
serpent.RequireRangeArgs(0, 1),
@@ -242,7 +90,7 @@ func (r *RootCmd) currentOrganization() *serpent.Command {
},
},
Handler: func(inv *serpent.Invocation) error {
orgArg := "current"
orgArg := "selected"
if len(inv.Args) >= 1 {
orgArg = inv.Args[0]
}
@@ -250,14 +98,14 @@ func (r *RootCmd) currentOrganization() *serpent.Command {
var orgs []codersdk.Organization
var err error
switch strings.ToLower(orgArg) {
case "current":
case "selected":
stringFormat = func(orgs []codersdk.Organization) (string, error) {
if len(orgs) != 1 {
return "", xerrors.Errorf("expected 1 organization, got %d", len(orgs))
}
return fmt.Sprintf("Current CLI Organization: %s (%s)\n", orgs[0].Name, orgs[0].ID.String()), nil
}
org, err := CurrentOrganization(r, inv, client)
org, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
+5 -98
View File
@@ -12,11 +12,8 @@ import (
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/pty/ptytest"
"github.com/coder/coder/v2/testutil"
)
func TestCurrentOrganization(t *testing.T) {
@@ -32,8 +29,10 @@ func TestCurrentOrganization(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode([]codersdk.Organization{
{
ID: orgID,
Name: "not-default",
MinimalOrganization: codersdk.MinimalOrganization{
ID: orgID,
Name: "not-default",
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
IsDefault: false,
@@ -43,7 +42,7 @@ func TestCurrentOrganization(t *testing.T) {
defer srv.Close()
client := codersdk.New(must(url.Parse(srv.URL)))
inv, root := clitest.New(t, "organizations", "show", "current")
inv, root := clitest.New(t, "organizations", "show", "selected")
clitest.SetupConfig(t, client, root)
pty := ptytest.New(t).Attach(inv)
errC := make(chan error)
@@ -53,98 +52,6 @@ func TestCurrentOrganization(t *testing.T) {
require.NoError(t, <-errC)
pty.ExpectMatch(orgID.String())
})
t.Run("OnlyID", func(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, nil)
first := coderdtest.CreateFirstUser(t, ownerClient)
// Owner is required to make orgs
client, _ := coderdtest.CreateAnotherUser(t, ownerClient, first.OrganizationID, rbac.RoleOwner())
ctx := testutil.Context(t, testutil.WaitMedium)
orgs := []string{"foo", "bar"}
for _, orgName := range orgs {
_, err := client.CreateOrganization(ctx, codersdk.CreateOrganizationRequest{
Name: orgName,
})
require.NoError(t, err)
}
inv, root := clitest.New(t, "organizations", "show", "--only-id")
clitest.SetupConfig(t, client, root)
pty := ptytest.New(t).Attach(inv)
errC := make(chan error)
go func() {
errC <- inv.Run()
}()
require.NoError(t, <-errC)
pty.ExpectMatch(first.OrganizationID.String())
})
t.Run("UsingFlag", func(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, nil)
first := coderdtest.CreateFirstUser(t, ownerClient)
// Owner is required to make orgs
client, _ := coderdtest.CreateAnotherUser(t, ownerClient, first.OrganizationID, rbac.RoleOwner())
ctx := testutil.Context(t, testutil.WaitMedium)
orgs := map[string]codersdk.Organization{
"foo": {},
"bar": {},
}
for orgName := range orgs {
org, err := client.CreateOrganization(ctx, codersdk.CreateOrganizationRequest{
Name: orgName,
})
require.NoError(t, err)
orgs[orgName] = org
}
inv, root := clitest.New(t, "organizations", "show", "current", "--only-id", "-z=bar")
clitest.SetupConfig(t, client, root)
pty := ptytest.New(t).Attach(inv)
errC := make(chan error)
go func() {
errC <- inv.Run()
}()
require.NoError(t, <-errC)
pty.ExpectMatch(orgs["bar"].ID.String())
})
}
func TestOrganizationSwitch(t *testing.T) {
t.Parallel()
t.Run("Switch", func(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, nil)
first := coderdtest.CreateFirstUser(t, ownerClient)
// Owner is required to make orgs
client, _ := coderdtest.CreateAnotherUser(t, ownerClient, first.OrganizationID, rbac.RoleOwner())
ctx := testutil.Context(t, testutil.WaitMedium)
orgs := []string{"foo", "bar"}
for _, orgName := range orgs {
_, err := client.CreateOrganization(ctx, codersdk.CreateOrganizationRequest{
Name: orgName,
})
require.NoError(t, err)
}
exp, err := client.OrganizationByName(ctx, "foo")
require.NoError(t, err)
inv, root := clitest.New(t, "organizations", "set", "foo")
clitest.SetupConfig(t, client, root)
pty := ptytest.New(t).Attach(inv)
errC := make(chan error)
go func() {
errC <- inv.Run()
}()
require.NoError(t, <-errC)
pty.ExpectMatch(exp.ID.String())
})
}
func must[V any](v V, err error) V {
+176
View File
@@ -0,0 +1,176 @@
package cli
import (
"fmt"
"strings"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
func (r *RootCmd) organizationMembers(orgContext *OrganizationContext) *serpent.Command {
cmd := &serpent.Command{
Use: "members",
Aliases: []string{"member"},
Short: "Manage organization members",
Children: []*serpent.Command{
r.listOrganizationMembers(orgContext),
r.assignOrganizationRoles(orgContext),
r.addOrganizationMember(orgContext),
r.removeOrganizationMember(orgContext),
},
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
}
return cmd
}
func (r *RootCmd) removeOrganizationMember(orgContext *OrganizationContext) *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "remove <username | user_id>",
Short: "Remove a new member to the current organization",
Middleware: serpent.Chain(
r.InitClient(client),
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
user := inv.Args[0]
err = client.DeleteOrganizationMember(ctx, organization.ID, user)
if err != nil {
return xerrors.Errorf("could not remove member from organization %q: %w", organization.HumanName(), err)
}
_, _ = fmt.Fprintf(inv.Stdout, "Organization member removed from %q\n", organization.HumanName())
return nil
},
}
return cmd
}
func (r *RootCmd) addOrganizationMember(orgContext *OrganizationContext) *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "add <username | user_id>",
Short: "Add a new member to the current organization",
Middleware: serpent.Chain(
r.InitClient(client),
serpent.RequireNArgs(1),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
user := inv.Args[0]
_, err = client.PostOrganizationMember(ctx, organization.ID, user)
if err != nil {
return xerrors.Errorf("could not add member to organization %q: %w", organization.HumanName(), err)
}
_, _ = fmt.Fprintf(inv.Stdout, "Organization member added to %q\n", organization.HumanName())
return nil
},
}
return cmd
}
func (r *RootCmd) assignOrganizationRoles(orgContext *OrganizationContext) *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "edit-roles <username | user_id> [roles...]",
Aliases: []string{"edit-role"},
Short: "Edit organization member's roles",
Middleware: serpent.Chain(
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
if len(inv.Args) < 1 {
return xerrors.Errorf("user_id or username is required as the first argument")
}
userIdentifier := inv.Args[0]
roles := inv.Args[1:]
member, err := client.UpdateOrganizationMemberRoles(ctx, organization.ID, userIdentifier, codersdk.UpdateRoles{
Roles: roles,
})
if err != nil {
return xerrors.Errorf("update member roles: %w", err)
}
updatedTo := make([]string, 0)
for _, role := range member.Roles {
updatedTo = append(updatedTo, role.String())
}
_, _ = fmt.Fprintf(inv.Stdout, "Member roles updated to [%s]\n", strings.Join(updatedTo, ", "))
return nil
},
}
return cmd
}
func (r *RootCmd) listOrganizationMembers(orgContext *OrganizationContext) *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.TableFormat([]codersdk.OrganizationMemberWithUserData{}, []string{"username", "organization_roles"}),
cliui.JSONFormat(),
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "list",
Short: "List all organization members",
Middleware: serpent.Chain(
serpent.RequireNArgs(0),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
res, err := client.OrganizationMembers(ctx, organization.ID)
if err != nil {
return xerrors.Errorf("fetch members: %w", err)
}
out, err := formatter.Format(inv.Context(), res)
if err != nil {
return err
}
_, err = fmt.Fprintln(inv.Stdout, out)
return err
},
}
formatter.AttachOptions(&cmd.Options)
return cmd
}
+82
View File
@@ -0,0 +1,82 @@
package cli_test
import (
"bytes"
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/testutil"
)
func TestListOrganizationMembers(t *testing.T) {
t.Parallel()
t.Run("OK", func(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, &coderdtest.Options{})
owner := coderdtest.CreateFirstUser(t, ownerClient)
client, user := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID, rbac.RoleUserAdmin())
ctx := testutil.Context(t, testutil.WaitMedium)
inv, root := clitest.New(t, "organization", "members", "list", "-c", "user_id,username,roles")
clitest.SetupConfig(t, client, root)
buf := new(bytes.Buffer)
inv.Stdout = buf
err := inv.WithContext(ctx).Run()
require.NoError(t, err)
require.Contains(t, buf.String(), user.Username)
require.Contains(t, buf.String(), owner.UserID.String())
})
}
func TestRemoveOrganizationMembers(t *testing.T) {
t.Parallel()
t.Run("OK", func(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, &coderdtest.Options{})
owner := coderdtest.CreateFirstUser(t, ownerClient)
orgAdminClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
_, user := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
ctx := testutil.Context(t, testutil.WaitMedium)
inv, root := clitest.New(t, "organization", "members", "remove", "-O", owner.OrganizationID.String(), user.Username)
clitest.SetupConfig(t, orgAdminClient, root)
buf := new(bytes.Buffer)
inv.Stdout = buf
err := inv.WithContext(ctx).Run()
require.NoError(t, err)
members, err := orgAdminClient.OrganizationMembers(ctx, owner.OrganizationID)
require.NoError(t, err)
require.Len(t, members, 2)
})
t.Run("UserNotExists", func(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, &coderdtest.Options{})
owner := coderdtest.CreateFirstUser(t, ownerClient)
orgAdminClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID, rbac.ScopedRoleOrgAdmin(owner.OrganizationID))
ctx := testutil.Context(t, testutil.WaitMedium)
inv, root := clitest.New(t, "organization", "members", "remove", "-O", owner.OrganizationID.String(), "random_name")
clitest.SetupConfig(t, orgAdminClient, root)
buf := new(bytes.Buffer)
inv.Stdout = buf
err := inv.WithContext(ctx).Run()
require.ErrorContains(t, err, "must be an existing uuid or username")
})
}
+305 -22
View File
@@ -1,18 +1,22 @@
package cli
import (
"encoding/json"
"fmt"
"io"
"slices"
"strings"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
func (r *RootCmd) organizationRoles() *serpent.Command {
func (r *RootCmd) organizationRoles(orgContext *OrganizationContext) *serpent.Command {
cmd := &serpent.Command{
Use: "roles",
Short: "Manage organization roles.",
@@ -22,34 +26,29 @@ func (r *RootCmd) organizationRoles() *serpent.Command {
},
Hidden: true,
Children: []*serpent.Command{
r.showOrganizationRoles(),
r.showOrganizationRoles(orgContext),
r.editOrganizationRole(orgContext),
},
}
return cmd
}
func (r *RootCmd) showOrganizationRoles() *serpent.Command {
func (r *RootCmd) showOrganizationRoles(orgContext *OrganizationContext) *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.ChangeFormatterData(
cliui.TableFormat([]assignableRolesTableRow{}, []string{"name", "display_name", "built_in", "site_permissions", "org_permissions", "user_permissions"}),
cliui.TableFormat([]roleTableRow{}, []string{"name", "display_name", "site_permissions", "organization_permissions", "user_permissions"}),
func(data any) (any, error) {
input, ok := data.([]codersdk.AssignableRoles)
inputs, ok := data.([]codersdk.AssignableRoles)
if !ok {
return nil, xerrors.Errorf("expected []codersdk.AssignableRoles got %T", data)
}
rows := make([]assignableRolesTableRow, 0, len(input))
for _, role := range input {
rows = append(rows, assignableRolesTableRow{
Name: role.Name,
DisplayName: role.DisplayName,
SitePermissions: fmt.Sprintf("%d permissions", len(role.SitePermissions)),
OrganizationPermissions: fmt.Sprintf("%d organizations", len(role.OrganizationPermissions)),
UserPermissions: fmt.Sprintf("%d permissions", len(role.UserPermissions)),
Assignable: role.Assignable,
BuiltIn: role.BuiltIn,
})
tableRows := make([]roleTableRow, 0)
for _, input := range inputs {
tableRows = append(tableRows, roleToTableView(input.Role))
}
return rows, nil
return tableRows, nil
},
),
cliui.JSONFormat(),
@@ -64,7 +63,7 @@ func (r *RootCmd) showOrganizationRoles() *serpent.Command {
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
org, err := CurrentOrganization(r, inv, client)
org, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
@@ -101,13 +100,297 @@ func (r *RootCmd) showOrganizationRoles() *serpent.Command {
return cmd
}
type assignableRolesTableRow struct {
func (r *RootCmd) editOrganizationRole(orgContext *OrganizationContext) *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.ChangeFormatterData(
cliui.TableFormat([]roleTableRow{}, []string{"name", "display_name", "site_permissions", "organization_permissions", "user_permissions"}),
func(data any) (any, error) {
typed, _ := data.(codersdk.Role)
return []roleTableRow{roleToTableView(typed)}, nil
},
),
cliui.JSONFormat(),
)
var (
dryRun bool
jsonInput bool
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "edit <role_name>",
Short: "Edit an organization custom role",
Long: FormatExamples(
Example{
Description: "Run with an input.json file",
Command: "coder roles edit --stdin < role.json",
},
),
Options: []serpent.Option{
cliui.SkipPromptOption(),
{
Name: "dry-run",
Description: "Does all the work, but does not submit the final updated role.",
Flag: "dry-run",
Value: serpent.BoolOf(&dryRun),
},
{
Name: "stdin",
Description: "Reads stdin for the json role definition to upload.",
Flag: "stdin",
Value: serpent.BoolOf(&jsonInput),
},
},
Middleware: serpent.Chain(
serpent.RequireRangeArgs(0, 1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
org, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
var customRole codersdk.Role
if jsonInput {
// JSON Upload mode
bytes, err := io.ReadAll(inv.Stdin)
if err != nil {
return xerrors.Errorf("reading stdin: %w", err)
}
err = json.Unmarshal(bytes, &customRole)
if err != nil {
return xerrors.Errorf("parsing stdin json: %w", err)
}
if customRole.Name == "" {
arr := make([]json.RawMessage, 0)
err = json.Unmarshal(bytes, &arr)
if err == nil && len(arr) > 0 {
return xerrors.Errorf("the input appears to be an array, only 1 role can be sent at a time")
}
return xerrors.Errorf("json input does not appear to be a valid role")
}
} else {
if len(inv.Args) == 0 {
return xerrors.Errorf("missing role name argument, usage: \"coder organizations roles edit <role_name>\"")
}
interactiveRole, err := interactiveOrgRoleEdit(inv, org.ID, client)
if err != nil {
return xerrors.Errorf("editing role: %w", err)
}
customRole = *interactiveRole
preview := fmt.Sprintf("permissions: %d site, %d org, %d user",
len(customRole.SitePermissions), len(customRole.OrganizationPermissions), len(customRole.UserPermissions))
_, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Are you sure you wish to update the role? " + preview,
Default: "yes",
IsConfirm: true,
})
if err != nil {
return xerrors.Errorf("abort: %w", err)
}
}
var updated codersdk.Role
if dryRun {
// Do not actually post
updated = customRole
} else {
updated, err = client.PatchOrganizationRole(ctx, customRole)
if err != nil {
return xerrors.Errorf("patch role: %w", err)
}
}
output, err := formatter.Format(ctx, updated)
if err != nil {
return xerrors.Errorf("formatting: %w", err)
}
_, err = fmt.Fprintln(inv.Stdout, output)
return err
},
}
formatter.AttachOptions(&cmd.Options)
return cmd
}
func interactiveOrgRoleEdit(inv *serpent.Invocation, orgID uuid.UUID, client *codersdk.Client) (*codersdk.Role, error) {
ctx := inv.Context()
roles, err := client.ListOrganizationRoles(ctx, orgID)
if err != nil {
return nil, xerrors.Errorf("listing roles: %w", err)
}
// Make sure the role actually exists first
var originalRole codersdk.AssignableRoles
for _, r := range roles {
if strings.EqualFold(inv.Args[0], r.Name) {
originalRole = r
break
}
}
if originalRole.Name == "" {
_, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "No organization role exists with that name, do you want to create one?",
Default: "yes",
IsConfirm: true,
})
if err != nil {
return nil, xerrors.Errorf("abort: %w", err)
}
originalRole.Role = codersdk.Role{
Name: inv.Args[0],
OrganizationID: orgID.String(),
}
}
// Some checks since interactive mode is limited in what it currently sees
if len(originalRole.SitePermissions) > 0 {
return nil, xerrors.Errorf("unable to edit role in interactive mode, it contains site wide permissions")
}
if len(originalRole.UserPermissions) > 0 {
return nil, xerrors.Errorf("unable to edit role in interactive mode, it contains user permissions")
}
role := &originalRole.Role
allowedResources := []codersdk.RBACResource{
codersdk.ResourceTemplate,
codersdk.ResourceWorkspace,
codersdk.ResourceUser,
codersdk.ResourceGroup,
}
const done = "Finish and submit changes"
const abort = "Cancel changes"
// Now starts the role editing "game".
customRoleLoop:
for {
selected, err := cliui.Select(inv, cliui.SelectOptions{
Message: "Select which resources to edit permissions",
Options: append(permissionPreviews(role, allowedResources), done, abort),
})
if err != nil {
return role, xerrors.Errorf("selecting resource: %w", err)
}
switch selected {
case done:
break customRoleLoop
case abort:
return role, xerrors.Errorf("edit role %q aborted", role.Name)
default:
strs := strings.Split(selected, "::")
resource := strings.TrimSpace(strs[0])
actions, err := cliui.MultiSelect(inv, cliui.MultiSelectOptions{
Message: fmt.Sprintf("Select actions to allow across the whole deployment for resources=%q", resource),
Options: slice.ToStrings(codersdk.RBACResourceActions[codersdk.RBACResource(resource)]),
Defaults: defaultActions(role, resource),
})
if err != nil {
return role, xerrors.Errorf("selecting actions for resource %q: %w", resource, err)
}
applyOrgResourceActions(role, resource, actions)
// back to resources!
}
}
// This println is required because the prompt ends us on the same line as some text.
_, _ = fmt.Println()
return role, nil
}
func applyOrgResourceActions(role *codersdk.Role, resource string, actions []string) {
if role.OrganizationPermissions == nil {
role.OrganizationPermissions = make([]codersdk.Permission, 0)
}
// Construct new site perms with only new perms for the resource
keep := make([]codersdk.Permission, 0)
for _, perm := range role.OrganizationPermissions {
perm := perm
if string(perm.ResourceType) != resource {
keep = append(keep, perm)
}
}
// Add new perms
for _, action := range actions {
keep = append(keep, codersdk.Permission{
Negate: false,
ResourceType: codersdk.RBACResource(resource),
Action: codersdk.RBACAction(action),
})
}
role.OrganizationPermissions = keep
}
func defaultActions(role *codersdk.Role, resource string) []string {
if role.OrganizationPermissions == nil {
role.OrganizationPermissions = []codersdk.Permission{}
}
defaults := make([]string, 0)
for _, perm := range role.OrganizationPermissions {
if string(perm.ResourceType) == resource {
defaults = append(defaults, string(perm.Action))
}
}
return defaults
}
func permissionPreviews(role *codersdk.Role, resources []codersdk.RBACResource) []string {
previews := make([]string, 0, len(resources))
for _, resource := range resources {
previews = append(previews, permissionPreview(role, resource))
}
return previews
}
func permissionPreview(role *codersdk.Role, resource codersdk.RBACResource) string {
if role.OrganizationPermissions == nil {
role.OrganizationPermissions = []codersdk.Permission{}
}
count := 0
for _, perm := range role.OrganizationPermissions {
if perm.ResourceType == resource {
count++
}
}
return fmt.Sprintf("%s :: %d permissions", resource, count)
}
func roleToTableView(role codersdk.Role) roleTableRow {
return roleTableRow{
Name: role.Name,
DisplayName: role.DisplayName,
OrganizationID: role.OrganizationID,
SitePermissions: fmt.Sprintf("%d permissions", len(role.SitePermissions)),
OrganizationPermissions: fmt.Sprintf("%d permissions", len(role.OrganizationPermissions)),
UserPermissions: fmt.Sprintf("%d permissions", len(role.UserPermissions)),
}
}
type roleTableRow struct {
Name string `table:"name,default_sort"`
DisplayName string `table:"display_name"`
OrganizationID string `table:"organization_id"`
SitePermissions string ` table:"site_permissions"`
// map[<org_id>] -> Permissions
OrganizationPermissions string `table:"org_permissions"`
OrganizationPermissions string `table:"organization_permissions"`
UserPermissions string `table:"user_permissions"`
Assignable bool `table:"assignable"`
BuiltIn bool `table:"built_in"`
}
+3
View File
@@ -58,6 +58,9 @@ func (r *RootCmd) ping() *serpent.Command {
_, _ = fmt.Fprintln(inv.Stderr, "Direct connections disabled.")
opts.BlockEndpoints = true
}
if !r.disableNetworkTelemetry {
opts.EnableTelemetry = true
}
conn, err := workspacesdk.New(client).DialAgent(ctx, workspaceAgent.ID, opts)
if err != nil {
return err
+3
View File
@@ -106,6 +106,9 @@ func (r *RootCmd) portForward() *serpent.Command {
_, _ = fmt.Fprintln(inv.Stderr, "Direct connections disabled.")
opts.BlockEndpoints = true
}
if !r.disableNetworkTelemetry {
opts.EnableTelemetry = true
}
conn, err := workspacesdk.New(client).DialAgent(ctx, workspaceAgent.ID, opts)
if err != nil {
return err
+186
View File
@@ -0,0 +1,186 @@
package cli
import (
"fmt"
"strings"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)
func (RootCmd) promptExample() *serpent.Command {
promptCmd := func(use string, prompt func(inv *serpent.Invocation) error, options ...serpent.Option) *serpent.Command {
return &serpent.Command{
Use: use,
Options: options,
Handler: func(inv *serpent.Invocation) error {
return prompt(inv)
},
}
}
var useSearch bool
useSearchOption := serpent.Option{
Name: "search",
Description: "Show the search.",
Required: false,
Flag: "search",
Value: serpent.BoolOf(&useSearch),
}
cmd := &serpent.Command{
Use: "prompt-example",
Short: "Example of various prompt types used within coder cli.",
Long: "Example of various prompt types used within coder cli. " +
"This command exists to aid in adjusting visuals of command prompts.",
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Children: []*serpent.Command{
promptCmd("confirm", func(inv *serpent.Invocation) error {
value, err := cliui.Prompt(inv, cliui.PromptOptions{
Text: "Basic confirmation prompt.",
Default: "yes",
IsConfirm: true,
})
_, _ = fmt.Fprintf(inv.Stdout, "%s\n", value)
return err
}),
promptCmd("validation", func(inv *serpent.Invocation) error {
value, err := cliui.Prompt(inv, cliui.PromptOptions{
Text: "Input a string that starts with a capital letter.",
Default: "",
Secret: false,
IsConfirm: false,
Validate: func(s string) error {
if len(s) == 0 {
return xerrors.Errorf("an input string is required")
}
if strings.ToUpper(string(s[0])) != string(s[0]) {
return xerrors.Errorf("input string must start with a capital letter")
}
return nil
},
})
_, _ = fmt.Fprintf(inv.Stdout, "%s\n", value)
return err
}),
promptCmd("secret", func(inv *serpent.Invocation) error {
value, err := cliui.Prompt(inv, cliui.PromptOptions{
Text: "Input a secret",
Default: "",
Secret: true,
IsConfirm: false,
Validate: func(s string) error {
if len(s) == 0 {
return xerrors.Errorf("an input string is required")
}
return nil
},
})
_, _ = fmt.Fprintf(inv.Stdout, "Your secret of length %d is safe with me\n", len(value))
return err
}),
promptCmd("select", func(inv *serpent.Invocation) error {
value, err := cliui.Select(inv, cliui.SelectOptions{
Options: []string{
"Blue", "Green", "Yellow", "Red", "Something else",
},
Default: "",
Message: "Select your favorite color:",
Size: 5,
HideSearch: !useSearch,
})
if value == "Something else" {
_, _ = fmt.Fprint(inv.Stdout, "I would have picked blue.\n")
} else {
_, _ = fmt.Fprintf(inv.Stdout, "%s is a nice color.\n", value)
}
return err
}, useSearchOption),
promptCmd("multiple", func(inv *serpent.Invocation) error {
_, _ = fmt.Fprintf(inv.Stdout, "This command exists to test the behavior of multiple prompts. The survey library does not erase the original message prompt after.")
thing, err := cliui.Select(inv, cliui.SelectOptions{
Message: "Select a thing",
Options: []string{
"Car", "Bike", "Plane", "Boat", "Train",
},
Default: "Car",
})
if err != nil {
return err
}
color, err := cliui.Select(inv, cliui.SelectOptions{
Message: "Select a color",
Options: []string{
"Blue", "Green", "Yellow", "Red",
},
Default: "Blue",
})
if err != nil {
return err
}
properties, err := cliui.MultiSelect(inv, cliui.MultiSelectOptions{
Message: "Select properties",
Options: []string{
"Fast", "Cool", "Expensive", "New",
},
Defaults: []string{"Fast"},
})
if err != nil {
return err
}
_, _ = fmt.Fprintf(inv.Stdout, "Your %s %s is awesome! Did you paint it %s?\n",
strings.Join(properties, " "),
thing,
color,
)
return err
}),
promptCmd("multi-select", func(inv *serpent.Invocation) error {
values, err := cliui.MultiSelect(inv, cliui.MultiSelectOptions{
Message: "Select some things:",
Options: []string{
"Code", "Chair", "Whale", "Diamond", "Carrot",
},
Defaults: []string{"Code"},
})
_, _ = fmt.Fprintf(inv.Stdout, "%q are nice choices.\n", strings.Join(values, ", "))
return err
}),
promptCmd("rich-parameter", func(inv *serpent.Invocation) error {
value, err := cliui.RichSelect(inv, cliui.RichSelectOptions{
Options: []codersdk.TemplateVersionParameterOption{
{
Name: "Blue",
Description: "Like the ocean.",
Value: "blue",
Icon: "/logo/blue.png",
},
{
Name: "Red",
Description: "Like a clown's nose.",
Value: "red",
Icon: "/logo/red.png",
},
{
Name: "Yellow",
Description: "Like a bumblebee. ",
Value: "yellow",
Icon: "/logo/yellow.png",
},
},
Default: "blue",
Size: 5,
HideSearch: useSearch,
})
_, _ = fmt.Fprintf(inv.Stdout, "%s is a good choice.\n", value.Name)
return err
}, useSearchOption),
},
}
return cmd
}
+1 -1
View File
@@ -21,7 +21,7 @@ func TestRename(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
+5 -5
View File
@@ -38,7 +38,7 @@ func TestRestart(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
ctx := testutil.Context(t, testutil.WaitLong)
@@ -69,7 +69,7 @@ func TestRestart(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
inv, root := clitest.New(t, "restart", workspace.Name, "--build-options")
@@ -123,7 +123,7 @@ func TestRestart(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
inv, root := clitest.New(t, "restart", workspace.Name,
@@ -202,7 +202,7 @@ func TestRestartWithParameters(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
cwr.RichParameterValues = []codersdk.WorkspaceBuildParameter{
{
Name: immutableParameterName,
@@ -250,7 +250,7 @@ func TestRestartWithParameters(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, mutableParamsResponse)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
cwr.RichParameterValues = []codersdk.WorkspaceBuildParameter{
{
Name: mutableParameterName,
+89 -73
View File
@@ -52,20 +52,20 @@ var (
)
const (
varURL = "url"
varToken = "token"
varAgentToken = "agent-token"
varAgentTokenFile = "agent-token-file"
varAgentURL = "agent-url"
varHeader = "header"
varHeaderCommand = "header-command"
varNoOpen = "no-open"
varNoVersionCheck = "no-version-warning"
varNoFeatureWarning = "no-feature-warning"
varForceTty = "force-tty"
varVerbose = "verbose"
varOrganizationSelect = "organization"
varDisableDirect = "disable-direct-connections"
varURL = "url"
varToken = "token"
varAgentToken = "agent-token"
varAgentTokenFile = "agent-token-file"
varAgentURL = "agent-url"
varHeader = "header"
varHeaderCommand = "header-command"
varNoOpen = "no-open"
varNoVersionCheck = "no-version-warning"
varNoFeatureWarning = "no-feature-warning"
varForceTty = "force-tty"
varVerbose = "verbose"
varDisableDirect = "disable-direct-connections"
varDisableNetworkTelemetry = "disable-network-telemetry"
notLoggedInMessage = "You are not logged in. Try logging in using 'coder login <url>'."
@@ -87,6 +87,8 @@ func (r *RootCmd) CoreSubcommands() []*serpent.Command {
r.login(),
r.logout(),
r.netcheck(),
r.notifications(),
r.organizations(),
r.portForward(),
r.publickey(),
r.resetPassword(),
@@ -95,7 +97,6 @@ func (r *RootCmd) CoreSubcommands() []*serpent.Command {
r.tokens(),
r.users(),
r.version(defaultVersionInfo),
r.organizations(),
// Workspace Commands
r.autoupdate(),
@@ -117,13 +118,14 @@ func (r *RootCmd) CoreSubcommands() []*serpent.Command {
r.stop(),
r.unfavorite(),
r.update(),
r.whoami(),
// Hidden
r.expCmd(),
r.gitssh(),
r.support(),
r.vscodeSSH(),
r.workspaceAgent(),
r.expCmd(),
r.support(),
}
}
@@ -436,6 +438,13 @@ func (r *RootCmd) Command(subcommands []*serpent.Command) (*serpent.Command, err
Value: serpent.BoolOf(&r.disableDirect),
Group: globalGroup,
},
{
Flag: varDisableNetworkTelemetry,
Env: "CODER_DISABLE_NETWORK_TELEMETRY",
Description: "Disable network telemetry. Network telemetry is collected when connecting to workspaces using the CLI, and is forwarded to the server. If telemetry is also enabled on the server, it may be sent to Coder. Network telemetry is used to measure network quality and detect regressions.",
Value: serpent.BoolOf(&r.disableNetworkTelemetry),
Group: globalGroup,
},
{
Flag: "debug-http",
Description: "Debug codersdk HTTP requests.",
@@ -451,15 +460,6 @@ func (r *RootCmd) Command(subcommands []*serpent.Command) (*serpent.Command, err
Value: serpent.StringOf(&r.globalConfig),
Group: globalGroup,
},
{
Flag: varOrganizationSelect,
FlagShorthand: "z",
Env: "CODER_ORGANIZATION",
Description: "Select which organization (uuid or name) to use This overrides what is present in the config file.",
Value: serpent.StringOf(&r.organizationSelect),
Hidden: true,
Group: globalGroup,
},
{
Flag: "version",
// This was requested by a customer to assist with their migration.
@@ -476,24 +476,24 @@ func (r *RootCmd) Command(subcommands []*serpent.Command) (*serpent.Command, err
// RootCmd contains parameters and helpers useful to all commands.
type RootCmd struct {
clientURL *url.URL
token string
globalConfig string
header []string
headerCommand string
agentToken string
agentTokenFile string
agentURL *url.URL
forceTTY bool
noOpen bool
verbose bool
organizationSelect string
versionFlag bool
disableDirect bool
debugHTTP bool
clientURL *url.URL
token string
globalConfig string
header []string
headerCommand string
agentToken string
agentTokenFile string
agentURL *url.URL
forceTTY bool
noOpen bool
verbose bool
versionFlag bool
disableDirect bool
debugHTTP bool
noVersionCheck bool
noFeatureWarning bool
disableNetworkTelemetry bool
noVersionCheck bool
noFeatureWarning bool
}
// InitClient authenticates the client with files from disk
@@ -632,52 +632,68 @@ func (r *RootCmd) createAgentClient() (*agentsdk.Client, error) {
return client, nil
}
// CurrentOrganization returns the currently active organization for the authenticated user.
func CurrentOrganization(r *RootCmd, inv *serpent.Invocation, client *codersdk.Client) (codersdk.Organization, error) {
conf := r.createConfig()
selected := r.organizationSelect
if selected == "" && conf.Organization().Exists() {
org, err := conf.Organization().Read()
if err != nil {
return codersdk.Organization{}, xerrors.Errorf("read selected organization from config file %q: %w", conf.Organization(), err)
}
selected = org
}
type OrganizationContext struct {
// FlagSelect is the value passed in via the --org flag
FlagSelect string
}
// Verify the org exists and the user is a member
func NewOrganizationContext() *OrganizationContext {
return &OrganizationContext{}
}
func (*OrganizationContext) optionName() string { return "Organization" }
func (o *OrganizationContext) AttachOptions(cmd *serpent.Command) {
cmd.Options = append(cmd.Options, serpent.Option{
Name: o.optionName(),
Description: "Select which organization (uuid or name) to use.",
// Only required if the user is a part of more than 1 organization.
// Otherwise, we can assume a default value.
Required: false,
Flag: "org",
FlagShorthand: "O",
Env: "CODER_ORGANIZATION",
Value: serpent.StringOf(&o.FlagSelect),
})
}
func (o *OrganizationContext) ValueSource(inv *serpent.Invocation) (string, serpent.ValueSource) {
opt := inv.Command.Options.ByName(o.optionName())
if opt == nil {
return o.FlagSelect, serpent.ValueSourceNone
}
return o.FlagSelect, opt.ValueSource
}
func (o *OrganizationContext) Selected(inv *serpent.Invocation, client *codersdk.Client) (codersdk.Organization, error) {
// Fetch the set of organizations the user is a member of.
orgs, err := client.OrganizationsByUser(inv.Context(), codersdk.Me)
if err != nil {
return codersdk.Organization{}, err
return codersdk.Organization{}, xerrors.Errorf("get organizations: %w", err)
}
// User manually selected an organization
if selected != "" {
if o.FlagSelect != "" {
index := slices.IndexFunc(orgs, func(org codersdk.Organization) bool {
return org.Name == selected || org.ID.String() == selected
return org.Name == o.FlagSelect || org.ID.String() == o.FlagSelect
})
if index < 0 {
return codersdk.Organization{}, xerrors.Errorf("organization %q not found, are you sure you are a member of this organization?", selected)
var names []string
for _, org := range orgs {
names = append(names, org.Name)
}
return codersdk.Organization{}, xerrors.Errorf("organization %q not found, are you sure you are a member of this organization? "+
"Valid options for '--org=' are [%s].", o.FlagSelect, strings.Join(names, ", "))
}
return orgs[index], nil
}
// User did not select an organization, so use the default.
index := slices.IndexFunc(orgs, func(org codersdk.Organization) bool {
return org.IsDefault
})
if index < 0 {
if len(orgs) == 1 {
// If there is no "isDefault", but only 1 org is present. We can just
// assume the single organization is correct. This is mainly a helper
// for cli hitting an old instance, or a user that belongs to a single
// org that is not the default.
return orgs[0], nil
}
return codersdk.Organization{}, xerrors.Errorf("unable to determine current organization. Use 'coder org set <org>' to select an organization to use")
if len(orgs) == 1 {
return orgs[0], nil
}
return orgs[index], nil
// No org selected, and we are more than 1? Return an error.
return codersdk.Organization{}, xerrors.Errorf("Must select an organization with --org=<org_name>.")
}
func splitNamedWorkspace(identifier string) (owner string, workspaceName string, err error) {
+110 -40
View File
@@ -55,6 +55,11 @@ import (
"cdr.dev/slog"
"cdr.dev/slog/sloggers/sloghuman"
"github.com/coder/pretty"
"github.com/coder/retry"
"github.com/coder/serpent"
"github.com/coder/wgtunnel/tunnelsdk"
"github.com/coder/coder/v2/buildinfo"
"github.com/coder/coder/v2/cli/clilog"
"github.com/coder/coder/v2/cli/cliui"
@@ -62,9 +67,9 @@ import (
"github.com/coder/coder/v2/cli/config"
"github.com/coder/coder/v2/coderd"
"github.com/coder/coder/v2/coderd/autobuild"
"github.com/coder/coder/v2/coderd/batchstats"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/awsiamrds"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbmem"
"github.com/coder/coder/v2/coderd/database/dbmetrics"
"github.com/coder/coder/v2/coderd/database/dbpurge"
@@ -74,6 +79,7 @@ import (
"github.com/coder/coder/v2/coderd/externalauth"
"github.com/coder/coder/v2/coderd/gitsshkey"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/oauthpki"
"github.com/coder/coder/v2/coderd/prometheusmetrics"
"github.com/coder/coder/v2/coderd/prometheusmetrics/insights"
@@ -87,7 +93,7 @@ import (
stringutil "github.com/coder/coder/v2/coderd/util/strings"
"github.com/coder/coder/v2/coderd/workspaceapps"
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
"github.com/coder/coder/v2/coderd/workspaceusage"
"github.com/coder/coder/v2/coderd/workspacestats"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/drpc"
"github.com/coder/coder/v2/cryptorand"
@@ -98,13 +104,9 @@ import (
"github.com/coder/coder/v2/provisionersdk"
sdkproto "github.com/coder/coder/v2/provisionersdk/proto"
"github.com/coder/coder/v2/tailnet"
"github.com/coder/pretty"
"github.com/coder/retry"
"github.com/coder/serpent"
"github.com/coder/wgtunnel/tunnelsdk"
)
func createOIDCConfig(ctx context.Context, vals *codersdk.DeploymentValues) (*coderd.OIDCConfig, error) {
func createOIDCConfig(ctx context.Context, logger slog.Logger, vals *codersdk.DeploymentValues) (*coderd.OIDCConfig, error) {
if vals.OIDC.ClientID == "" {
return nil, xerrors.Errorf("OIDC client ID must be set!")
}
@@ -112,6 +114,12 @@ func createOIDCConfig(ctx context.Context, vals *codersdk.DeploymentValues) (*co
return nil, xerrors.Errorf("OIDC issuer URL must be set!")
}
// Skipping issuer checks is not recommended.
if vals.OIDC.SkipIssuerChecks {
logger.Warn(ctx, "issuer checks with OIDC is disabled. This is not recommended as it can compromise the security of the authentication")
ctx = oidc.InsecureIssuerURLContext(ctx, vals.OIDC.IssuerURL.String())
}
oidcProvider, err := oidc.NewProvider(
ctx, vals.OIDC.IssuerURL.String(),
)
@@ -165,10 +173,14 @@ func createOIDCConfig(ctx context.Context, vals *codersdk.DeploymentValues) (*co
Provider: oidcProvider,
Verifier: oidcProvider.Verifier(&oidc.Config{
ClientID: vals.OIDC.ClientID.String(),
// Enabling this skips checking the "iss" claim in the token
// matches the issuer URL. This is not recommended.
SkipIssuerCheck: vals.OIDC.SkipIssuerChecks.Value(),
}),
EmailDomain: vals.OIDC.EmailDomain,
AllowSignups: vals.OIDC.AllowSignups.Value(),
UsernameField: vals.OIDC.UsernameField.String(),
NameField: vals.OIDC.NameField.String(),
EmailField: vals.OIDC.EmailField.String(),
AuthURLParams: vals.OIDC.AuthURLParams.Value,
IgnoreUserInfo: vals.OIDC.IgnoreUserInfo.Value(),
@@ -592,6 +604,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
SSHConfigOptions: configSSHOptions,
},
AllowWorkspaceRenames: vals.AllowWorkspaceRenames.Value(),
NotificationsEnqueuer: notifications.NewNoopEnqueuer(), // Changed further down if notifications enabled.
}
if httpServers.TLSConfig != nil {
options.TLSCertificates = httpServers.TLSConfig.Certificates
@@ -653,13 +666,17 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
// Missing:
// - Userinfo
// - Verify
oc, err := createOIDCConfig(ctx, vals)
oc, err := createOIDCConfig(ctx, options.Logger, vals)
if err != nil {
return xerrors.Errorf("create oidc config: %w", err)
}
options.OIDCConfig = oc
}
experiments := coderd.ReadExperiments(
options.Logger, options.DeploymentValues.Experiments.Value(),
)
// We'll read from this channel in the select below that tracks shutdown. If it remains
// nil, that case of the select will just never fire, but it's important not to have a
// "bare" read on this channel.
@@ -796,31 +813,18 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
cliui.Infof(inv.Stdout, "\n==> Logs will stream in below (press ctrl+c to gracefully exit):")
if vals.Telemetry.Enable {
gitAuth := make([]telemetry.GitAuth, 0)
// TODO:
var gitAuthConfigs []codersdk.ExternalAuthConfig
for _, cfg := range gitAuthConfigs {
gitAuth = append(gitAuth, telemetry.GitAuth{
Type: cfg.Type,
})
vals, err := vals.WithoutSecrets()
if err != nil {
return xerrors.Errorf("remove secrets from deployment values: %w", err)
}
options.Telemetry, err = telemetry.New(telemetry.Options{
BuiltinPostgres: builtinPostgres,
DeploymentID: deploymentID,
Database: options.Database,
Logger: logger.Named("telemetry"),
URL: vals.Telemetry.URL.Value(),
Wildcard: vals.WildcardAccessURL.String() != "",
DERPServerRelayURL: vals.DERP.Server.RelayURL.String(),
GitAuth: gitAuth,
GitHubOAuth: vals.OAuth2.Github.ClientID != "",
OIDCAuth: vals.OIDC.ClientID != "",
OIDCIssuerURL: vals.OIDC.IssuerURL.String(),
Prometheus: vals.Prometheus.Enable.Value(),
STUN: len(vals.DERP.Server.STUNAddresses) != 0,
Tunnel: tunnel != nil,
Experiments: vals.Experiments.Value(),
BuiltinPostgres: builtinPostgres,
DeploymentID: deploymentID,
Database: options.Database,
Logger: logger.Named("telemetry"),
URL: vals.Telemetry.URL.Value(),
Tunnel: tunnel != nil,
DeploymentConfig: vals,
ParseLicenseJWT: func(lic *telemetry.License) error {
// This will be nil when running in AGPL-only mode.
if options.ParseLicenseClaims == nil {
@@ -843,7 +847,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
}
defer options.Telemetry.Close()
} else {
logger.Warn(ctx, `telemetry disabled, unable to notify of security issues. Read more: https://coder.com/docs/v2/latest/admin/telemetry`)
logger.Warn(ctx, `telemetry disabled, unable to notify of security issues. Read more: https://coder.com/docs/admin/telemetry`)
}
// This prevents the pprof import from being accidentally deleted.
@@ -869,9 +873,9 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
options.SwaggerEndpoint = vals.Swagger.Enable.Value()
}
batcher, closeBatcher, err := batchstats.New(ctx,
batchstats.WithLogger(options.Logger.Named("batchstats")),
batchstats.WithStore(options.Database),
batcher, closeBatcher, err := workspacestats.NewBatcher(ctx,
workspacestats.BatcherWithLogger(options.Logger.Named("batchstats")),
workspacestats.BatcherWithStore(options.Database),
)
if err != nil {
return xerrors.Errorf("failed to create agent stats batcher: %w", err)
@@ -976,12 +980,39 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
defer purger.Close()
// Updates workspace usage
tracker := workspaceusage.New(options.Database,
workspaceusage.WithLogger(logger.Named("workspace_usage_tracker")),
tracker := workspacestats.NewTracker(options.Database,
workspacestats.TrackerWithLogger(logger.Named("workspace_usage_tracker")),
)
options.WorkspaceUsageTracker = tracker
defer tracker.Close()
// Manage notifications.
var (
notificationsManager *notifications.Manager
)
if experiments.Enabled(codersdk.ExperimentNotifications) {
cfg := options.DeploymentValues.Notifications
metrics := notifications.NewMetrics(options.PrometheusRegistry)
// The enqueuer is responsible for enqueueing notifications to the given store.
enqueuer, err := notifications.NewStoreEnqueuer(cfg, options.Database, templateHelpers(options), logger.Named("notifications.enqueuer"))
if err != nil {
return xerrors.Errorf("failed to instantiate notification store enqueuer: %w", err)
}
options.NotificationsEnqueuer = enqueuer
// The notification manager is responsible for:
// - creating notifiers and managing their lifecycles (notifiers are responsible for dequeueing/sending notifications)
// - keeping the store updated with status updates
notificationsManager, err = notifications.NewManager(cfg, options.Database, metrics, logger.Named("notifications.manager"))
if err != nil {
return xerrors.Errorf("failed to instantiate notification manager: %w", err)
}
// nolint:gocritic // TODO: create own role.
notificationsManager.Run(dbauthz.AsSystemRestricted(ctx))
}
// Wrap the server in middleware that redirects to the access URL if
// the request is not to a local IP.
var handler http.Handler = coderAPI.RootHandler
@@ -1044,7 +1075,7 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
autobuildTicker := time.NewTicker(vals.AutobuildPollInterval.Value())
defer autobuildTicker.Stop()
autobuildExecutor := autobuild.NewExecutor(
ctx, options.Database, options.Pubsub, coderAPI.TemplateScheduleStore, &coderAPI.Auditor, coderAPI.AccessControlStore, logger, autobuildTicker.C)
ctx, options.Database, options.Pubsub, coderAPI.TemplateScheduleStore, &coderAPI.Auditor, coderAPI.AccessControlStore, logger, autobuildTicker.C, options.NotificationsEnqueuer)
autobuildExecutor.Run()
hangDetectorTicker := time.NewTicker(vals.JobHangDetectorInterval.Value())
@@ -1062,10 +1093,10 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
case <-stopCtx.Done():
exitErr = stopCtx.Err()
waitForProvisionerJobs = true
_, _ = io.WriteString(inv.Stdout, cliui.Bold("Stop caught, waiting for provisioner jobs to complete and gracefully exiting. Use ctrl+\\ to force quit"))
_, _ = io.WriteString(inv.Stdout, cliui.Bold("Stop caught, waiting for provisioner jobs to complete and gracefully exiting. Use ctrl+\\ to force quit\n"))
case <-interruptCtx.Done():
exitErr = interruptCtx.Err()
_, _ = io.WriteString(inv.Stdout, cliui.Bold("Interrupt caught, gracefully exiting. Use ctrl+\\ to force quit"))
_, _ = io.WriteString(inv.Stdout, cliui.Bold("Interrupt caught, gracefully exiting. Use ctrl+\\ to force quit\n"))
case <-tunnelDone:
exitErr = xerrors.New("dev tunnel closed unexpectedly")
case <-pubsubWatchdogTimeout:
@@ -1101,6 +1132,21 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
// Cancel any remaining in-flight requests.
shutdownConns()
if notificationsManager != nil {
// Stop the notification manager, which will cause any buffered updates to the store to be flushed.
// If the Stop() call times out, messages that were sent but not reflected as such in the store will have
// their leases expire after a period of time and will be re-queued for sending.
// See CODER_NOTIFICATIONS_LEASE_PERIOD.
cliui.Info(inv.Stdout, "Shutting down notifications manager..."+"\n")
err = shutdownWithTimeout(notificationsManager.Stop, 5*time.Second)
if err != nil {
cliui.Warnf(inv.Stderr, "Notifications manager shutdown took longer than 5s, "+
"this may result in duplicate notifications being sent: %s\n", err)
} else {
cliui.Info(inv.Stdout, "Gracefully shut down notifications manager\n")
}
}
// Shut down provisioners before waiting for WebSockets
// connections to close.
var wg sync.WaitGroup
@@ -1240,6 +1286,15 @@ func (r *RootCmd) Server(newAPI func(context.Context, *coderd.Options) (*coderd.
return serverCmd
}
// templateHelpers builds a set of functions which can be called in templates.
// We build them here to avoid an import cycle by using coderd.Options in notifications.Manager.
// We can later use this to inject whitelabel fields when app name / logo URL are overridden.
func templateHelpers(options *coderd.Options) map[string]any {
return map[string]any{
"base_url": func() string { return options.AccessURL.String() },
}
}
// printDeprecatedOptions loops through all command options, and prints
// a warning for usage of deprecated options.
func PrintDeprecatedOptions() serpent.MiddlewareFunc {
@@ -1524,6 +1579,19 @@ func generateSelfSignedCertificate() (*tls.Certificate, error) {
return &cert, nil
}
// defaultCipherSuites is a list of safe cipher suites that we default to. This
// is different from Golang's list of defaults, which unfortunately includes
// `TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA`.
var defaultCipherSuites = func() []uint16 {
ret := []uint16{}
for _, suite := range tls.CipherSuites() {
ret = append(ret, suite.ID)
}
return ret
}()
// configureServerTLS returns the TLS config used for the Coderd server
// connections to clients. A logger is passed in to allow printing warning
// messages that do not block startup.
@@ -1554,6 +1622,8 @@ func configureServerTLS(ctx context.Context, logger slog.Logger, tlsMinVersion,
return nil, err
}
tlsConfig.CipherSuites = cipherIDs
} else {
tlsConfig.CipherSuites = defaultCipherSuites
}
switch tlsClientAuth {
+5 -2
View File
@@ -85,6 +85,7 @@ func (r *RootCmd) newCreateAdminUserCommand() *serpent.Command {
// Use the validator tags so we match the API's validation.
req := codersdk.CreateUserRequest{
Username: "username",
Name: "Admin User",
Email: "email@coder.com",
Password: "ValidPa$$word123!",
OrganizationID: uuid.New(),
@@ -116,6 +117,7 @@ func (r *RootCmd) newCreateAdminUserCommand() *serpent.Command {
return err
}
}
if newUserEmail == "" {
newUserEmail, err = cliui.Prompt(inv, cliui.PromptOptions{
Text: "Email",
@@ -189,10 +191,11 @@ func (r *RootCmd) newCreateAdminUserCommand() *serpent.Command {
ID: uuid.New(),
Email: newUserEmail,
Username: newUserUsername,
Name: "Admin User",
HashedPassword: []byte(hashedPassword),
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
RBACRoles: []string{rbac.RoleOwner()},
RBACRoles: []string{rbac.RoleOwner().String()},
LoginType: database.LoginTypePassword,
})
if err != nil {
@@ -222,7 +225,7 @@ func (r *RootCmd) newCreateAdminUserCommand() *serpent.Command {
UserID: newUser.ID,
CreatedAt: dbtime.Now(),
UpdatedAt: dbtime.Now(),
Roles: []string{rbac.RoleOrgAdmin(org.ID)},
Roles: []string{rbac.RoleOrgAdmin()},
})
if err != nil {
return xerrors.Errorf("insert organization member: %w", err)
+5 -4
View File
@@ -17,6 +17,7 @@ import (
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/userpassword"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/pty/ptytest"
"github.com/coder/coder/v2/testutil"
)
@@ -56,7 +57,7 @@ func TestServerCreateAdminUser(t *testing.T) {
require.NoError(t, err)
require.True(t, ok, "password does not match")
require.EqualValues(t, []string{rbac.RoleOwner()}, user.RBACRoles, "user does not have owner role")
require.EqualValues(t, []string{codersdk.RoleOwner}, user.RBACRoles, "user does not have owner role")
// Check that user is admin in every org.
orgs, err := db.GetOrganizations(ctx)
@@ -66,12 +67,12 @@ func TestServerCreateAdminUser(t *testing.T) {
orgIDs[org.ID] = struct{}{}
}
orgMemberships, err := db.GetOrganizationMembershipsByUserID(ctx, user.ID)
orgMemberships, err := db.OrganizationMembers(ctx, database.OrganizationMembersParams{UserID: user.ID})
require.NoError(t, err)
orgIDs2 := make(map[uuid.UUID]struct{}, len(orgMemberships))
for _, membership := range orgMemberships {
orgIDs2[membership.OrganizationID] = struct{}{}
assert.Equal(t, []string{rbac.RoleOrgAdmin(membership.OrganizationID)}, membership.Roles, "user is not org admin")
orgIDs2[membership.OrganizationMember.OrganizationID] = struct{}{}
assert.Equal(t, []string{rbac.RoleOrgAdmin()}, membership.OrganizationMember.Roles, "user is not org admin")
}
require.Equal(t, orgIDs, orgIDs2, "user is not in all orgs")
+22
View File
@@ -20,6 +20,28 @@ import (
"github.com/coder/serpent"
)
func Test_configureServerTLS(t *testing.T) {
t.Parallel()
t.Run("DefaultNoInsecureCiphers", func(t *testing.T) {
t.Parallel()
logger := slogtest.Make(t, nil)
cfg, err := configureServerTLS(context.Background(), logger, "tls12", "none", nil, nil, "", nil, false)
require.NoError(t, err)
require.NotEmpty(t, cfg)
insecureCiphers := tls.InsecureCipherSuites()
for _, cipher := range cfg.CipherSuites {
for _, insecure := range insecureCiphers {
if cipher == insecure.ID {
t.Logf("Insecure cipher found by default: %s", insecure.Name)
t.Fail()
}
}
}
})
}
func Test_configureCipherSuites(t *testing.T) {
t.Parallel()
+42 -31
View File
@@ -967,26 +967,32 @@ func TestServer(t *testing.T) {
assert.NoError(t, err)
// nolint:bodyclose
res, err = http.DefaultClient.Do(req)
return err == nil
}, testutil.WaitShort, testutil.IntervalFast)
defer res.Body.Close()
if err != nil {
return false
}
defer res.Body.Close()
scanner := bufio.NewScanner(res.Body)
hasActiveUsers := false
for scanner.Scan() {
// This metric is manually registered to be tracked in the server. That's
// why we test it's tracked here.
if strings.HasPrefix(scanner.Text(), "coderd_api_active_users_duration_hour") {
hasActiveUsers = true
continue
scanner := bufio.NewScanner(res.Body)
hasActiveUsers := false
for scanner.Scan() {
// This metric is manually registered to be tracked in the server. That's
// why we test it's tracked here.
if strings.HasPrefix(scanner.Text(), "coderd_api_active_users_duration_hour") {
hasActiveUsers = true
continue
}
if strings.HasPrefix(scanner.Text(), "coderd_db_query_latencies_seconds") {
t.Fatal("db metrics should not be tracked when --prometheus-collect-db-metrics is not enabled")
}
t.Logf("scanned %s", scanner.Text())
}
if strings.HasPrefix(scanner.Text(), "coderd_db_query_latencies_seconds") {
t.Fatal("db metrics should not be tracked when --prometheus-collect-db-metrics is not enabled")
if scanner.Err() != nil {
t.Logf("scanner err: %s", scanner.Err().Error())
return false
}
t.Logf("scanned %s", scanner.Text())
}
require.NoError(t, scanner.Err())
require.True(t, hasActiveUsers)
return hasActiveUsers
}, testutil.WaitShort, testutil.IntervalFast, "didn't find coderd_api_active_users_duration_hour in time")
})
t.Run("DBMetricsEnabled", func(t *testing.T) {
@@ -1017,20 +1023,25 @@ func TestServer(t *testing.T) {
assert.NoError(t, err)
// nolint:bodyclose
res, err = http.DefaultClient.Do(req)
return err == nil
}, testutil.WaitShort, testutil.IntervalFast)
defer res.Body.Close()
scanner := bufio.NewScanner(res.Body)
hasDBMetrics := false
for scanner.Scan() {
if strings.HasPrefix(scanner.Text(), "coderd_db_query_latencies_seconds") {
hasDBMetrics = true
if err != nil {
return false
}
t.Logf("scanned %s", scanner.Text())
}
require.NoError(t, scanner.Err())
require.True(t, hasDBMetrics)
defer res.Body.Close()
scanner := bufio.NewScanner(res.Body)
hasDBMetrics := false
for scanner.Scan() {
if strings.HasPrefix(scanner.Text(), "coderd_db_query_latencies_seconds") {
hasDBMetrics = true
}
t.Logf("scanned %s", scanner.Text())
}
if scanner.Err() != nil {
t.Logf("scanner err: %s", scanner.Err().Error())
return false
}
return hasDBMetrics
}, testutil.WaitShort, testutil.IntervalFast, "didn't find coderd_db_query_latencies_seconds in time")
})
})
t.Run("GitHubOAuth", func(t *testing.T) {
@@ -1347,7 +1358,7 @@ func TestServer(t *testing.T) {
}
return lastStat.Size() > 0
},
testutil.WaitShort,
dur, //nolint:gocritic
testutil.IntervalFast,
"file at %s should exist, last stat: %+v",
fiName, lastStat,
+1 -1
View File
@@ -20,7 +20,7 @@ func TestShow(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, completeWithAgent())
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
args := []string{
+65 -14
View File
@@ -6,7 +6,6 @@ import (
"os"
"time"
"github.com/jedib0t/go-pretty/v6/table"
"golang.org/x/xerrors"
tsspeedtest "tailscale.com/net/speedtest"
"tailscale.com/wgengine/capture"
@@ -19,12 +18,51 @@ import (
"github.com/coder/serpent"
)
type SpeedtestResult struct {
Overall SpeedtestResultInterval `json:"overall"`
Intervals []SpeedtestResultInterval `json:"intervals"`
}
type SpeedtestResultInterval struct {
StartTimeSeconds float64 `json:"start_time_seconds"`
EndTimeSeconds float64 `json:"end_time_seconds"`
ThroughputMbits float64 `json:"throughput_mbits"`
}
type speedtestTableItem struct {
Interval string `table:"Interval,nosort"`
Throughput string `table:"Throughput"`
}
func (r *RootCmd) speedtest() *serpent.Command {
var (
direct bool
duration time.Duration
direction string
pcapFile string
formatter = cliui.NewOutputFormatter(
cliui.ChangeFormatterData(cliui.TableFormat([]speedtestTableItem{}, []string{"Interval", "Throughput"}), func(data any) (any, error) {
res, ok := data.(SpeedtestResult)
if !ok {
// This should never happen
return "", xerrors.Errorf("expected speedtestResult, got %T", data)
}
tableRows := make([]any, len(res.Intervals)+2)
for i, r := range res.Intervals {
tableRows[i] = speedtestTableItem{
Interval: fmt.Sprintf("%.2f-%.2f sec", r.StartTimeSeconds, r.EndTimeSeconds),
Throughput: fmt.Sprintf("%.4f Mbits/sec", r.ThroughputMbits),
}
}
tableRows[len(res.Intervals)] = cliui.TableSeparator{}
tableRows[len(res.Intervals)+1] = speedtestTableItem{
Interval: fmt.Sprintf("%.2f-%.2f sec", res.Overall.StartTimeSeconds, res.Overall.EndTimeSeconds),
Throughput: fmt.Sprintf("%.4f Mbits/sec", res.Overall.ThroughputMbits),
}
return tableRows, nil
}),
cliui.JSONFormat(),
)
)
client := new(codersdk.Client)
cmd := &serpent.Command{
@@ -64,6 +102,9 @@ func (r *RootCmd) speedtest() *serpent.Command {
_, _ = fmt.Fprintln(inv.Stderr, "Direct connections disabled.")
opts.BlockEndpoints = true
}
if !r.disableNetworkTelemetry {
opts.EnableTelemetry = true
}
if pcapFile != "" {
s := capture.New()
opts.CaptureHook = s.LogPacket
@@ -101,14 +142,14 @@ func (r *RootCmd) speedtest() *serpent.Command {
}
peer := status.Peer[status.Peers()[0]]
if !p2p && direct {
cliui.Infof(inv.Stdout, "Waiting for a direct connection... (%dms via %s)", dur.Milliseconds(), peer.Relay)
cliui.Infof(inv.Stderr, "Waiting for a direct connection... (%dms via %s)", dur.Milliseconds(), peer.Relay)
continue
}
via := peer.Relay
if via == "" {
via = "direct"
}
cliui.Infof(inv.Stdout, "%dms via %s", dur.Milliseconds(), via)
cliui.Infof(inv.Stderr, "%dms via %s", dur.Milliseconds(), via)
break
}
} else {
@@ -124,24 +165,33 @@ func (r *RootCmd) speedtest() *serpent.Command {
default:
return xerrors.Errorf("invalid direction: %q", direction)
}
cliui.Infof(inv.Stdout, "Starting a %ds %s test...", int(duration.Seconds()), tsDir)
cliui.Infof(inv.Stderr, "Starting a %ds %s test...", int(duration.Seconds()), tsDir)
results, err := conn.Speedtest(ctx, tsDir, duration)
if err != nil {
return err
}
tableWriter := cliui.Table()
tableWriter.AppendHeader(table.Row{"Interval", "Throughput"})
var outputResult SpeedtestResult
startTime := results[0].IntervalStart
for _, r := range results {
if r.Total {
tableWriter.AppendSeparator()
outputResult.Intervals = make([]SpeedtestResultInterval, len(results)-1)
for i, r := range results {
interval := SpeedtestResultInterval{
StartTimeSeconds: r.IntervalStart.Sub(startTime).Seconds(),
EndTimeSeconds: r.IntervalEnd.Sub(startTime).Seconds(),
ThroughputMbits: r.MBitsPerSecond(),
}
if r.Total {
interval.StartTimeSeconds = 0
outputResult.Overall = interval
} else {
outputResult.Intervals[i] = interval
}
tableWriter.AppendRow(table.Row{
fmt.Sprintf("%.2f-%.2f sec", r.IntervalStart.Sub(startTime).Seconds(), r.IntervalEnd.Sub(startTime).Seconds()),
fmt.Sprintf("%.4f Mbits/sec", r.MBitsPerSecond()),
})
}
_, err = fmt.Fprintln(inv.Stdout, tableWriter.Render())
conn.Conn.SendSpeedtestTelemetry(outputResult.Overall.ThroughputMbits)
out, err := formatter.Format(inv.Context(), outputResult)
if err != nil {
return err
}
_, err = fmt.Fprintln(inv.Stdout, out)
return err
},
}
@@ -173,5 +223,6 @@ func (r *RootCmd) speedtest() *serpent.Command {
Value: serpent.StringOf(&pcapFile),
},
}
formatter.AttachOptions(&cmd.Options)
return cmd
}
+45
View File
@@ -1,7 +1,9 @@
package cli_test
import (
"bytes"
"context"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
@@ -10,6 +12,7 @@ import (
"cdr.dev/slog"
"cdr.dev/slog/sloggers/slogtest"
"github.com/coder/coder/v2/agent/agenttest"
"github.com/coder/coder/v2/cli"
"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/codersdk"
@@ -56,3 +59,45 @@ func TestSpeedtest(t *testing.T) {
})
<-cmdDone
}
func TestSpeedtestJson(t *testing.T) {
t.Parallel()
t.Skip("Potentially flaky test - see https://github.com/coder/coder/issues/6321")
if testing.Short() {
t.Skip("This test takes a minimum of 5ms per a hardcoded value in Tailscale!")
}
client, workspace, agentToken := setupWorkspaceForAgent(t)
_ = agenttest.New(t, client.URL, agentToken)
coderdtest.AwaitWorkspaceAgents(t, client, workspace.ID)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
require.Eventually(t, func() bool {
ws, err := client.Workspace(ctx, workspace.ID)
if !assert.NoError(t, err) {
return false
}
a := ws.LatestBuild.Resources[0].Agents[0]
return a.Status == codersdk.WorkspaceAgentConnected &&
a.LifecycleState == codersdk.WorkspaceAgentLifecycleReady
}, testutil.WaitLong, testutil.IntervalFast, "agent is not ready")
inv, root := clitest.New(t, "speedtest", "--output=json", workspace.Name)
clitest.SetupConfig(t, client, root)
out := bytes.NewBuffer(nil)
inv.Stdout = out
ctx, cancel = context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
inv.Logger = slogtest.Make(t, nil).Named("speedtest").Leveled(slog.LevelDebug)
cmdDone := tGo(t, func() {
err := inv.WithContext(ctx).Run()
assert.NoError(t, err)
})
<-cmdDone
var result cli.SpeedtestResult
require.NoError(t, json.Unmarshal(out.Bytes(), &result))
require.Len(t, result.Intervals, 5)
}
+45 -4
View File
@@ -12,6 +12,7 @@ import (
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"sync"
"time"
@@ -40,6 +41,10 @@ import (
"github.com/coder/serpent"
)
const (
disableUsageApp = "disable"
)
var (
workspacePollInterval = time.Minute
autostopNotifyCountdown = []time.Duration{30 * time.Minute}
@@ -57,6 +62,7 @@ func (r *RootCmd) ssh() *serpent.Command {
logDirPath string
remoteForwards []string
env []string
usageApp string
disableAutostart bool
)
client := new(codersdk.Client)
@@ -237,8 +243,9 @@ func (r *RootCmd) ssh() *serpent.Command {
}
conn, err := workspacesdk.New(client).
DialAgent(ctx, workspaceAgent.ID, &workspacesdk.DialAgentOptions{
Logger: logger,
BlockEndpoints: r.disableDirect,
Logger: logger,
BlockEndpoints: r.disableDirect,
EnableTelemetry: !r.disableNetworkTelemetry,
})
if err != nil {
return xerrors.Errorf("dial agent: %w", err)
@@ -251,6 +258,15 @@ func (r *RootCmd) ssh() *serpent.Command {
stopPolling := tryPollWorkspaceAutostop(ctx, client, workspace)
defer stopPolling()
usageAppName := getUsageAppName(usageApp)
if usageAppName != "" {
closeUsage := client.UpdateWorkspaceUsageWithBodyContext(ctx, workspace.ID, codersdk.PostWorkspaceUsageRequest{
AgentID: workspaceAgent.ID,
AppName: usageAppName,
})
defer closeUsage()
}
if stdio {
rawSSH, err := conn.SSH(ctx)
if err != nil {
@@ -421,6 +437,7 @@ func (r *RootCmd) ssh() *serpent.Command {
}
err = sshSession.Wait()
conn.SendDisconnectedTelemetry()
if err != nil {
if exitErr := (&gossh.ExitError{}); errors.As(err, &exitErr) {
// Clear the error since it's not useful beyond
@@ -509,6 +526,13 @@ func (r *RootCmd) ssh() *serpent.Command {
FlagShorthand: "e",
Value: serpent.StringArrayOf(&env),
},
{
Flag: "usage-app",
Description: "Specifies the usage app to use for workspace activity tracking.",
Env: "CODER_SSH_USAGE_APP",
Value: serpent.StringOf(&usageApp),
Hidden: true,
},
sshDisableAutostartOption(serpent.BoolOf(&disableAutostart)),
}
return cmd
@@ -711,12 +735,12 @@ func tryPollWorkspaceAutostop(ctx context.Context, client *codersdk.Client, work
lock := flock.New(filepath.Join(os.TempDir(), "coder-autostop-notify-"+workspace.ID.String()))
conditionCtx, cancelCondition := context.WithCancel(ctx)
condition := notifyCondition(conditionCtx, client, workspace.ID, lock)
stopFunc := notify.Notify(condition, workspacePollInterval, autostopNotifyCountdown...)
notifier := notify.New(condition, workspacePollInterval, autostopNotifyCountdown)
return func() {
// With many "ssh" processes running, `lock.TryLockContext` can be hanging until the context canceled.
// Without this cancellation, a CLI process with failed remote-forward could be hanging indefinitely.
cancelCondition()
stopFunc()
notifier.Close()
}
}
@@ -1044,3 +1068,20 @@ func (r stdioErrLogReader) Read(_ []byte) (int, error) {
r.l.Error(context.Background(), "reading from stdin in stdio mode is not allowed")
return 0, io.EOF
}
func getUsageAppName(usageApp string) codersdk.UsageAppName {
if usageApp == disableUsageApp {
return ""
}
allowedUsageApps := []string{
string(codersdk.UsageAppNameSSH),
string(codersdk.UsageAppNameVscode),
string(codersdk.UsageAppNameJetbrains),
}
if slices.Contains(allowedUsageApps, usageApp) {
return codersdk.UsageAppName(usageApp)
}
return codersdk.UsageAppNameSSH
}
+114 -3
View File
@@ -36,6 +36,7 @@ import (
"github.com/coder/coder/v2/agent"
"github.com/coder/coder/v2/agent/agentssh"
"github.com/coder/coder/v2/agent/agenttest"
agentproto "github.com/coder/coder/v2/agent/proto"
"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/coderd/coderdtest"
@@ -43,6 +44,7 @@ import (
"github.com/coder/coder/v2/coderd/database/dbfake"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/workspacestats/workspacestatstest"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/provisioner/echo"
"github.com/coder/coder/v2/provisionersdk/proto"
@@ -106,7 +108,7 @@ func TestSSH(t *testing.T) {
})
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
// Stop the workspace
workspaceBuild := coderdtest.CreateWorkspaceBuild(t, client, workspace, database.WorkspaceTransitionStop)
@@ -164,7 +166,7 @@ func TestSSH(t *testing.T) {
coderdtest.AwaitTemplateVersionJobCompleted(t, ownerClient, version.ID)
template := coderdtest.CreateTemplate(t, ownerClient, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, owner.OrganizationID, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
workspace := coderdtest.CreateWorkspace(t, client, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
cwr.AutomaticUpdates = codersdk.AutomaticUpdatesAlways
})
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
@@ -371,7 +373,7 @@ func TestSSH(t *testing.T) {
})
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, client, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
// Stop the workspace
workspaceBuild := coderdtest.CreateWorkspaceBuild(t, client, workspace, database.WorkspaceTransitionStop)
@@ -1292,6 +1294,115 @@ func TestSSH(t *testing.T) {
require.NoError(t, err)
require.Len(t, ents, 1, "expected one file in logdir %s", logDir)
})
t.Run("UpdateUsage", func(t *testing.T) {
t.Parallel()
type testCase struct {
name string
experiment bool
usageAppName string
expectedCalls int
expectedCountSSH int
expectedCountJetbrains int
expectedCountVscode int
}
tcs := []testCase{
{
name: "NoExperiment",
},
{
name: "Empty",
experiment: true,
expectedCalls: 1,
expectedCountSSH: 1,
},
{
name: "SSH",
experiment: true,
usageAppName: "ssh",
expectedCalls: 1,
expectedCountSSH: 1,
},
{
name: "Jetbrains",
experiment: true,
usageAppName: "jetbrains",
expectedCalls: 1,
expectedCountJetbrains: 1,
},
{
name: "Vscode",
experiment: true,
usageAppName: "vscode",
expectedCalls: 1,
expectedCountVscode: 1,
},
{
name: "InvalidDefaultsToSSH",
experiment: true,
usageAppName: "invalid",
expectedCalls: 1,
expectedCountSSH: 1,
},
{
name: "Disable",
experiment: true,
usageAppName: "disable",
},
}
for _, tc := range tcs {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
dv := coderdtest.DeploymentValues(t)
if tc.experiment {
dv.Experiments = []string{string(codersdk.ExperimentWorkspaceUsage)}
}
batcher := &workspacestatstest.StatsBatcher{
LastStats: &agentproto.Stats{},
}
admin, store := coderdtest.NewWithDatabase(t, &coderdtest.Options{
DeploymentValues: dv,
StatsBatcher: batcher,
})
admin.SetLogger(slogtest.Make(t, nil).Named("client").Leveled(slog.LevelDebug))
first := coderdtest.CreateFirstUser(t, admin)
client, user := coderdtest.CreateAnotherUser(t, admin, first.OrganizationID)
r := dbfake.WorkspaceBuild(t, store, database.Workspace{
OrganizationID: first.OrganizationID,
OwnerID: user.ID,
}).WithAgent().Do()
workspace := r.Workspace
agentToken := r.AgentToken
inv, root := clitest.New(t, "ssh", workspace.Name, fmt.Sprintf("--usage-app=%s", tc.usageAppName))
clitest.SetupConfig(t, client, root)
pty := ptytest.New(t).Attach(inv)
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
cmdDone := tGo(t, func() {
err := inv.WithContext(ctx).Run()
assert.NoError(t, err)
})
pty.ExpectMatch("Waiting")
_ = agenttest.New(t, client.URL, agentToken)
coderdtest.AwaitWorkspaceAgents(t, client, workspace.ID)
// Shells on Mac, Windows, and Linux all exit shells with the "exit" command.
pty.WriteLine("exit")
<-cmdDone
require.EqualValues(t, tc.expectedCalls, batcher.Called)
require.EqualValues(t, tc.expectedCountSSH, batcher.LastStats.SessionCountSsh)
require.EqualValues(t, tc.expectedCountJetbrains, batcher.LastStats.SessionCountJetbrains)
require.EqualValues(t, tc.expectedCountVscode, batcher.LastStats.SessionCountVscode)
})
}
})
}
//nolint:paralleltest // This test uses t.Setenv, parent test MUST NOT be parallel.
+5 -5
View File
@@ -109,7 +109,7 @@ func TestStart(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
// Stop the workspace
workspaceBuild := coderdtest.CreateWorkspaceBuild(t, client, workspace, database.WorkspaceTransitionStop)
@@ -163,7 +163,7 @@ func TestStart(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, echoResponses)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, member, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
// Stop the workspace
workspaceBuild := coderdtest.CreateWorkspaceBuild(t, client, workspace, database.WorkspaceTransitionStop)
@@ -211,7 +211,7 @@ func TestStartWithParameters(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, immutableParamsResponse)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
cwr.RichParameterValues = []codersdk.WorkspaceBuildParameter{
{
Name: immutableParameterName,
@@ -263,7 +263,7 @@ func TestStartWithParameters(t *testing.T) {
version := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, mutableParamsResponse)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
cwr.RichParameterValues = []codersdk.WorkspaceBuildParameter{
{
Name: mutableParameterName,
@@ -349,7 +349,7 @@ func TestStartAutoUpdate(t *testing.T) {
version1 := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version1.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version1.ID)
workspace := coderdtest.CreateWorkspace(t, member, owner.OrganizationID, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
workspace := coderdtest.CreateWorkspace(t, member, template.ID, func(cwr *codersdk.CreateWorkspaceRequest) {
cwr.AutomaticUpdates = codersdk.AutomaticUpdatesAlways
})
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
+3 -3
View File
@@ -100,7 +100,7 @@ func TestStatePush(t *testing.T) {
})
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, templateAdmin, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, templateAdmin, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
stateFile, err := os.CreateTemp(t.TempDir(), "")
require.NoError(t, err)
@@ -126,7 +126,7 @@ func TestStatePush(t *testing.T) {
})
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, templateAdmin, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, templateAdmin, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
inv, root := clitest.New(t, "state", "push", "--build", strconv.Itoa(int(workspace.LatestBuild.BuildNumber)), workspace.Name, "-")
clitest.SetupConfig(t, templateAdmin, root)
@@ -146,7 +146,7 @@ func TestStatePush(t *testing.T) {
})
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, version.ID)
workspace := coderdtest.CreateWorkspace(t, templateAdmin, owner.OrganizationID, template.ID)
workspace := coderdtest.CreateWorkspace(t, templateAdmin, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)
inv, root := clitest.New(t, "state", "push",
"--build", strconv.Itoa(int(workspace.LatestBuild.BuildNumber)),
+1
View File
@@ -254,6 +254,7 @@ func writeBundle(src *support.Bundle, dest *zip.Writer) error {
"deployment/health.json": src.Deployment.HealthReport,
"network/connection_info.json": src.Network.ConnectionInfo,
"network/netcheck.json": src.Network.Netcheck,
"network/interfaces.json": src.Network.Interfaces,
"workspace/template.json": src.Workspace.Template,
"workspace/template_version.json": src.Workspace.TemplateVersion,
"workspace/parameters.json": src.Workspace.Parameters,
+4
View File
@@ -197,6 +197,10 @@ func assertBundleContents(t *testing.T, path string, wantWorkspace bool, wantAge
var v derphealth.Report
decodeJSONFromZip(t, f, &v)
require.NotEmpty(t, v, "netcheck should not be empty")
case "network/interfaces.json":
var v healthsdk.InterfacesReport
decodeJSONFromZip(t, f, &v)
require.NotEmpty(t, v, "interfaces should not be empty")
case "workspace/workspace.json":
var v codersdk.Workspace
decodeJSONFromZip(t, f, &v)
+7 -5
View File
@@ -31,6 +31,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
dormancyAutoDeletion time.Duration
uploadFlags templateUploadFlags
orgContext = NewOrganizationContext()
)
client := new(codersdk.Client)
cmd := &serpent.Command{
@@ -68,7 +69,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
}
}
organization, err := CurrentOrganization(r, inv, client)
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
@@ -96,7 +97,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
var varsFiles []string
if !uploadFlags.stdin() {
varsFiles, err = DiscoverVarsFiles(uploadFlags.directory)
varsFiles, err = codersdk.DiscoverVarsFiles(uploadFlags.directory)
if err != nil {
return err
}
@@ -117,7 +118,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
return err
}
userVariableValues, err := ParseUserVariableValues(
userVariableValues, err := codersdk.ParseUserVariableValues(
varsFiles,
variablesFile,
commandLineVariables)
@@ -159,7 +160,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
RequireActiveVersion: requireActiveVersion,
}
_, err = client.CreateTemplate(inv.Context(), organization.ID, createReq)
template, err := client.CreateTemplate(inv.Context(), organization.ID, createReq)
if err != nil {
return err
}
@@ -170,7 +171,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
pretty.Sprint(cliui.DefaultStyles.DateTimeStamp, time.Now().Format(time.Stamp))+"! "+
"Developers can provision a workspace with this template using:")+"\n")
_, _ = fmt.Fprintln(inv.Stdout, " "+pretty.Sprint(cliui.DefaultStyles.Code, fmt.Sprintf("coder create --template=%q [workspace name]", templateName)))
_, _ = fmt.Fprintln(inv.Stdout, " "+pretty.Sprint(cliui.DefaultStyles.Code, fmt.Sprintf("coder create --template=%q --org=%q [workspace name]", templateName, template.OrganizationName)))
_, _ = fmt.Fprintln(inv.Stdout)
return nil
@@ -243,6 +244,7 @@ func (r *RootCmd) templateCreate() *serpent.Command {
cliui.SkipPromptOption(),
}
orgContext.AttachOptions(cmd)
cmd.Options = append(cmd.Options, uploadFlags.options()...)
return cmd
}
+1 -1
View File
@@ -18,7 +18,7 @@ import (
"github.com/coder/coder/v2/testutil"
)
func TestTemplateCreate(t *testing.T) {
func TestCliTemplateCreate(t *testing.T) {
t.Parallel()
t.Run("Create", func(t *testing.T) {
t.Parallel()
+3 -1
View File
@@ -15,6 +15,7 @@ import (
)
func (r *RootCmd) templateDelete() *serpent.Command {
orgContext := NewOrganizationContext()
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "delete [name...]",
@@ -32,7 +33,7 @@ func (r *RootCmd) templateDelete() *serpent.Command {
templates = []codersdk.Template{}
)
organization, err := CurrentOrganization(r, inv, client)
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
@@ -81,6 +82,7 @@ func (r *RootCmd) templateDelete() *serpent.Command {
return nil
},
}
orgContext.AttachOptions(cmd)
return cmd
}
+3 -1
View File
@@ -36,6 +36,7 @@ func (r *RootCmd) templateEdit() *serpent.Command {
requireActiveVersion bool
deprecationMessage string
disableEveryone bool
orgContext = NewOrganizationContext()
)
client := new(codersdk.Client)
@@ -77,7 +78,7 @@ func (r *RootCmd) templateEdit() *serpent.Command {
}
}
organization, err := CurrentOrganization(r, inv, client)
organization, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("get current organization: %w", err)
}
@@ -324,6 +325,7 @@ func (r *RootCmd) templateEdit() *serpent.Command {
},
cliui.SkipPromptOption(),
}
orgContext.AttachOptions(cmd)
return cmd
}
+3 -7
View File
@@ -12,7 +12,7 @@ import (
func (r *RootCmd) templateList() *serpent.Command {
formatter := cliui.NewOutputFormatter(
cliui.TableFormat([]templateTableRow{}, []string{"name", "last updated", "used by"}),
cliui.TableFormat([]templateTableRow{}, []string{"name", "organization name", "last updated", "used by"}),
cliui.JSONFormat(),
)
@@ -25,17 +25,13 @@ func (r *RootCmd) templateList() *serpent.Command {
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
organization, err := CurrentOrganization(r, inv, client)
if err != nil {
return err
}
templates, err := client.TemplatesByOrganization(inv.Context(), organization.ID)
templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{})
if err != nil {
return err
}
if len(templates) == 0 {
_, _ = fmt.Fprintf(inv.Stderr, "%s No templates found in %s! Create one:\n\n", Caret, color.HiWhiteString(organization.Name))
_, _ = fmt.Fprintf(inv.Stderr, "%s No templates found! Create one:\n\n", Caret)
_, _ = fmt.Fprintln(inv.Stderr, color.HiMagentaString(" $ coder templates push <directory>\n"))
return nil
}
+1 -5
View File
@@ -88,9 +88,6 @@ func TestTemplateList(t *testing.T) {
client := coderdtest.New(t, &coderdtest.Options{})
owner := coderdtest.CreateFirstUser(t, client)
org, err := client.Organization(context.Background(), owner.OrganizationID)
require.NoError(t, err)
templateAdmin, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.RoleTemplateAdmin())
inv, root := clitest.New(t, "templates", "list")
@@ -110,8 +107,7 @@ func TestTemplateList(t *testing.T) {
require.NoError(t, <-errC)
pty.ExpectMatch("No templates found in")
pty.ExpectMatch(org.Name)
pty.ExpectMatch("No templates found")
pty.ExpectMatch("Create one:")
})
}
+3 -1
View File
@@ -20,6 +20,7 @@ func (r *RootCmd) templatePull() *serpent.Command {
tarMode bool
zipMode bool
versionName string
orgContext = NewOrganizationContext()
)
client := new(codersdk.Client)
@@ -45,7 +46,7 @@ func (r *RootCmd) templatePull() *serpent.Command {
return xerrors.Errorf("either tar or zip can be selected")
}
organization, err := CurrentOrganization(r, inv, client)
organization, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("get current organization: %w", err)
}
@@ -187,6 +188,7 @@ func (r *RootCmd) templatePull() *serpent.Command {
},
cliui.SkipPromptOption(),
}
orgContext.AttachOptions(cmd)
return cmd
}
+17 -6
View File
@@ -34,6 +34,7 @@ func (r *RootCmd) templatePush() *serpent.Command {
provisionerTags []string
uploadFlags templateUploadFlags
activate bool
orgContext = NewOrganizationContext()
)
client := new(codersdk.Client)
cmd := &serpent.Command{
@@ -46,7 +47,7 @@ func (r *RootCmd) templatePush() *serpent.Command {
Handler: func(inv *serpent.Invocation) error {
uploadFlags.setWorkdir(workdir)
organization, err := CurrentOrganization(r, inv, client)
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
@@ -80,7 +81,7 @@ func (r *RootCmd) templatePush() *serpent.Command {
var varsFiles []string
if !uploadFlags.stdin() {
varsFiles, err = DiscoverVarsFiles(uploadFlags.directory)
varsFiles, err = codersdk.DiscoverVarsFiles(uploadFlags.directory)
if err != nil {
return err
}
@@ -100,7 +101,17 @@ func (r *RootCmd) templatePush() *serpent.Command {
return err
}
userVariableValues, err := ParseUserVariableValues(
// If user hasn't provided new provisioner tags, inherit ones from the active template version.
if len(tags) == 0 && template.ActiveVersionID != uuid.Nil {
templateVersion, err := client.TemplateVersion(inv.Context(), template.ActiveVersionID)
if err != nil {
return err
}
tags = templateVersion.Job.Tags
inv.Logger.Info(inv.Context(), "reusing existing provisioner tags", "tags", tags)
}
userVariableValues, err := codersdk.ParseUserVariableValues(
varsFiles,
variablesFile,
commandLineVariables)
@@ -216,6 +227,7 @@ func (r *RootCmd) templatePush() *serpent.Command {
cliui.SkipPromptOption(),
}
cmd.Options = append(cmd.Options, uploadFlags.options()...)
orgContext.AttachOptions(cmd)
return cmd
}
@@ -407,9 +419,8 @@ func createValidTemplateVersion(inv *serpent.Invocation, args createValidTemplat
if errors.As(err, &jobErr) && !codersdk.JobIsMissingParameterErrorCode(jobErr.Code) {
return nil, err
}
if err != nil {
return nil, err
}
return nil, err
}
version, err = client.TemplateVersion(inv.Context(), version.ID)
if err != nil {
+129
View File
@@ -403,6 +403,135 @@ func TestTemplatePush(t *testing.T) {
assert.NotEqual(t, template.ActiveVersionID, templateVersions[1].ID)
})
t.Run("ProvisionerTags", func(t *testing.T) {
t.Parallel()
t.Run("ChangeTags", func(t *testing.T) {
t.Parallel()
// Start the first provisioner
client, provisionerDocker, api := coderdtest.NewWithAPI(t, &coderdtest.Options{
IncludeProvisionerDaemon: true,
ProvisionerDaemonTags: map[string]string{
"docker": "true",
},
})
defer provisionerDocker.Close()
// Start the second provisioner
provisionerFoobar := coderdtest.NewTaggedProvisionerDaemon(t, api, "provisioner-foobar", map[string]string{
"foobar": "foobaz",
})
defer provisionerFoobar.Close()
owner := coderdtest.CreateFirstUser(t, client)
templateAdmin, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.RoleTemplateAdmin())
// Create the template with initial tagged template version.
templateVersion := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil, func(ctvr *codersdk.CreateTemplateVersionRequest) {
ctvr.ProvisionerTags = map[string]string{
"docker": "true",
}
})
templateVersion = coderdtest.AwaitTemplateVersionJobCompleted(t, client, templateVersion.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, templateVersion.ID)
// Push new template version without provisioner tags. CLI should reuse tags from the previous version.
source := clitest.CreateTemplateVersionSource(t, &echo.Responses{
Parse: echo.ParseComplete,
ProvisionApply: echo.ApplyComplete,
})
inv, root := clitest.New(t, "templates", "push", template.Name, "--directory", source, "--test.provisioner", string(database.ProvisionerTypeEcho), "--name", template.Name,
"--provisioner-tag", "foobar=foobaz")
clitest.SetupConfig(t, templateAdmin, root)
pty := ptytest.New(t).Attach(inv)
execDone := make(chan error)
go func() {
execDone <- inv.Run()
}()
matches := []struct {
match string
write string
}{
{match: "Upload", write: "yes"},
}
for _, m := range matches {
pty.ExpectMatch(m.match)
pty.WriteLine(m.write)
}
require.NoError(t, <-execDone)
// Verify template version tags
template, err := client.Template(context.Background(), template.ID)
require.NoError(t, err)
templateVersion, err = client.TemplateVersion(context.Background(), template.ActiveVersionID)
require.NoError(t, err)
require.EqualValues(t, map[string]string{"foobar": "foobaz", "owner": "", "scope": "organization"}, templateVersion.Job.Tags)
})
t.Run("DoNotChangeTags", func(t *testing.T) {
t.Parallel()
// Start the tagged provisioner
client := coderdtest.New(t, &coderdtest.Options{
IncludeProvisionerDaemon: true,
ProvisionerDaemonTags: map[string]string{
"docker": "true",
},
})
owner := coderdtest.CreateFirstUser(t, client)
templateAdmin, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID, rbac.RoleTemplateAdmin())
// Create the template with initial tagged template version.
templateVersion := coderdtest.CreateTemplateVersion(t, client, owner.OrganizationID, nil, func(ctvr *codersdk.CreateTemplateVersionRequest) {
ctvr.ProvisionerTags = map[string]string{
"docker": "true",
}
})
templateVersion = coderdtest.AwaitTemplateVersionJobCompleted(t, client, templateVersion.ID)
template := coderdtest.CreateTemplate(t, client, owner.OrganizationID, templateVersion.ID)
// Push new template version without provisioner tags. CLI should reuse tags from the previous version.
source := clitest.CreateTemplateVersionSource(t, &echo.Responses{
Parse: echo.ParseComplete,
ProvisionApply: echo.ApplyComplete,
})
inv, root := clitest.New(t, "templates", "push", template.Name, "--directory", source, "--test.provisioner", string(database.ProvisionerTypeEcho), "--name", template.Name)
clitest.SetupConfig(t, templateAdmin, root)
pty := ptytest.New(t).Attach(inv)
execDone := make(chan error)
go func() {
execDone <- inv.Run()
}()
matches := []struct {
match string
write string
}{
{match: "Upload", write: "yes"},
}
for _, m := range matches {
pty.ExpectMatch(m.match)
pty.WriteLine(m.write)
}
require.NoError(t, <-execDone)
// Verify template version tags
template, err := client.Template(context.Background(), template.ID)
require.NoError(t, err)
templateVersion, err = client.TemplateVersion(context.Background(), template.ActiveVersionID)
require.NoError(t, err)
require.EqualValues(t, map[string]string{"docker": "true", "owner": "", "scope": "organization"}, templateVersion.Job.Tags)
})
})
t.Run("Variables", func(t *testing.T) {
t.Parallel()
+19 -21
View File
@@ -17,10 +17,6 @@ func (r *RootCmd) templates() *serpent.Command {
Use: "templates",
Short: "Manage templates",
Long: "Templates are written in standard Terraform and describe the infrastructure for workspaces\n" + FormatExamples(
Example{
Description: "Make changes to your template, and plan the changes",
Command: "coder templates plan my-template",
},
Example{
Description: "Create or push an update to the template. Your developers can update their workspaces",
Command: "coder templates push my-template",
@@ -83,14 +79,15 @@ type templateTableRow struct {
Template codersdk.Template
// Used by table format:
Name string `json:"-" table:"name,default_sort"`
CreatedAt string `json:"-" table:"created at"`
LastUpdated string `json:"-" table:"last updated"`
OrganizationID uuid.UUID `json:"-" table:"organization id"`
Provisioner codersdk.ProvisionerType `json:"-" table:"provisioner"`
ActiveVersionID uuid.UUID `json:"-" table:"active version id"`
UsedBy string `json:"-" table:"used by"`
DefaultTTL time.Duration `json:"-" table:"default ttl"`
Name string `json:"-" table:"name,default_sort"`
CreatedAt string `json:"-" table:"created at"`
LastUpdated string `json:"-" table:"last updated"`
OrganizationID uuid.UUID `json:"-" table:"organization id"`
OrganizationName string `json:"-" table:"organization name"`
Provisioner codersdk.ProvisionerType `json:"-" table:"provisioner"`
ActiveVersionID uuid.UUID `json:"-" table:"active version id"`
UsedBy string `json:"-" table:"used by"`
DefaultTTL time.Duration `json:"-" table:"default ttl"`
}
// templateToRows converts a list of templates to a list of templateTableRow for
@@ -99,15 +96,16 @@ func templatesToRows(templates ...codersdk.Template) []templateTableRow {
rows := make([]templateTableRow, len(templates))
for i, template := range templates {
rows[i] = templateTableRow{
Template: template,
Name: template.Name,
CreatedAt: template.CreatedAt.Format("January 2, 2006"),
LastUpdated: template.UpdatedAt.Format("January 2, 2006"),
OrganizationID: template.OrganizationID,
Provisioner: template.Provisioner,
ActiveVersionID: template.ActiveVersionID,
UsedBy: pretty.Sprint(cliui.DefaultStyles.Fuchsia, formatActiveDevelopers(template.ActiveUserCount)),
DefaultTTL: (time.Duration(template.DefaultTTLMillis) * time.Millisecond),
Template: template,
Name: template.Name,
CreatedAt: template.CreatedAt.Format("January 2, 2006"),
LastUpdated: template.UpdatedAt.Format("January 2, 2006"),
OrganizationID: template.OrganizationID,
OrganizationName: template.OrganizationName,
Provisioner: template.Provisioner,
ActiveVersionID: template.ActiveVersionID,
UsedBy: pretty.Sprint(cliui.DefaultStyles.Fuchsia, formatActiveDevelopers(template.ActiveUserCount)),
DefaultTTL: (time.Duration(template.DefaultTTLMillis) * time.Millisecond),
}
}
+7 -3
View File
@@ -31,6 +31,7 @@ func (r *RootCmd) setArchiveTemplateVersion(archive bool) *serpent.Command {
pastVerb = "unarchived"
}
orgContext := NewOrganizationContext()
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: presentVerb + " <template-name> [template-version-names...] ",
@@ -47,7 +48,7 @@ func (r *RootCmd) setArchiveTemplateVersion(archive bool) *serpent.Command {
versions []codersdk.TemplateVersion
)
organization, err := CurrentOrganization(r, inv, client)
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
@@ -92,6 +93,7 @@ func (r *RootCmd) setArchiveTemplateVersion(archive bool) *serpent.Command {
return nil
},
}
orgContext.AttachOptions(cmd)
return cmd
}
@@ -99,6 +101,7 @@ func (r *RootCmd) setArchiveTemplateVersion(archive bool) *serpent.Command {
func (r *RootCmd) archiveTemplateVersions() *serpent.Command {
var all serpent.Bool
client := new(codersdk.Client)
orgContext := NewOrganizationContext()
cmd := &serpent.Command{
Use: "archive [template-name...] ",
Short: "Archive unused or failed template versions from a given template(s)",
@@ -121,7 +124,7 @@ func (r *RootCmd) archiveTemplateVersions() *serpent.Command {
templates = []codersdk.Template{}
)
organization, err := CurrentOrganization(r, inv, client)
organization, err := orgContext.Selected(inv, client)
if err != nil {
return err
}
@@ -166,7 +169,7 @@ func (r *RootCmd) archiveTemplateVersions() *serpent.Command {
inv.Stdout, fmt.Sprintf("Archived %d versions from "+pretty.Sprint(cliui.DefaultStyles.Keyword, template.Name)+" at "+cliui.Timestamp(time.Now()), len(resp.ArchivedIDs)),
)
if ok, _ := inv.ParsedFlags().GetBool("verbose"); err == nil && ok {
if ok, _ := inv.ParsedFlags().GetBool("verbose"); ok {
data, err := json.Marshal(resp)
if err != nil {
return xerrors.Errorf("marshal verbose response: %w", err)
@@ -179,6 +182,7 @@ func (r *RootCmd) archiveTemplateVersions() *serpent.Command {
return nil
},
}
orgContext.AttachOptions(cmd)
return cmd
}
+3 -1
View File
@@ -51,6 +51,7 @@ func (r *RootCmd) templateVersionsList() *serpent.Command {
cliui.JSONFormat(),
)
client := new(codersdk.Client)
orgContext := NewOrganizationContext()
var includeArchived serpent.Bool
@@ -93,7 +94,7 @@ func (r *RootCmd) templateVersionsList() *serpent.Command {
},
},
Handler: func(inv *serpent.Invocation) error {
organization, err := CurrentOrganization(r, inv, client)
organization, err := orgContext.Selected(inv, client)
if err != nil {
return xerrors.Errorf("get current organization: %w", err)
}
@@ -122,6 +123,7 @@ func (r *RootCmd) templateVersionsList() *serpent.Command {
},
}
orgContext.AttachOptions(cmd)
formatter.AttachOptions(&cmd.Options)
return cmd
}
+9
View File
@@ -27,6 +27,7 @@ SUBCOMMANDS:
login Authenticate with Coder deployment
logout Unauthenticate your local session
netcheck Print network debug information for DERP and STUN
notifications Manage Coder notifications
open Open a workspace
ping Ping a workspace
port-forward Forward ports from a workspace to the local machine. For
@@ -55,6 +56,7 @@ SUBCOMMANDS:
date
users Manage users
version Show coder version
whoami Fetch authenticated user info for Coder deployment
GLOBAL OPTIONS:
Global options are applied to all commands. They can be set using environment
@@ -66,6 +68,13 @@ variables or flags.
--disable-direct-connections bool, $CODER_DISABLE_DIRECT_CONNECTIONS
Disable direct (P2P) connections to workspaces.
--disable-network-telemetry bool, $CODER_DISABLE_NETWORK_TELEMETRY
Disable network telemetry. Network telemetry is collected when
connecting to workspaces using the CLI, and is forwarded to the
server. If telemetry is also enabled on the server, it may be sent to
Coder. Network telemetry is used to measure network quality and detect
regressions.
--global-config string, $CODER_CONFIG_DIR (default: ~/.config/coderv2)
Path to the global `coder` config directory.
+3
View File
@@ -18,6 +18,9 @@ OPTIONS:
--auth string, $CODER_AGENT_AUTH (default: token)
Specify the authentication type to use for the agent.
--block-file-transfer bool, $CODER_AGENT_BLOCK_FILE_TRANSFER (default: false)
Block file transfer using known applications: nc,rsync,scp,sftp.
--debug-address string, $CODER_AGENT_DEBUG_ADDRESS (default: 127.0.0.1:2113)
The bind address to serve a debug HTTP server.
+3
View File
@@ -10,6 +10,9 @@ USAGE:
$ coder create <username>/<workspace_name>
OPTIONS:
-O, --org string, $CODER_ORGANIZATION
Select which organization (uuid or name) to use.
--automatic-updates string, $CODER_WORKSPACE_AUTOMATIC_UPDATES (default: never)
Specify automatic updates setting for the workspace (accepts 'always'
or 'never').
+3 -2
View File
@@ -13,8 +13,9 @@ OPTIONS:
-c, --column string-array (default: workspace,template,status,healthy,last built,current version,outdated,starts at,stops after)
Columns to display in table output. Available columns: favorite,
workspace, template, status, healthy, last built, current version,
outdated, starts at, starts next, stops after, stops next, daily cost.
workspace, organization id, organization name, template, status,
healthy, last built, current version, outdated, starts at, starts
next, stops after, stops next, daily cost.
-o, --output string (default: table)
Output format. Available formats: table, json.
+1
View File
@@ -7,6 +7,7 @@
"owner_name": "testuser",
"owner_avatar_url": "",
"organization_id": "[first org ID]",
"organization_name": "first-organization",
"template_id": "[template ID]",
"template_name": "test-template",
"template_display_name": "",
+3
View File
@@ -10,6 +10,9 @@ OPTIONS:
Specifies an email address to use if creating the first user for the
deployment.
--first-user-full-name string, $CODER_FIRST_USER_FULL_NAME
Specifies a human-readable name for the first user of the deployment.
--first-user-password string, $CODER_FIRST_USER_PASSWORD
Specifies a password to use if creating the first user for the
deployment.
+28
View File
@@ -0,0 +1,28 @@
coder v0.0.0-devel
USAGE:
coder notifications
Manage Coder notifications
Aliases: notification
Administrators can use these commands to change notification settings.
- Pause Coder notifications. Administrators can temporarily stop notifiers
from
dispatching messages in case of the target outage (for example: unavailable
SMTP
server or Webhook not responding).:
$ coder notifications pause
- Resume Coder notifications:
$ coder notifications resume
SUBCOMMANDS:
pause Pause notifications
resume Resume notifications
———
Run `coder --help` for a list of global options.
+9
View File
@@ -0,0 +1,9 @@
coder v0.0.0-devel
USAGE:
coder notifications pause
Pause notifications
———
Run `coder --help` for a list of global options.
+9
View File
@@ -0,0 +1,9 @@
coder v0.0.0-devel
USAGE:
coder notifications resume
Resume notifications
———
Run `coder --help` for a list of global options.
+77
View File
@@ -326,6 +326,74 @@ can safely ignore these settings.
Minimum supported version of TLS. Accepted values are "tls10",
"tls11", "tls12" or "tls13".
NOTIFICATIONS OPTIONS:
Configure how notifications are processed and delivered.
--notifications-dispatch-timeout duration, $CODER_NOTIFICATIONS_DISPATCH_TIMEOUT (default: 1m0s)
How long to wait while a notification is being sent before giving up.
--notifications-max-send-attempts int, $CODER_NOTIFICATIONS_MAX_SEND_ATTEMPTS (default: 5)
The upper limit of attempts to send a notification.
--notifications-method string, $CODER_NOTIFICATIONS_METHOD (default: smtp)
Which delivery method to use (available options: 'smtp', 'webhook').
NOTIFICATIONS / EMAIL OPTIONS:
Configure how email notifications are sent.
--notifications-email-force-tls bool, $CODER_NOTIFICATIONS_EMAIL_FORCE_TLS (default: false)
Force a TLS connection to the configured SMTP smarthost.
--notifications-email-from string, $CODER_NOTIFICATIONS_EMAIL_FROM
The sender's address to use.
--notifications-email-hello string, $CODER_NOTIFICATIONS_EMAIL_HELLO (default: localhost)
The hostname identifying the SMTP server.
--notifications-email-smarthost host:port, $CODER_NOTIFICATIONS_EMAIL_SMARTHOST (default: localhost:587)
The intermediary SMTP host through which emails are sent.
NOTIFICATIONS / EMAIL / EMAIL AUTHENTICATION OPTIONS:
Configure SMTP authentication options.
--notifications-email-auth-identity string, $CODER_NOTIFICATIONS_EMAIL_AUTH_IDENTITY
Identity to use with PLAIN authentication.
--notifications-email-auth-password string, $CODER_NOTIFICATIONS_EMAIL_AUTH_PASSWORD
Password to use with PLAIN/LOGIN authentication.
--notifications-email-auth-password-file string, $CODER_NOTIFICATIONS_EMAIL_AUTH_PASSWORD_FILE
File from which to load password for use with PLAIN/LOGIN
authentication.
--notifications-email-auth-username string, $CODER_NOTIFICATIONS_EMAIL_AUTH_USERNAME
Username to use with PLAIN/LOGIN authentication.
NOTIFICATIONS / EMAIL / EMAIL TLS OPTIONS:
Configure TLS for your SMTP server target.
--notifications-email-tls-ca-cert-file string, $CODER_NOTIFICATIONS_EMAIL_TLS_CACERTFILE
CA certificate file to use.
--notifications-email-tls-cert-file string, $CODER_NOTIFICATIONS_EMAIL_TLS_CERTFILE
Certificate file to use.
--notifications-email-tls-cert-key-file string, $CODER_NOTIFICATIONS_EMAIL_TLS_CERTKEYFILE
Certificate key file to use.
--notifications-email-tls-server-name string, $CODER_NOTIFICATIONS_EMAIL_TLS_SERVERNAME
Server name to verify against the target certificate.
--notifications-email-tls-skip-verify bool, $CODER_NOTIFICATIONS_EMAIL_TLS_SKIPVERIFY
Skip verification of the target server's certificate (insecure).
--notifications-email-tls-starttls bool, $CODER_NOTIFICATIONS_EMAIL_TLS_STARTTLS
Enable STARTTLS to upgrade insecure SMTP connections using TLS.
NOTIFICATIONS / WEBHOOK OPTIONS:
--notifications-webhook-endpoint url, $CODER_NOTIFICATIONS_WEBHOOK_ENDPOINT
The endpoint to which to send webhooks.
OAUTH2 / GITHUB OPTIONS:
--oauth2-github-allow-everyone bool, $CODER_OAUTH2_GITHUB_ALLOW_EVERYONE
Allow all logins, setting this option means allowed orgs and teams
@@ -407,6 +475,9 @@ OIDC OPTIONS:
--oidc-issuer-url string, $CODER_OIDC_ISSUER_URL
Issuer URL to use for Login with OIDC.
--oidc-name-field string, $CODER_OIDC_NAME_FIELD (default: name)
OIDC claim field to use as the name.
--oidc-group-regex-filter regexp, $CODER_OIDC_GROUP_REGEX_FILTER (default: .*)
If provided any group name not matching the regex is ignored. This
allows for filtering out groups that are not needed. This filter is
@@ -442,6 +513,12 @@ OIDC OPTIONS:
The custom text to show on the error page informing about disabled
OIDC signups. Markdown format is supported.
--dangerous-oidc-skip-issuer-checks bool, $CODER_DANGEROUS_OIDC_SKIP_ISSUER_CHECKS
OIDC issuer urls must match in the request, the id_token 'iss' claim,
and in the well-known configuration. This flag disables that
requirement, and can lead to an insecure OIDC configuration. It is not
recommended to use this flag.
PROVISIONING OPTIONS:
Tune the behavior of the provisioner, which is responsible for creating,
updating, and deleting workspace resources.
+7
View File
@@ -6,6 +6,10 @@ USAGE:
Run upload and download tests from your machine to a workspace
OPTIONS:
-c, --column string-array (default: Interval,Throughput)
Columns to display in table output. Available columns: Interval,
Throughput.
-d, --direct bool
Specifies whether to wait for a direct connection before testing
speed.
@@ -14,6 +18,9 @@ OPTIONS:
Specifies whether to run in reverse mode where the client receives and
the server sends.
-o, --output string (default: table)
Output format. Available formats: table, json.
--pcap-file string
Specifies a file to write a network capture to.

Some files were not shown because too many files have changed in this diff Show More