## 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>
327 lines
10 KiB
Go
327 lines
10 KiB
Go
// Command scopesdocgen generates the API key scopes reference at
|
|
// docs/reference/api-key-scopes.md from the RBAC scope catalog. It lists the
|
|
// scopes a token may request: the built-in scopes, the composite coder:*
|
|
// scopes with the permissions each one expands to, and the low-level
|
|
// resource:action scopes. Because the source is rbac.ExternalScopeNames and
|
|
// the policy definitions behind it, the page stays in sync as scopes change.
|
|
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"maps"
|
|
"path/filepath"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/rbac"
|
|
"github.com/coder/coder/v2/coderd/rbac/policy"
|
|
stringutil "github.com/coder/coder/v2/coderd/util/strings"
|
|
"github.com/coder/coder/v2/scripts/atomicwrite"
|
|
"github.com/coder/coder/v2/scripts/docgenenv"
|
|
"github.com/coder/flog"
|
|
)
|
|
|
|
// routeTitles is the sidebar breadcrumb to this page's route. The page
|
|
// mirrors that route's metadata into its front matter, so the sidebar sources
|
|
// stay the single source of the title and description.
|
|
var routeTitles = []string{"Reference", "API key scopes"}
|
|
|
|
var exampleScopes = []rbac.ScopeName{
|
|
"coder:workspaces.access",
|
|
"template:read",
|
|
}
|
|
|
|
const intro = `A scope limits what an API key can do.
|
|
A scoped key never exceeds the permissions of the user who created it: Coder checks the scope and the user's roles on every request, so a scope narrows access and never widens it.
|
|
|
|
Pass ` + "`--scope`" + ` once per scope when you create a token:
|
|
|
|
%s
|
|
|
|
A token created without an explicit scope uses ` + "`coder:all`" + `, which grants the full permissions of its owner.
|
|
To create and revoke tokens, refer to [Sessions & API Tokens](../admin/users/sessions-tokens.md).
|
|
|
|
This page lists every canonical scope a token can request and the deprecated names Coder accepts for backward compatibility.
|
|
Coder rejects any scope name not listed on this page with a ` + "`400`" + ` response.
|
|
|
|
`
|
|
|
|
const builtinSection = `## Built-in scopes
|
|
|
|
Built-in scopes cover the two broadest cases: the full permissions of the owner, and connections to workspace applications.
|
|
|
|
`
|
|
|
|
const compositeSection = `## Composite scopes
|
|
|
|
A composite scope groups the permissions that one task needs, so you can scope a token to that task without listing each permission.
|
|
Each scope below grants the permissions in its table.
|
|
|
|
`
|
|
|
|
const lowLevelSection = `## Low-level scopes
|
|
|
|
A low-level scope grants one action on one resource, written as ` + "`resource:action`" + `.
|
|
Combine low-level scopes when no composite scope matches the task.
|
|
|
|
The ` + "`resource:*`" + ` form grants every action on that resource, including actions not listed on this page.
|
|
|
|
`
|
|
|
|
const deprecatedSection = `## Deprecated scope names
|
|
|
|
Coder still accepts the following names and stores each one as its canonical equivalent.
|
|
Use the canonical name.
|
|
|
|
`
|
|
|
|
func main() {
|
|
sourcesDir := flag.String("manifest-sources", filepath.Join("docs", docgenenv.ManifestSourcesDir), "directory of the docs sidebar sources that supply the page metadata")
|
|
out := flag.String("out", "docs/reference/api-key-scopes.md", "path to write the generated reference page")
|
|
flag.Parse()
|
|
|
|
manifest, err := docgenenv.LoadManifestSources(*sourcesDir)
|
|
if err != nil {
|
|
flog.Fatalf("%v", err)
|
|
}
|
|
route := manifest.FindRoute(routeTitles...)
|
|
if route == nil {
|
|
flog.Fatalf("sidebar sources %q have no route %q", *sourcesDir, strings.Join(routeTitles, " > "))
|
|
}
|
|
|
|
content, err := render(*route)
|
|
if err != nil {
|
|
flog.Fatalf("render scopes reference: %v", err)
|
|
}
|
|
if err := atomicwrite.File(*out, []byte(content)); err != nil {
|
|
flog.Fatalf("write %s: %v", *out, err)
|
|
}
|
|
flog.Successf("wrote %s", *out)
|
|
}
|
|
|
|
func render(route docgenenv.Route) (string, error) {
|
|
builtin, composite, lowLevel := partitionScopes(rbac.ExternalScopeNames())
|
|
|
|
var b strings.Builder
|
|
// The front matter title renders as the page heading, so the body starts
|
|
// at the intro and its sections begin at level two.
|
|
_, _ = b.WriteString(docgenenv.GeneratedHeader(route))
|
|
_, _ = fmt.Fprintf(&b, intro, exampleCommand())
|
|
|
|
_, _ = b.WriteString(builtinSection)
|
|
if err := renderBuiltin(&b, builtin); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
_, _ = b.WriteString(compositeSection)
|
|
if err := renderComposite(&b, composite); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
_, _ = b.WriteString(lowLevelSection)
|
|
if err := renderLowLevel(&b, lowLevel); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
_, _ = b.WriteString(deprecatedSection)
|
|
if err := renderDeprecatedAliases(&b, rbac.ScopeAliases()); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return strings.TrimRight(b.String(), "\n") + "\n", nil
|
|
}
|
|
|
|
// partitionScopes splits the public scope names into the built-in scopes,
|
|
// composite scopes, and low-level resource:action scopes.
|
|
func partitionScopes(names []string) (builtin, composite, lowLevel []string) {
|
|
for _, name := range names {
|
|
scope := rbac.ScopeName(name)
|
|
switch scope {
|
|
case rbac.ScopeAll, rbac.ScopeApplicationConnect:
|
|
builtin = append(builtin, name)
|
|
default:
|
|
if _, ok := rbac.CompositeSitePermissions(scope); ok {
|
|
composite = append(composite, name)
|
|
} else {
|
|
lowLevel = append(lowLevel, name)
|
|
}
|
|
}
|
|
}
|
|
slices.Sort(builtin)
|
|
slices.Sort(composite)
|
|
slices.Sort(lowLevel)
|
|
return builtin, composite, lowLevel
|
|
}
|
|
|
|
func renderBuiltin(b *strings.Builder, names []string) error {
|
|
_, _ = b.WriteString("| Scope | Grants |\n|-------|--------|\n")
|
|
for _, name := range names {
|
|
scope, err := rbac.ExpandScope(rbac.ScopeName(name))
|
|
if err != nil {
|
|
return xerrors.Errorf("expand builtin scope %q: %w", name, err)
|
|
}
|
|
description := sentence(scope.DisplayName)
|
|
if err := validateTableCells(name, description); err != nil {
|
|
return xerrors.Errorf("render builtin scope %q: %w", name, err)
|
|
}
|
|
_, _ = fmt.Fprintf(b, "| `%s` | %s |\n", name, description)
|
|
}
|
|
_, _ = b.WriteString("\n")
|
|
return nil
|
|
}
|
|
|
|
func renderComposite(b *strings.Builder, names []string) error {
|
|
for _, name := range names {
|
|
perms, ok := rbac.CompositeSitePermissions(rbac.ScopeName(name))
|
|
if !ok {
|
|
return xerrors.Errorf("composite scope %q has no permissions", name)
|
|
}
|
|
|
|
byResource := map[string][]string{}
|
|
for _, perm := range perms {
|
|
byResource[perm.ResourceType] = append(byResource[perm.ResourceType], string(perm.Action))
|
|
}
|
|
|
|
_, _ = fmt.Fprintf(b, "### `%s`\n\n", name)
|
|
_, _ = b.WriteString("| Resource | Actions |\n|----------|---------|\n")
|
|
for _, resource := range slices.Sorted(maps.Keys(byResource)) {
|
|
actions := byResource[resource]
|
|
slices.Sort(actions)
|
|
actionList := codeList(actions)
|
|
if err := validateTableCells(resource, actionList); err != nil {
|
|
return xerrors.Errorf("render composite scope %q: %w", name, err)
|
|
}
|
|
_, _ = fmt.Fprintf(b, "| `%s` | %s |\n", resource, actionList)
|
|
}
|
|
_, _ = b.WriteString("\n")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func renderLowLevel(b *strings.Builder, names []string) error {
|
|
byResource := map[string][]string{}
|
|
for _, name := range names {
|
|
resource, _, ok := rbac.ParseResourceAction(name)
|
|
if !ok {
|
|
return xerrors.Errorf("low-level scope %q is not a resource:action pair", name)
|
|
}
|
|
byResource[resource] = append(byResource[resource], name)
|
|
}
|
|
|
|
for _, resource := range slices.Sorted(maps.Keys(byResource)) {
|
|
_, _ = fmt.Fprintf(b, "### `%s`\n\n", resource)
|
|
_, _ = b.WriteString("| Scope | Description |\n|-------|-------------|\n")
|
|
|
|
scopes := byResource[resource]
|
|
slices.Sort(scopes)
|
|
for _, scope := range scopes {
|
|
_, action, _ := rbac.ParseResourceAction(scope)
|
|
description, err := actionDescription(resource, action)
|
|
if err != nil {
|
|
return xerrors.Errorf("describe low-level scope %q: %w", scope, err)
|
|
}
|
|
if err := validateTableCells(scope, description); err != nil {
|
|
return xerrors.Errorf("render low-level scope %q: %w", scope, err)
|
|
}
|
|
_, _ = fmt.Fprintf(b, "| `%s` | %s |\n", scope, description)
|
|
}
|
|
_, _ = b.WriteString("\n")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// actionDescription returns the description the policy declares for an action
|
|
// on a resource. The wildcard action has no policy entry of its own, so it is
|
|
// described in terms of the resource it covers.
|
|
func actionDescription(resource, action string) (string, error) {
|
|
if action == policy.WildcardSymbol {
|
|
return fmt.Sprintf("Every action on `%s`, including actions not listed on this page.", resource), nil
|
|
}
|
|
def, ok := policy.RBACPermissions[resource]
|
|
if !ok {
|
|
return "", xerrors.Errorf("resource %q has no policy definition", resource)
|
|
}
|
|
desc, ok := def.Actions[policy.Action(action)]
|
|
if !ok {
|
|
return "", xerrors.Errorf("resource %q has no description for action %q", resource, action)
|
|
}
|
|
return sentence(string(desc)), nil
|
|
}
|
|
|
|
// acronyms restores the capitalization of terms that the policy descriptions
|
|
// spell in lower case.
|
|
var acronyms = map[string]string{
|
|
"api": "API",
|
|
"cli": "CLI",
|
|
"idp": "IdP",
|
|
"oidc": "OIDC",
|
|
"ssh": "SSH",
|
|
"ui": "UI",
|
|
"url": "URL",
|
|
}
|
|
|
|
var acronymPattern = regexp.MustCompile(`(?i)\b(` + strings.Join(slices.Sorted(maps.Keys(acronyms)), "|") + `)\b`)
|
|
|
|
// sentence capitalizes the first word of a policy description and gives it
|
|
// terminal punctuation, so table cells read as sentences.
|
|
func sentence(s string) string {
|
|
s = strings.TrimSpace(s)
|
|
if s == "" {
|
|
return s
|
|
}
|
|
|
|
s = acronymPattern.ReplaceAllStringFunc(s, func(word string) string {
|
|
return acronyms[strings.ToLower(word)]
|
|
})
|
|
|
|
first, rest, _ := strings.Cut(s, " ")
|
|
first = stringutil.Capitalize(first)
|
|
s = strings.TrimSpace(first + " " + rest)
|
|
|
|
if !strings.HasSuffix(s, ".") {
|
|
s += "."
|
|
}
|
|
return s
|
|
}
|
|
|
|
// codeList renders values as a comma-separated list of inline code spans.
|
|
func codeList(values []string) string {
|
|
quoted := make([]string, len(values))
|
|
for i, v := range values {
|
|
quoted[i] = "`" + v + "`"
|
|
}
|
|
return strings.Join(quoted, ", ")
|
|
}
|
|
|
|
func exampleCommand() string {
|
|
args := make([]string, len(exampleScopes))
|
|
for i, scope := range exampleScopes {
|
|
args[i] = "--scope " + string(scope)
|
|
}
|
|
return "```shell\ncoder tokens create " + strings.Join(args, " ") + "\n```"
|
|
}
|
|
|
|
func renderDeprecatedAliases(b *strings.Builder, aliases map[rbac.ScopeName]rbac.ScopeName) error {
|
|
_, _ = b.WriteString("| Deprecated name | Canonical name |\n|-----------------|----------------|\n")
|
|
for _, alias := range slices.Sorted(maps.Keys(aliases)) {
|
|
if err := validateTableCells(string(alias), string(aliases[alias])); err != nil {
|
|
return xerrors.Errorf("render deprecated scope %q: %w", alias, err)
|
|
}
|
|
_, _ = fmt.Fprintf(b, "| `%s` | `%s` |\n", alias, aliases[alias])
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateTableCells(values ...string) error {
|
|
for _, value := range values {
|
|
if strings.Contains(value, "|") {
|
|
return xerrors.Errorf("table cell contains a pipe: %q", value)
|
|
}
|
|
}
|
|
return nil
|
|
}
|