Files
coder/coderd/rbac/scopes_test.go
T
9368917813 feat: report the negotiated scope to the user and the client (#28179)
**TL;DR**

Last of the stack, split out of #28045. #28178 decided what the scope
is; this PR is everything that reports it, to the user on the consent
page and to the client on rejection.

| PR | What it does |
|---|---|
| #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated
scope has somewhere to live. Every code is still stamped unrestricted. |
| #28167 | `ScopesCover` compares an allowlist against a request by
permission coverage rather than by name, and fails closed on any shape
it does not model. Added with no production callers. |
| #28178 | The authorize endpoint checks the request against the scope
catalog, grants it only if the app's filtered allowlist covers it, and
persists the result on the code. |
| **#28179 (this)** | The consent page lists the negotiated permissions,
and `invalid_scope` reaches the client's own callback per RFC 6749
§4.1.2.1 instead of a Coder error page. Retires the interim plumbing
#28178 left behind. |

- #28178 has merged, so this diff is against main and reviews on its
own. It is still worth reading first: nothing here decides a scope, it
only reports the one `negotiateScope` already returns.
- **The consent page HTML is not final.** Layout and wording in
`site/static/oauth2allow.html` are still being refined. It is in this
branch so the scope-enforcement flow can be exercised end to end in a
browser, not because the markup is settled. The reviewable part of Half
A is the Go side that decides what the page states; the presentation
will change.
- An unrestricted grant still reads as full access, not as a scope name.
Nothing about what a token can do changes in this PR either.

**Where in the flow**

- Authorize endpoint only, both verbs. GET decides what the consent page
states; both verbs send `invalid_scope` to the callback. The token
exchange, refresh, and revocation are untouched.
- `negotiateScope` is unchanged from #28178, so which requests succeed
is unchanged. This PR reads its result twice: once to decide what the
page lists, once to decide where the rejection goes.
- The endpoint sits behind `apiKeyMiddlewareRedirect`, so the user is
authenticated before any of this runs. That matters for the redirect,
not just for the page.
- Consent page rendering moves a decision into Go rather than the
template: `RenderOAuthAllowData` carries `Scopes` and `Unrestricted`
separately, and the template branches on `Unrestricted` alone.

**What it satisfies**

- RFC 6749 §4.1.2.1 — on a failure that is not a bad redirection URI,
the server "informs the client by adding the following parameters to the
query component of the redirection URI". `invalid_scope` now goes there.
#28178's interim delivery, a static error page on GET and an error body
on POST, is what this replaces.
- RFC 6749 §4.1.2.1 — `state` is "REQUIRED if a `state` parameter was
present in the client authorization request", so it is echoed only when
the client sent one, never synthesized. Pinned by
`OmittedStateNotEchoed`.
- RFC 6749 §3.1.2.4 and §4.1.2.1 — on a "missing, invalid, or
mismatching redirection URI" the server "MUST NOT automatically redirect
the user-agent to the invalid redirection URI". This is the whole
ordering argument, and the file's other error paths keep their existing
delivery precisely because several of them are where that validation
fails.
- RFC 9700 §2.1 — pre-registered redirection URIs "MUST utilize exact
string matching". `extractAuthorizeParams` already did this before the
stack; Half B depends on it rather than adding it.
- RFC 9700 §4.11.2 — names this exact hazard: an attacker who registers
a client can "intentionally send an erroneous authorization request,
e.g., by using an invalid scope value, thus instructing the
authorization server to redirect the user agent to its phishing site".
The destination is still only ever a URI that client registered, so this
is a phishing surface that costs an attacker a registration, not an open
redirect. The precaution the section requires, authenticating the user
first, is what `apiKeyMiddlewareRedirect` provides.
- RFC 9700 §4.12 — a server redirecting a request that may carry
credentials "MUST NOT use the HTTP 307 status code". 302, matching the
success redirect beside it.
- RFC 6749 §4.1.2.1 — `server_error` exists "because a 500 Internal
Server Error HTTP status code cannot be returned to the client via an
HTTP redirect". An unusable registered callback is the one case with
nowhere to redirect, so it answers 500 on both verbs and logs the app
and URL for an operator to correlate by.
- Not yet: §1.4.1 still wants `scope` in the token response when the
grant differs from the request. Tokens are untouched here, as in #28178,
so that lands with enforcement.

---

Split out of #28045
([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Last of three.
#28178 has merged, so this reviews against main.

#28178 decided what the scope is. This PR is everything that tells
someone about it.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
2026-09-01 09:16:08 -07:00

262 lines
8.7 KiB
Go

package rbac_test
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/policy"
)
func TestExpandScope(t *testing.T) {
t.Parallel()
t.Run("low_level_pairs", func(t *testing.T) {
t.Parallel()
cases := []struct {
name string
resource string
action policy.Action
}{
{name: "workspace:start", resource: rbac.ResourceWorkspace.Type, action: policy.ActionWorkspaceStart},
{name: "workspace:ssh", resource: rbac.ResourceWorkspace.Type, action: policy.ActionSSH},
{name: "template:use", resource: rbac.ResourceTemplate.Type, action: policy.ActionUse},
{name: "api_key:read", resource: rbac.ResourceApiKey.Type, action: policy.ActionRead},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
s, err := rbac.ScopeName(tc.name).Expand()
require.NoError(t, err)
// site-only single permission
require.Len(t, s.Site, 1)
require.Equal(t, tc.resource, s.Site[0].ResourceType)
require.Equal(t, tc.action, s.Site[0].Action)
require.Empty(t, s.ByOrgID)
require.Empty(t, s.User)
require.Equal(t, []rbac.AllowListElement{rbac.AllowListAll()}, s.AllowIDList)
})
}
})
t.Run("invalid_low_level", func(t *testing.T) {
t.Parallel()
invalid := []string{
"", // empty
"workspace:", // missing action
":read", // missing resource
"unknown:read", // unknown resource
"workspace:bogus", // unknown action
"a:b:c", // too many parts
}
for _, name := range invalid {
t.Run(name, func(t *testing.T) {
t.Parallel()
_, err := rbac.ScopeName(name).Expand()
require.Error(t, err)
})
}
})
}
func TestScopesCover(t *testing.T) {
t.Parallel()
tests := []struct {
name string
allowed []rbac.ScopeName
requested rbac.ScopeName
want bool
// wantErrContains names the side that could not be expanded. Asserting
// the side keeps rows that fail through different paths from passing
// on each other's errors.
wantErrContains string
}{
{
name: "IdenticalName",
allowed: []rbac.ScopeName{"workspace:read"},
requested: "workspace:read",
want: true,
},
{
// Name matching alone cannot decide this: coder:workspaces.access
// never mentions workspace:ssh by name, but its expansion covers it.
name: "CompositeCoversItsMember",
allowed: []rbac.ScopeName{"coder:workspaces.access"},
requested: "workspace:ssh",
want: true,
},
{
// The composite grants no permission on this resource at all.
name: "CompositeDoesNotCoverUnrelatedResource",
allowed: []rbac.ScopeName{"coder:workspaces.access"},
requested: "user_secret:delete",
want: false,
},
{
// Same resource, action the composite does not grant. Coverage
// compares the pair, not the resource alone.
name: "CompositeDoesNotCoverUngrantedActionOnSameResource",
allowed: []rbac.ScopeName{"coder:workspaces.access"},
requested: "workspace:delete",
want: false,
},
{
name: "AllCoversEverything",
allowed: []rbac.ScopeName{rbac.ScopeAll},
requested: "user_secret:delete",
want: true,
},
{
name: "NarrowScopeDoesNotCoverAll",
allowed: []rbac.ScopeName{"workspace:read"},
requested: rbac.ScopeAll,
want: false,
},
{
name: "ResourceWildcardCoversOneAction",
allowed: []rbac.ScopeName{"workspace:*"},
requested: "workspace:ssh",
want: true,
},
{
name: "OneActionDoesNotCoverResourceWildcard",
allowed: []rbac.ScopeName{"workspace:ssh"},
requested: "workspace:*",
want: false,
},
{
// A composite is covered only when every permission it expands
// to is granted, so a strict subset of them is not enough.
name: "PartialUnionDoesNotCoverComposite",
allowed: []rbac.ScopeName{"template:read", "file:create"},
requested: "coder:templates.build",
want: false,
},
{
// The allowed side is a union rather than a set of independent
// candidates, so one composite's permissions may be drawn from
// several allowed entries at once.
name: "UnionOfAllowedScopesCoversComposite",
allowed: []rbac.ScopeName{"template:read", "file:*", "provisioner_jobs:read"},
requested: "coder:templates.build",
want: true,
},
{
name: "EmptyAllowedCoversNothing",
allowed: nil,
requested: "workspace:read",
want: false,
},
{
// Not a false: a caller cannot distinguish "known and not
// covered" from "we could not tell", so an undecidable
// comparison is surfaced rather than answered.
name: "UnknownRequestedScopeErrors",
allowed: []rbac.ScopeName{rbac.ScopeAll},
requested: "not_a_real_scope",
wantErrContains: "expand requested scope",
},
{
name: "UnknownAllowedScopeErrors",
allowed: []rbac.ScopeName{"not_a_real_scope"},
requested: "workspace:read",
wantErrContains: "expand allowed scope",
},
{
// An implementation answering on the first match never reaches it.
name: "UnknownAllowedScopeErrorsBesideCoveringScope",
allowed: []rbac.ScopeName{rbac.ScopeAll, "not_a_real_scope"},
requested: "workspace:read",
wantErrContains: "expand allowed scope",
},
{
// The aliases IsExternalScope accepts are not expandable names,
// so callers must canonicalize before asking about coverage.
name: "NonCanonicalAliasErrorsRequestedAll",
allowed: []rbac.ScopeName{rbac.ScopeAll},
requested: "all",
wantErrContains: "expand requested scope",
},
{
name: "NonCanonicalAliasErrorsRequestedApplicationConnect",
allowed: []rbac.ScopeName{rbac.ScopeAll},
requested: "application_connect",
wantErrContains: "expand requested scope",
},
{
// The only row that would catch someone canonicalizing inside the
// allowed loop, which would silently widen what an allow list
// accepts without any caller asking for it.
name: "NonCanonicalAliasErrorsAllowedApplicationConnect",
allowed: []rbac.ScopeName{"application_connect"},
requested: rbac.ScopeApplicationConnect,
wantErrContains: "expand allowed scope",
},
{
name: "NonCanonicalAliasErrorsAllowedAll",
allowed: []rbac.ScopeName{"all"},
requested: rbac.ScopeAll,
wantErrContains: "expand allowed scope",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
got, err := rbac.ScopesCover(test.allowed, test.requested)
if test.wantErrContains != "" {
require.ErrorContains(t, err, test.wantErrContains)
require.False(t, got, "an undecided comparison must not report coverage")
return
}
require.NoError(t, err)
require.Equal(t, test.want, got)
})
}
}
// TestCanonicalScopeName pins the alias mapping. Without it the two case arms
// could be swapped, so that requesting `all` persisted application_connect and
// the reverse, and the suite would stay green.
func TestCanonicalScopeName(t *testing.T) {
t.Parallel()
require.Equal(t, rbac.ScopeAll, rbac.CanonicalScopeName("all"))
require.Equal(t, rbac.ScopeApplicationConnect, rbac.CanonicalScopeName("application_connect"))
// Canonical names and low-level names are returned unchanged, so callers
// can canonicalize unconditionally.
require.Equal(t, rbac.ScopeAll, rbac.CanonicalScopeName(rbac.ScopeAll))
require.Equal(t, rbac.ScopeApplicationConnect, rbac.CanonicalScopeName(rbac.ScopeApplicationConnect))
require.Equal(t, rbac.ScopeName("workspace:read"), rbac.CanonicalScopeName("workspace:read"))
require.Equal(t, rbac.ScopeName("not_a_real_scope"), rbac.CanonicalScopeName("not_a_real_scope"))
}
// TestScopesCoverEveryExternalScope asserts the property the OAuth2 allowlist
// check depends on: coder:all is a ceiling over the whole external catalog, and
// every catalog name covers itself. A name that cannot be compared at all would
// otherwise reject every request naming it, which is a rejection no app owner
// could act on.
func TestScopesCoverEveryExternalScope(t *testing.T) {
t.Parallel()
// The aliases inherit this without being named here: TestScopeAliases pins
// that each one canonicalizes to a name this list offers.
for _, name := range rbac.ExternalScopeNames() {
scope := rbac.ScopeName(name)
covered, err := rbac.ScopesCover([]rbac.ScopeName{rbac.ScopeAll}, scope)
require.NoErrorf(t, err, "coder:all vs %q", scope)
require.Truef(t, covered, "coder:all must cover %q", scope)
covered, err = rbac.ScopesCover([]rbac.ScopeName{scope}, scope)
require.NoErrorf(t, err, "%q vs itself", scope)
require.Truef(t, covered, "%q must cover itself", scope)
}
}