**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>
250 lines
8.8 KiB
Go
250 lines
8.8 KiB
Go
package rbac
|
|
|
|
import (
|
|
"reflect"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/coder/coder/v2/coderd/rbac/policy"
|
|
)
|
|
|
|
var (
|
|
workspaceRead = Permission{ResourceType: "workspace", Action: policy.ActionRead}
|
|
workspaceDelete = Permission{ResourceType: "workspace", Action: policy.ActionDelete}
|
|
workspaceWildcard = Permission{ResourceType: "workspace", Action: policy.WildcardSymbol}
|
|
workspaceDeleteNegate = Permission{ResourceType: "workspace", Action: policy.ActionDelete, Negate: true}
|
|
wildcardResourceRead = Permission{ResourceType: policy.WildcardSymbol, Action: policy.ActionRead}
|
|
)
|
|
|
|
// coverableScope is the shape every ExpandScope result has: site permissions
|
|
// only, wildcard allow list, no negatives.
|
|
func coverableScope(perms ...Permission) Scope {
|
|
return Scope{
|
|
Role: Role{Site: perms},
|
|
AllowIDList: []AllowListElement{AllowListAll()},
|
|
}
|
|
}
|
|
|
|
// TestScopeAliases asserts what the shared table exists to guarantee, which no
|
|
// test outside this package can: every alias is public, resolves to a public
|
|
// name, and resolves to one the RBAC layer can expand. A name IsExternalScope
|
|
// calls public but ExpandScope rejects is requestable in name only, and every
|
|
// request naming it fails. Iterating the table rather than naming the two
|
|
// aliases means a third is covered the day it is added.
|
|
func TestScopeAliases(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
require.NotEmpty(t, scopeAliases)
|
|
|
|
for alias, canonical := range scopeAliases {
|
|
require.Truef(t, IsExternalScope(alias), "alias %q must be public", alias)
|
|
require.Equalf(t, canonical, CanonicalScopeName(alias), "alias %q", alias)
|
|
|
|
// An alias is a second spelling of a scope, not a scope of its own.
|
|
require.Truef(t, IsExternalScope(canonical), "canonical %q must be public", canonical)
|
|
_, err := ExpandScope(canonical)
|
|
require.NoErrorf(t, err, "canonical %q must expand", canonical)
|
|
|
|
// The alias itself does not expand, which is what makes
|
|
// canonicalization mandatory before storage or coverage rather than a
|
|
// tidying step callers may skip.
|
|
_, err = ExpandScope(alias)
|
|
require.Errorf(t, err, "alias %q must not expand directly", alias)
|
|
|
|
// The list a client reads offers the canonical spelling and only that
|
|
// one, so a caller can request a name from it and store what it
|
|
// requested. Listing the alias too would offer two names for one scope,
|
|
// one of which fails to expand once stored.
|
|
require.NotContainsf(t, ExternalScopeNames(), string(alias), "list must omit alias %q", alias)
|
|
require.Containsf(t, ExternalScopeNames(), string(canonical), "list must offer %q", canonical)
|
|
}
|
|
}
|
|
|
|
// TestScopesCoverGuards drives Scope values that no catalog entry produces.
|
|
// The guards exist for authority ScopeName inputs cannot express today, so
|
|
// ScopesCover cannot reach them and they would otherwise ship unverified.
|
|
//
|
|
// Each shape runs on both sides of the comparison, with the opposite side
|
|
// coverable, so a guard consulted on only one side fails here.
|
|
func TestScopesCoverGuards(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
scope Scope
|
|
wantErr string
|
|
}{
|
|
{
|
|
name: "SitePermissionsOnly",
|
|
scope: coverableScope(workspaceRead),
|
|
},
|
|
{
|
|
name: "UserPermission",
|
|
scope: Scope{
|
|
Role: Role{
|
|
Site: []Permission{workspaceRead},
|
|
User: []Permission{workspaceRead},
|
|
},
|
|
AllowIDList: []AllowListElement{AllowListAll()},
|
|
},
|
|
wantErr: "grants org or user permissions",
|
|
},
|
|
{
|
|
// The case the guards were added for: a scope granting every
|
|
// workspace action except delete. The permission coverage reads is
|
|
// harmless, and the one it does not read carves delete back out, so
|
|
// comparing on Site alone would answer a request for
|
|
// workspace:delete from a wildcard the scope has already qualified.
|
|
name: "NegativeUserPermission",
|
|
scope: Scope{
|
|
Role: Role{
|
|
Site: []Permission{workspaceWildcard},
|
|
User: []Permission{workspaceDeleteNegate},
|
|
},
|
|
AllowIDList: []AllowListElement{AllowListAll()},
|
|
},
|
|
wantErr: "grants org or user permissions",
|
|
},
|
|
{
|
|
name: "OrgPermission",
|
|
scope: Scope{
|
|
Role: Role{
|
|
Site: []Permission{workspaceRead},
|
|
ByOrgID: map[string]OrgPermissions{"00000000-0000-0000-0000-000000000001": {}},
|
|
},
|
|
AllowIDList: []AllowListElement{AllowListAll()},
|
|
},
|
|
wantErr: "grants org or user permissions",
|
|
},
|
|
{
|
|
name: "NegativeSitePermission",
|
|
scope: coverableScope(workspaceWildcard, workspaceDeleteNegate),
|
|
wantErr: "carries a negative permission",
|
|
},
|
|
{
|
|
name: "NarrowedAllowList",
|
|
scope: Scope{
|
|
Role: Role{Site: []Permission{workspaceRead}},
|
|
AllowIDList: []AllowListElement{{Type: "workspace", ID: "00000000-0000-0000-0000-000000000002"}},
|
|
},
|
|
wantErr: "carries a resource allow list",
|
|
},
|
|
}
|
|
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
// The opposite side always covers, so a guard error stays
|
|
// distinguishable from an ordinary uncovered result.
|
|
cleanGrant := namedScope{name: "clean_scope", scope: coverableScope(workspaceWildcard)}
|
|
cleanRequest := namedScope{name: "clean_scope", scope: coverableScope(workspaceRead)}
|
|
under := namedScope{name: "test_scope", scope: test.scope}
|
|
|
|
sides := []struct {
|
|
side string
|
|
allowed []namedScope
|
|
requested namedScope
|
|
}{
|
|
{side: coverageSideRequested, allowed: []namedScope{cleanGrant}, requested: under},
|
|
{side: coverageSideAllowed, allowed: []namedScope{under}, requested: cleanRequest},
|
|
}
|
|
|
|
for _, args := range sides {
|
|
side := args.side
|
|
got, err := scopesCoverExpanded(args.allowed, args.requested)
|
|
if test.wantErr == "" {
|
|
require.NoErrorf(t, err, "side %q", side)
|
|
require.Truef(t, got, "side %q", side)
|
|
continue
|
|
}
|
|
require.ErrorContainsf(t, err, test.wantErr, "side %q", side)
|
|
// The side names itself, so an operator reading the error can
|
|
// tell which half of the comparison was undecidable.
|
|
require.ErrorContainsf(t, err, side+` scope "test_scope"`, "side %q", side)
|
|
require.Falsef(t, got, "an undecided comparison must not report coverage, side %q", side)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// The only wildcard resource the catalog spells is coder:all's {*, *}, so no
|
|
// catalog-driven case reaches this shape.
|
|
func TestScopesCoverWildcardResourceChecksAction(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
allowed := []namedScope{{name: "wildcard_read", scope: coverableScope(wildcardResourceRead)}}
|
|
|
|
// Positive control: the wildcard resource does match, so the assertion
|
|
// below fails on the action rather than the resource.
|
|
covered, err := scopesCoverExpanded(allowed, namedScope{name: "workspace_read", scope: coverableScope(workspaceRead)})
|
|
require.NoError(t, err)
|
|
require.True(t, covered)
|
|
|
|
covered, err = scopesCoverExpanded(allowed, namedScope{name: "workspace_delete", scope: coverableScope(workspaceDelete)})
|
|
require.NoError(t, err)
|
|
require.False(t, covered, "read on every resource must not cover delete")
|
|
|
|
// The mirror, on the requested side.
|
|
covered, err = scopesCoverExpanded(
|
|
[]namedScope{{name: "workspace_read", scope: coverableScope(workspaceRead)}},
|
|
namedScope{name: "wildcard_read", scope: coverableScope(wildcardResourceRead)},
|
|
)
|
|
require.NoError(t, err)
|
|
require.False(t, covered, "read on one resource must not cover read on every resource")
|
|
}
|
|
|
|
// TestCoverageModelFields fails when one of the types coverage reads grows a
|
|
// field, so someone decides whether checkCoverable has to account for it.
|
|
func TestCoverageModelFields(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
typ reflect.Type
|
|
fields []string
|
|
}{
|
|
{
|
|
// permissionCovered compares ResourceType and Action; Negate is
|
|
// why checkCoverable refuses a scope carrying one.
|
|
name: "Permission",
|
|
typ: reflect.TypeOf(Permission{}),
|
|
fields: []string{"Negate", "ResourceType", "Action"},
|
|
},
|
|
{
|
|
// Scope embeds Role, so Role is where Site, User, and ByOrgID
|
|
// reach the guards.
|
|
name: "Role",
|
|
typ: reflect.TypeOf(Role{}),
|
|
fields: []string{"Identifier", "DisplayName", "Site", "User", "ByOrgID", "cachedRegoValue"},
|
|
},
|
|
{
|
|
name: "Scope",
|
|
typ: reflect.TypeOf(Scope{}),
|
|
fields: []string{"Role", "AllowIDList"},
|
|
},
|
|
{
|
|
// allowListContainsAll reads both fields to decide whether the
|
|
// allow list leaves the Site permissions unconditional.
|
|
name: "AllowListElement",
|
|
typ: reflect.TypeOf(AllowListElement{}),
|
|
fields: []string{"ID", "Type"},
|
|
},
|
|
}
|
|
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
got := make([]string, 0, test.typ.NumField())
|
|
for i := range test.typ.NumField() {
|
|
got = append(got, test.typ.Field(i).Name)
|
|
}
|
|
|
|
require.ElementsMatchf(t, test.fields, got,
|
|
"%s changed shape: decide whether the new field carries authority coverage must model, extend checkCoverable if it does, then update this list", test.name)
|
|
})
|
|
}
|
|
}
|