51 Commits
Author SHA1 Message Date
Ehab Younes fc01bee831 fix: keep new API keys within the caller's scopes and allow list (#30256)
A scoped key holding api_key:create could mint a broader key, e.g. a token scoped to [api_key:create user:read] could mint coder:all.

- New keys must be covered by the caller's scopes and allow list, and inherit them when none are requested
- Requests beyond the caller return 403
- New key expiry is capped at the caller's
- Covers POST /users/{user}/keys/tokens, POST /users/{user}/keys, app auth-redirect, and /oauth2/authorize (invalid_scope on excess grants or a restricted session allow list)
- coder:all sessions, including browser logins, behave as before
- Not addressed: workspace start still mints a coder:all key for the owner
2026-10-07 11:43:19 +03:00
Nick Vigilante 4a184ca54a feat: add generated API key scopes reference (DOCS-135) (#29307)
## Summary

Coder validates every requested API key scope against a curated public
catalog in `coderd/rbac`, but the docs never listed it. Readers had to
infer the requestable set from the `codersdk.APIKeyScope` enum, which is
a superset that includes internal scopes a token cannot carry.

This adds `scripts/scopesdocgen`, which renders
`docs/reference/api-key-scopes.md` from `rbac.ExternalScopeNames` and
the policy definitions behind it:

- built-in scopes (`coder:all`, `coder:application_connect`)
- composite `coder:*` scopes, each with the permissions it expands to
- low-level `resource:action` scopes, with the action descriptions the
policy declares
- the deprecated `all` / `application_connect` aliases and their
canonical spellings

The generator is wired into `make gen`, so CI fails when the scope
catalog and the page drift apart.

## Also in this change

- `coderd/apikey.go`: the unrequestable-scope `400` detail pointed at
`admin/users/sessions-tokens#api-key-scopes`, which only ever held a
partial list. It now points at the generated reference.
- `docs/admin/users/sessions-tokens.md`: the partial enumeration and the
"read the schema, but not all of it applies" caveat are replaced with a
link to the reference. The how-to content stays.

## Verification

- `go test ./scripts/scopesdocgen` covers the sentence formatting, the
scope partitioning, and a guard that every name in
`rbac.ExternalScopeNames()` appears on the rendered page.
- `go test ./coderd -run
'TestTokenScoped|TestCreateTokenScopes|TestExternalScopesAreStorable|TestTokenLegacySingularScopeCompat'`
passes, confirming the page's claims about the default scope and the
rejection of internal scopes.
- `make lint/emdash`, `make lint/docs-html`, `make lint/check-scopes`,
`pnpm run check-docs`, and Vale on the changed pages are clean. Full
`make pre-commit` passed.

<details>
<summary>Context and scope decisions</summary>

Part of the DOCS Automated reference documentation project, which tracks
generating reference pages from product source of truth instead of
maintaining them by hand. DOCS-135 is the first item: it was filed as
"wire up the existing generator," but `scripts/apikeyscopesgen` emits Go
(`codersdk/apikey_scopes_gen.go`), not documentation, so there was no
generator output to surface and this adds one.

Decisions made while implementing:

- **Placement.** `docs/reference/api-key-scopes.md`, as a direct child
of Reference rather than inside `docs/reference/api/`, because that
directory is owned by the swagger generator.
- **Page shape.** Follows the `scripts/docgenenv` convention for
generated reference pages: the generated marker and page metadata in
front matter, the generated-content banner in the body, and sections
starting at level two because the front-matter title renders as the page
heading.
- **Public scopes only.** The page lists what `rbac.IsExternalScope`
accepts. Internal `resource:action` pairs are deliberately excluded,
which is the distinction the old schema link failed to make.
- **Acronym handling.** Policy action descriptions are lowercase source
strings (`"ssh into a given workspace"`). The generator restores the
casing of a small set of leading acronyms rather than editing the RBAC
package, so the change stays inside the docs pipeline.

Sibling backlog items turned out to be already delivered and are being
rescoped separately: `metricsdocgen` and `auditdocgen` already write
into their docs pages, and `scripts/configdocgen` already generates the
configuration reference.

</details>

---

Generated with Coder Agents on behalf of @nickvigilante. Linear:
[DOCS-135](https://linear.app/codercom/issue/DOCS-135/wave-1-wire-up-api-key-scopes-reference-to-docs)


## Product UI impact, please read

This PR corrects three RBAC action description strings in
`coderd/rbac/policy/policy.go`:

| Action | Before | After |
|---|---|---|
| `workspace:start` | allows starting a workspace | start a workspace |
| `workspace:stop` | allows stopping a workspace | stop a workspace |
| `api_key:update` | update an api key, eg expires | update an api key,
for example its expiry |

These were internal-facing until this PR, which is what made them worth
fixing: the new reference page renders them verbatim to operators, and
"eg expires" is not decodable by a reader without codebase context.

**They are not docs-only.** `make gen` propagates them to
`coderd/rbac/object_gen.go` and
`site/src/api/rbacresourcesGenerated.ts`, and
`CreateEditRolePageView.tsx` renders the description next to each action
in the custom roles editor. So this changes admin UI copy, and
`CreateEditRolePageView.stories.tsx` means Pixel may now report a
genuine snapshot diff on that component rather than the pre-existing
failure noted below.

The new wording matches the convention the rest of the table already
follows (`ssh into a given workspace`, `create an AI Gateway key`), so
this makes the UI more internally consistent, not less. Flagging it
explicitly because a docs PR changing product copy deserves an owner's
eyes rather than a silent merge. Happy to split it out if RBAC or
frontend would rather own it, with the caveat that the reference page
would then publish `eg expires` in the meantime.

<details>
<summary>CI note: Storybook / Pixel failure</summary>

The `Storybook` check fails at its `Snapshot` step, and `Pixel / Review`
reports `build failed` with no snapshots processed.

**Updated:** this note originally said the branch touched no files under
`site/`. That is no longer true. Correcting the RBAC policy description
strings (CRF-24) required `make gen`, which regenerated
`site/src/api/rbacresourcesGenerated.ts` alongside
`coderd/rbac/object_gen.go`. That file is a generated string table with
no rendered component behind it, so it still cannot account for a
Storybook snapshot or Pixel build failure, but the original
justification no longer holds and is replaced by this one. The failure
predates that change: it was present when the branch genuinely had no
`site/` diff. Every other check passes.

</details>
2026-10-01 16:09:01 -04:00
Bobby HoandMcKayla はな c9fc5b7ea1 fix: canonicalize API key scope aliases at ingress (#28322)
`rbac.IsExternalScope` accepts `all` and `application_connect`, neither
of which is an `api_key_scope` enum member. The plural `Scopes` field
stored the name as given, so `{"scopes":["all"]}` passed validation and
then 500'd inside `apikey.Generate` with `invalid API key scope: "all"`.
Reachable from `coder tokens create --scope all`, from the spellings
`docs/admin/users/sessions-tokens.md` taught, and from the `codersdk`
constants exported for exactly this purpose.

- Canonicalize inside `apikey.Generate`, in the loop that already
validates each name. One statement covers every caller and all three
input paths: plural `Scopes`, deprecated singular `Scope`, and the
default. Replaces two open-coded switches and the handler's own
per-element copy, so one place decides the stored spelling and the
handler only decides what may be requested.
- Deduplicate in the same pass. An alias and its canonical spelling are
two names going in and one name in the column.
- `ExternalScopeNames()` lists every name `IsExternalScope` accepts,
instead of dropping catalog entries that fail to parse. A curated entry
that cannot be stored used to pass every test and 500 at runtime; it now
fails two.
- Split the 400. A misspelled name and an internal `api_key_scope`
member need different words, since no re-spelling makes the second
requestable. Both rejection sites share one helper that names the case
and links the docs.
- Add reject-path tests for `not_a_real_scope` and `debug_info:read`.
The second is a valid enum member the rbac catalog treats as internal,
so before this both handler guards could be deleted with the suite still
green. A further case pins that plural `Scopes` wins when a caller sets
both fields.
- `TestExternalScopesAreStorable` pins the class rather than the two
known instances: every public rbac scope name must be storable.
`coderd/rbac` cannot assert this itself, since `database` imports `rbac`
and not the reverse.
- Docs use the canonical spellings, link the `codersdk.APIKeyScope`
schema, and say which scopes a token cannot request.

Egress is unchanged: `convertAPIKey` still derives a legacy singular
name on the way out. `ExternalScopeNames()` returns the same 57 names as
before, and `codersdk/apikey_scopes_gen.go` regenerates identically.

`rbac.CanonicalScopeName` merged with #28167, so this applies to `main`
and reviews on its own. The OAuth2 provider ignores scopes entirely
today (`authorize.go:237`, `tokens.go:377`, `tokens.go:520`), so it is
unaffected until those TODOs resolve.

Deferred from review: PLAT-528, PLAT-529, PLAT-530, and PLAT-532.
PLAT-532 covers `{"scopes":[]}` and `{"allow_list":[]}` defaulting open,
which predates this PR.

---------

Co-authored-by: McKayla はな <mckayla@hey.com>
2026-08-25 17:12:51 -07:00
Atif Ali fad69df710 fix: correct SCIM Swagger try it out URLs (#24779) 2026-05-05 02:54:03 +05:00
Kyle Carberry 8c8b307b97 fix: persist session cookie to disk to prevent PWA logout (#23746) 2026-04-01 09:54:59 -04:00
Kacper Sawicki 1e274063d4 feat(coderd): filter expired API tokens server-side (#22263)
## Summary

Moves expired token filtering from client-side to server-side by adding
an `include_expired` parameter to the `GetAPIKeysByLoginType` and
`GetAPIKeysByUserID` database queries. This is more efficient for large
deployments with many expired/short-lived tokens.

## Changes

- Add `include_expired` parameter to SQL queries using `OR`
short-circuit
- Add `include_expired` query parameter to `GET
/users/{user}/keys/tokens`
- Add `IncludeExpired` field to `codersdk.TokensFilter`
- Remove client-side filtering from CLI `tokens list` command
- Add `TestTokensFilterExpired` test

Fixes coder/internal#1357
2026-02-24 15:27:03 +00:00
Cian JohnstonandClaude Opus 4.5 4a3304fc38 feat(cli)!: expire tokens by default (#21783)
## Summary

> NOTE: Calling this out as a breaking change in case existing consumers
of the CLI depend on being able to see expired tokens OR being able to
delete tokens immediately.

Updates the `coder tokens rm` command to immediately expire a token by
ID, preserving the token record for audit trail purposes. Tokens can
still be deleted by passing `--delete`.

## Problem

During an incident on dev.coder.com, operators needed to urgently expire
an API key that was stuck in a hot loop. The only way to do this was via
direct database access:

```sql
UPDATE api_keys SET expires_at = NOW() WHERE id = '...';
```

This is not ideal for operators who may not have direct DB access or
want to avoid manual SQL.

## Solution

This PR adds:

- **API endpoint**: `PUT /api/v2/users/{user}/keys/{keyid}/expire` -
Sets the token's `expires_at` to now
- **SDK method**: `ExpireAPIKey(ctx, userID, keyID)` 
- **Updates CLI**: `coder tokens rm <name|id|token>` now _expires_ by
default. You can still delete by passing the `--delete` flag. The `coder
tokens list` command now also hides expired tokens by default. You can
`--include-expired` if needed to include them.
- **Audit logging**: The expire action is logged with old and new key
states

## Test plan

- Tests cover: owner expiring own token, admin expiring other user's
token, non-admin cannot expire other's token, 404 for non-existent token

Closes #21782

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-17 13:16:46 +00:00
Zach 091d31224d fix: replace moby/moby namesgenerator with internal implementation (#21377)
Replace the external moby/moby/pkg/namesgenerator dependency with an
internal implementation using gofakeit/v7. The moby package has ~25k
unique name combinations, and with its retry parameter only adds a
random digit 0-9, giving ~250k possibilities. In parallel tests, this
has led to collisions (flakes).

The new internal API at coderd/util/namesgenerator eliminates the
external dependnecy and offers functions with explicit uniqueness
guarantees. This PR also consolidates fragmented name generation in a
few places to use the new package.

| Old (moby/moby)                     | New                    |
|-------------------------------------|------------------------|
| namesgenerator.GetRandomName(0)     | NameWith("_")          |
| namesgenerator.GetRandomName(>0)    | NameDigitWith("_")     |
| testutil.GetRandomName(t)           | UniqueName()           |
| testutil.GetRandomNameHyphenated(t) | UniqueNameWith("-")    |

namesgenerator package API:
- NameWith(delim): random name, not unique
- NameDigitWith(delim): random name with 1-9 suffix, not unique
- UniqueName(): guaranteed unique via atomic counter
- UniqueNameWith(delim): unique with custom delimiter

Names continue to be docker style `[adjective][delim][surname]`. Unique
names are truncated to 32 characters (preserving the numeric suffix) to
fit common name length limits in Coder.

Related test flakes:
https://github.com/coder/internal/issues/1212
https://github.com/coder/internal/issues/118
https://github.com/coder/internal/issues/1068
2026-01-09 15:40:26 -07:00
Spike Curtis bddb808b25 chore: arrange imports in a standard way (#21452)
Fixes all our Go file imports to match the preferred spec that we've _mostly_ been using. For example:

```
import (
	"context"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/xerrors"
	"gopkg.in/natefinch/lumberjack.v2"

	"cdr.dev/slog/v3"
	"github.com/coder/coder/v2/codersdk/agentsdk"
	"github.com/coder/serpent"
)
```

3 groups: standard library, 3rd partly libs, Coder libs.

This PR makes the change across the codebase. The PR in the stack above modifies our formatting to maintain this state of affairs, and is a separate PR so it's possible to review that one in detail.
2026-01-08 15:24:11 +04:00
Spike Curtis 49b34a716a fix: fix slog to always use array of Fields (#21426)
Upgrades to slog v3 which includes a small, but backward incompatible API change to the acceptible call arguments when logging. This change allows us to verify via compile time type checking that arguments are correct and won't cause a panic, as was possible in slog v1, which this replaces (v2 was tagged but never used in coder/coder).

It also updates dependencies that also use slog and were updated.

I've left the `aibridge` dependency as a commit SHA, under the assumption that the team there (cc @pawbana @dannykopping ) will tag and update the dependency soon and on their own schedule.

Other dependencies, I pushed new tags.
2026-01-08 10:29:41 +04:00
Thomas Kosiewski ed90ecf00e feat: add allow_list to resource-scoped API tokens (#19964)
# Add API key allow_list for resource-scoped tokens

This PR adds support for API key allow lists, enabling tokens to be scoped to specific resources. The implementation:

1. Adds a new `allow_list` field to the `CreateTokenRequest` struct, allowing clients to specify resource-specific scopes when creating API tokens
2. Implements `APIAllowListTarget` type to represent resource targets in the format `<type>:<id>` with support for wildcards
3. Adds validation and normalization logic for allow lists to handle wildcards and deduplication
4. Integrates with RBAC by creating an `APIKeyEffectiveScope` that merges API key scopes with allow list restrictions
5. Updates API documentation and TypeScript types to reflect the new functionality

This feature enables creating tokens that are limited to specific resources (like workspaces or templates) by ID, making it possible to create more granular API tokens with limited access.
2025-10-09 14:53:08 +02:00
Thomas Kosiewski d0db9ec88f feat: add multi-scope support to API keys (#19917)
# Canonicalize API Key Scopes

This PR introduces canonical API key scopes with a `coder:` namespace prefix to avoid collisions with low-level resource:action names. It:

1. Renames special API key scopes in the database:
   - `all` → `coder:all`
   - `application_connect` → `coder:application_connect`

2. Adds support for a new `scopes` field in the API key creation request, allowing multiple scopes to be specified while maintaining backward compatibility with the singular `scope` field.

3. Updates the API documentation to reflect these changes, including the new endpoint for listing public API key scopes.

4. Ensures backward compatibility by mapping between legacy and canonical scope names in relevant code paths.
2025-09-26 11:56:34 +02:00
Thomas Kosiewski 4bda39585d feat: add external API key scopes (#19916)
# Add support for low-level API key scopes

This PR adds support for fine-grained API key scopes based on RBAC resource:action pairs. It includes:

1. A new endpoint `/api/v2/auth/scopes` to list all public low-level API key scopes
2. Generated constants in the SDK for all public scopes
3. Tests to verify scope validation during token creation
4. Updated API documentation to reflect the expanded scope options

The implementation allows users to create API keys with specific permissions like `workspace:read` or `template:use` instead of only the legacy `all` or `application_connect` scopes.



Fixes #19847
2025-09-26 11:43:32 +02:00
Cian Johnston bd6e91eeab fix(coderd): add audit log on creating a new session key (#19672)
Fixes https://github.com/coder/coder/issues/19671
(re-?)Adds an audit log entry when an API key is created via `coder
login`.

NOTE: This does _not_ backfill audit logs.

<img width="1354" height="207" alt="Screenshot 2025-09-02 at 14 16 24"
src="https://github.com/user-attachments/assets/921e85c1-eced-4a19-9d37-8f84f4af1e73"
/>
2025-09-02 14:21:56 +01:00
Cian Johnston 06cbb2890f fix: expire token for prebuilds user when regenerating session token (#19667)
* provisionerdserver: Expires prebuild user token for workspace, if it
exists, when regenerating session token.
* dbauthz: disallow prebuilds user from creating api keys
* dbpurge: added functionality to expire stale api keys owned by the
prebuilds user
2025-09-02 09:38:43 +01:00
Rowan Smith 93279dff24 chore: change format of key from uuid to string to fix swagger issue (#19380)
ref: https://codercom.slack.com/archives/C014JH42DBJ/p1755192759211289

this change allows api keys to be deleted via swagger
2025-08-18 12:37:51 +10:00
Thomas Kosiewski f569d9c33d feat: add separate max token lifetime for administrators (#18267)
# Add separate token lifetime limits for administrators

This PR introduces a new configuration option `--max-admin-token-lifetime` that allows administrators to create API tokens with longer lifetimes than regular users. By default, administrators can create tokens with a lifetime of up to 7 days (168 hours), while the existing `--max-token-lifetime` setting continues to apply to regular users.

The implementation:
- Adds a new `MaximumAdminTokenDuration` field to the session configuration
- Modifies the token validation logic to check the user's role and apply the appropriate lifetime limit
- Updates the token configuration endpoint to return the correct maximum lifetime based on the user's role
- Adds tests to verify that administrators can create tokens with longer and shorter lifetimes
- Updates documentation and help text to reflect the new option

This change allows organizations to grant administrators extended token lifetimes while maintaining tighter security controls for regular users.

Fixes #17395
2025-06-06 17:36:30 +02:00
Steven Masley 52d555880c chore: add custom samesite options to auth cookies (#16885)
Allows controlling `samesite` cookie settings from the deployment config
2025-04-08 14:15:14 -05:00
Jon AyersandClaude 17ddee05e5 chore: update golang to 1.24.1 (#17035)
- Update go.mod to use Go 1.24.1
- Update GitHub Actions setup-go action to use Go 1.24.1
- Fix linting issues with golangci-lint by:
  - Updating to golangci-lint v1.57.1 (more compatible with Go 1.24.1)

🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <claude@anthropic.com>
2025-03-26 01:56:39 -05:00
Ethan fccf6f1e0e feat!: add --default-token-lifetime (#14631) 2024-09-18 21:23:42 +10:00
Kayla Washburn-Love de2585b0b6 chore: use rw.WriteHeader to write responses without bodies (#13870) 2024-07-11 13:38:33 -06:00
Steven Masley cb6b5e8fbd chore: push rbac actions to policy package (#13274)
Just moved `rbac.Action` -> `policy.Action`. This is for the stacked PR to not have circular dependencies when doing autogen. Without this, the autogen can produce broken golang code, which prevents the autogen from compiling.

So just avoiding circular dependencies. Doing this in it's own PR to reduce LoC diffs in the primary PR, since this has 0 functional changes.
2024-05-15 09:46:35 -05:00
Steven Masley 838e8df5be chore: merge apikey/token session config values (#12817)
* chore: merge apikey/token session config values

There is a confusing difference between an apikey and a token. This
difference leaks into our configs. This change does not resolve the
difference. It only groups the config values to try and manage any
bloat that occurs from adding more similar config values
2024-04-10 10:34:49 -05:00
AsherandSteven Masley 16c6cefde8 chore: pass lifetime directly into api key generate (#11715)
Rather than passing all the deployment values.  This is to make it
easier to generate API keys as part of the oauth flow.

I also added and fixed a test for when the lifetime is set and the
default and expiration are unset.

Co-authored-by: Steven Masley <stevenmasley@gmail.com>
2024-01-22 11:42:55 -09:00
Cian Johnston 2ac532982d feat(coderd/database): generate foreign key constraints and add database.IsForeignKeyViolation (#9657)
* feat(coderd/database): generate foreign key constraints, add database.IsForeignKeyViolation

* address PR comments
2023-09-13 13:28:46 +01:00
Mathias Fredriksson 19d7da3d24 refactor(coderd/database): split Time and Now into dbtime package (#9482)
Ref: #9380
2023-09-01 16:50:12 +00:00
Kyle Carberry 22e781eced chore: add /v2 to import module path (#9072)
* chore: add /v2 to import module path

go mod requires semantic versioning with versions greater than 1.x

This was a mechanical update by running:
```
go install github.com/marwan-at-work/mod/cmd/mod@latest
mod upgrade
```

Migrate generated files to import /v2

* Fix gen
2023-08-18 18:55:43 +00:00
Jon Ayers ec5ef51b49 feat: add session token injection to provisioner (#7461) 2023-05-17 23:29:22 -05:00
Steven Masley 38e5b9679b chore: Rbac errors should be returned, and not hidden behind 404 (#7122)
* chore: Rbac errors should be returned, and not hidden behind 404

SqlErrNoRows was hiding actual errors
* Replace sql.ErrNoRow checks
* Remove sql err no rows check from dbauthz test
* Fix to use dbauthz system user
2023-04-13 13:06:16 -05:00
Steven Masley 90da09bc2c chore: Make deployment admin page show better durations (#6856)
* chore: Make deployment admin page show better durations

Also fix group mappings
2023-03-29 16:26:20 -05:00
Steven Masley 2321160c62 feat: Dbauthz is now default, remove out of experimental (#6650)
* feat: dbauthz always on, out of experimental
* Add ability to do rbac checks in unit tests
* Remove AuthorizeAllEndpoints
* Remove duplicate rbac checks
2023-03-21 09:10:22 -05:00
Kira Pilot 090e37fc46 feat(audit): auditing token addition and removal (#6649)
* auditing tokens

* adding diffs for token auditing

* added test

* generating docs

* auditing owner field
2023-03-17 10:41:44 -07:00
Kira Pilot 811a69f371 feat(site): add ability to create tokens from account tokens page (#6608)
* add token actions

* added basic token form

* removed token switch

* refined date field

* limiting lifetime days to maxTokenLifetime

* broke apart files

* added loader and error

* fixed form layout

* added some unit tests

* fixed be tests

* no authorize check
2023-03-16 08:25:08 -07:00
Ammar Bandukwala 3b73321a6c feat: refactor deployment config (#6347) 2023-03-07 15:10:01 -06:00
71d1e63af0 feat: add ability to name tokens (#6365)
* add tokens switch

* reorged TokensPage

* using Trans component for description

* using Trans component on DeleteDialog

* add owner col

* simplify hook return

* lint

* type for response

* added flag for name

* fixed auth

* lint, prettier, tests

* added unique index for login type token

* remove tokens by name

* better check for unique constraint

* docs

* test: Fix dbfake to insert token name

* fix doc tests

* Update cli/tokens.go

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

* Update coderd/database/migrations/000102_add_apikey_name.down.sql

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

* add more specificity to IsUniqueViolation check

* fix tests

* Fix AutorizeAllEndpoints

* rename migration

---------

Co-authored-by: Steven Masley <stevenmasley@coder.com>
Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
2023-03-02 09:39:38 -08:00
Kira Pilot 6304bfb5c0 feat: add 'Show all tokens' toggle for owners (#6325)
* add tokens switch

* reorged TokensPage

* using Trans component for description

* using Trans component on DeleteDialog

* add owner col

* simplify hook return

* lint

* type for response

* PR feedback

* fix lint
2023-03-01 08:35:55 -08:00
Kira Pilot a32169ccb5 feat: add flag to see all tokens if owner (#6227)
* added query for tokens by user id

* updated query args

* adding owner col

* fix request params

* update-golden-files

* added owners col to ls table output

* added ttoken translations

* prettier

* format table according to arg

* using slice.Contains

* refactored token state

* cleanup
2023-02-23 07:00:27 -08:00
Ammar Bandukwala f05609b4da chore: format Go more aggressively 2023-02-18 18:32:09 -06:00
Kira PilotandSteven Masley 46fe59f5e7 feat: audit login (#5925)
* added migration for api key resource

* sort of working

* auditing login

* passing  the correct user id

* added and fixed tests

* gen documentation

* formatting and lint

* lint

* audit Github oauth and write tests

* audit oauth and write  tests

* added defer fn for login error auditing

* fixed test

* feat: audit logout (#5998)

* Update coderd/userauth.go

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

* fix test

* bypassing diff generation if login/logout

* lint

---------

Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
2023-02-06 15:12:50 -05:00
Dean Sheather cf9abe3a6c feat: add session expiry control flags (#5976)
Adds --session-duration which lets admins customize the default session
expiration for browser sessions.

Adds --disable-session-expiry-refresh which allows admins to prevent
session expiry from being automatically bumped upon the API key being
used.
2023-02-03 17:38:36 +00:00
Kyle Carberry 7ad87505c8 chore: move agent functions from codersdk into agentsdk (#5903)
* chore: rename `AgentConn` to `WorkspaceAgentConn`

The codersdk was becoming bloated with consts for the workspace
agent that made no sense to a reader. `Tailnet*` is an example
of these consts.

* chore: remove `Get` prefix from *Client functions

* chore: remove `BypassRatelimits` option in `codersdk.Client`

It feels wrong to have this as a direct option because it's so infrequently
needed by API callers. It's better to directly modify headers in the two
places that we actually use it.

* Merge `appearance.go` and `buildinfo.go` into `deployment.go`

* Merge `experiments.go` and `features.go` into `deployment.go`

* Fix `make gen` referencing old type names

* Merge `error.go` into `client.go`

`codersdk.Response` lived in `error.go`, which is wrong.

* chore: refactor workspace agent functions into agentsdk

It was odd conflating the codersdk that clients should use
with functions that only the agent should use. This separates
them into two SDKs that are closely coupled, but separate.

* Merge `insights.go` into `deployment.go`

* Merge `organizationmember.go` into `organizations.go`

* Merge `quota.go` into `workspaces.go`

* Rename `sse.go` to `serversentevents.go`

* Rename `codersdk.WorkspaceAppHostResponse` to `codersdk.AppHostResponse`

* Format `.vscode/settings.json`

* Fix outdated naming in `api.ts`

* Fix app host response

* Fix unsupported type

* Fix imported type
2023-01-29 15:47:24 -06:00
Steven MasleyandCian Johnston 08cce81ac8 feat: Implement allow_list for scopes for resource specific permissions (#5769)
* feat: Implement allow_list for scopes for resource specific permissions

Feature that adds an allow_list for scopes to specify particular resources.
This enables workspace agent tokens to use the same RBAC system as users.

- Add ID to compileSQL matchers
* Plumb through WithID on rbac objects
* Rename Scope -> ScopeName
* Update input.json with scope allow_list

Co-authored-by: Cian Johnston <cian@coder.com>
2023-01-19 13:41:36 -06:00
Garrett Delfosse 0cf713869b feat: Manage tokens in dashboard (#5444) 2023-01-13 17:20:03 +00:00
Marcin Tojek deebfcbd53 feat: Validate swagger definitions (#5694)
* docs: audit, deploymentconfig, files, parameters

* Swagger comments in workspacebuilds.go

* structs in workspacebuilds.go

* workspaceagents: instance identity

* workspaceagents.go in progress

* workspaceagents.go in progress

* Agents

* workspacebuilds.go

* /workspaces

* templates.go, templateversions.go

* templateversion.go in progress

* cancel

* templateversions

* wip

* Merge

* x-apidocgen

* NullTime hack not needed anymore

* Fix: x-apidocgen

* Members

* Fixes

* Fix

* WIP

* WIP

* Users

* Logout

* User profile

* Status suspend activate

* User roles

* User tokens

* Keys

* SSH key

* All

* Typo

* Fix

* Entitlements

* Groups

* SCIM

* Fix

* Fix

* Clean templates

* Sort API pages

* Fix: HashedSecret

* WIP

* WIP

* WIP

* Fix: cover workspaceagents

* Assert: consistent ID and summary

* Assert: success or failure defined

* Fix: parallel

* Refactor

* Support enterprise

* Go comment goes to top

* Security

* assertPathParametersDefined

* assertUniqueRoutes

* assertRequestBody

* More fixes

* Fix: exceptions

* Fix field format

* Address PR comments

* Refactor
2023-01-13 12:27:21 +01:00
Marcin Tojek 8e9cbdd71b docs: API users (#5620)
* docs: audit, deploymentconfig, files, parameters

* Swagger comments in workspacebuilds.go

* structs in workspacebuilds.go

* workspaceagents: instance identity

* workspaceagents.go in progress

* workspaceagents.go in progress

* Agents

* workspacebuilds.go

* /workspaces

* templates.go, templateversions.go

* templateversion.go in progress

* cancel

* templateversions

* wip

* Merge

* x-apidocgen

* NullTime hack not needed anymore

* Fix: x-apidocgen

* Members

* Fixes

* Fix

* WIP

* WIP

* Users

* Logout

* User profile

* Status suspend activate

* User roles

* User tokens

* Keys

* SSH key

* All

* Typo

* Fix

* Fix

* Fix: LoginWithPasswordRequest
2023-01-11 14:08:04 +01:00
Dean SheatherandBruno Quaresma 50dfc2082b feat: endpoint to logout app subdomain URLs (#5428)
Co-authored-by: Bruno Quaresma <bruno@coder.com>
2022-12-20 18:45:13 +00:00
Garrett Delfosse 40a5c0476f feat: add flag for token lifetime (#5385) 2022-12-12 15:39:31 -05:00
Kyle Carberry f75a54cd1e feat: Support x-forwarded-for headers for IPs (#4684)
* feat: Support x-forwarded-for headers for IPs

Fixes #4430.

* Fix realip accepting headers

* Fix unused headers
2022-10-23 13:21:49 -05:00
Dean Sheather d898737d6d feat: app sharing (now open source!) (#4378) 2022-10-15 02:46:38 +10:00
Garrett Delfosse 32bb1e7ce9 fix: add back missing postAPIKey route (#4406) 2022-10-06 17:56:43 -04:00