Skip to content

Commit 4a402d3

Browse files
committed
fix(coderd): canonicalize API key scope aliases at ingress
IsExternalScope accepts `all` and `application_connect`, which are not api_key_scope enum members. The plural Scopes field appended the requested name verbatim, so POST /users/{user}/keys/tokens with {"scopes":["all"]} passed validation and then failed inside apikey.Generate, answering HTTP 500 with `invalid API key scope: "all"`. codersdk still exports APIKeyScopeAll and APIKeyScopeApplicationConnect, so a caller reaches this by passing the constants the SDK offers for exactly this purpose. Route every accepted name through rbac.CanonicalScopeName. That fixes the plural path and deletes the two open-coded alias switches, which restated a mapping the rbac package already owns and had to be kept in step by hand. The singular Scope field behaves as before, now by the shared table.
1 parent eab5e28 commit 4a402d3

3 files changed

Lines changed: 61 additions & 23 deletions

File tree

‎coderd/apikey.go‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -68,37 +68,32 @@ func (api *API) postToken(rw http.ResponseWriter, r *http.Request) {
6868
// Map and validate requested scope.
6969
// Accept legacy special scopes (all, application_connect) and external scopes.
7070
// Default to coder:all scopes for backward compatibility.
71+
// IsExternalScope accepts alias spellings that are not api_key_scope enum
72+
// members, so every accepted name is canonicalized before it is stored.
7173
scopes := database.APIKeyScopes{database.ApiKeyScopeCoderAll}
7274
if len(createToken.Scopes) > 0 {
7375
scopes = make(database.APIKeyScopes, 0, len(createToken.Scopes))
7476
for _, s := range createToken.Scopes {
75-
name := string(s)
76-
if !rbac.IsExternalScope(rbac.ScopeName(name)) {
77+
name := rbac.ScopeName(s)
78+
if !rbac.IsExternalScope(name) {
7779
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
7880
Message: "Failed to create API key.",
7981
Detail: fmt.Sprintf("invalid or unsupported API key scope: %q", name),
8082
})
8183
return
8284
}
83-
scopes = append(scopes, database.APIKeyScope(name))
85+
scopes = append(scopes, database.APIKeyScope(rbac.CanonicalScopeName(name)))
8486
}
8587
} else if string(createToken.Scope) != "" {
86-
name := string(createToken.Scope)
87-
if !rbac.IsExternalScope(rbac.ScopeName(name)) {
88+
name := rbac.ScopeName(createToken.Scope)
89+
if !rbac.IsExternalScope(name) {
8890
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
8991
Message: "Failed to create API key.",
9092
Detail: fmt.Sprintf("invalid or unsupported API key scope: %q", name),
9193
})
9294
return
9395
}
94-
switch name {
95-
case "all":
96-
scopes = database.APIKeyScopes{database.ApiKeyScopeCoderAll}
97-
case "application_connect":
98-
scopes = database.APIKeyScopes{database.ApiKeyScopeCoderApplicationConnect}
99-
default:
100-
scopes = database.APIKeyScopes{database.APIKeyScope(name)}
101-
}
96+
scopes = database.APIKeyScopes{database.APIKeyScope(rbac.CanonicalScopeName(name))}
10297
}
10398

10499
tokenName := namesgenerator.NameDigitWith("_")

‎coderd/apikey/apikey.go‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313

1414
"github.com/coder/coder/v2/coderd/database"
1515
"github.com/coder/coder/v2/coderd/database/dbtime"
16+
"github.com/coder/coder/v2/coderd/rbac"
1617
"github.com/coder/coder/v2/coderd/rbac/policy"
1718
"github.com/coder/coder/v2/cryptorand"
1819
)
@@ -87,16 +88,10 @@ func Generate(params CreateParams) (database.InsertAPIKeyParams, string, error)
8788
case len(params.Scopes) > 0:
8889
scopes = params.Scopes
8990
case params.Scope != "":
90-
var scope database.APIKeyScope
91-
switch params.Scope {
92-
case "all":
93-
scope = database.ApiKeyScopeCoderAll
94-
case "application_connect":
95-
scope = database.ApiKeyScopeCoderApplicationConnect
96-
default:
97-
scope = params.Scope
98-
}
99-
scopes = database.APIKeyScopes{scope}
91+
// Callers may pass an alias spelling, which is not an api_key_scope enum
92+
// member and so would fail the validity check below.
93+
canonical := rbac.CanonicalScopeName(rbac.ScopeName(params.Scope))
94+
scopes = database.APIKeyScopes{database.APIKeyScope(canonical)}
10095
default:
10196
// Default to coder:all scope for backward compatibility.
10297
scopes = database.APIKeyScopes{database.ApiKeyScopeCoderAll}

‎coderd/apikey_test.go‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,54 @@ func TestTokenLegacySingularScopeCompat(t *testing.T) {
180180
}
181181
}
182182

183+
// The plural Scopes field accepts the same legacy names as the singular Scope
184+
// field above: IsExternalScope validates both spellings, and codersdk still
185+
// exports APIKeyScopeAll and APIKeyScopeApplicationConnect for callers to pass.
186+
// Both must persist canonically, since the api_key_scope enum has no member for
187+
// either alias and convertAPIKey derives the deprecated singular field by
188+
// looking for the canonical value.
189+
func TestTokenLegacyPluralScopeCompat(t *testing.T) {
190+
t.Parallel()
191+
192+
cases := []struct {
193+
name string
194+
requested codersdk.APIKeyScope
195+
canonical codersdk.APIKeyScope
196+
}{
197+
{
198+
name: "all",
199+
requested: codersdk.APIKeyScopeAll,
200+
canonical: codersdk.APIKeyScopeCoderAll,
201+
},
202+
{
203+
name: "application_connect",
204+
requested: codersdk.APIKeyScopeApplicationConnect,
205+
canonical: codersdk.APIKeyScopeCoderApplicationConnect,
206+
},
207+
}
208+
209+
for _, tc := range cases {
210+
t.Run(tc.name, func(t *testing.T) {
211+
t.Parallel()
212+
ctx, cancel := context.WithTimeout(t.Context(), testutil.WaitLong)
213+
defer cancel()
214+
client := coderdtest.New(t, nil)
215+
_ = coderdtest.CreateFirstUser(t, client)
216+
217+
_, err := client.CreateToken(ctx, codersdk.Me, codersdk.CreateTokenRequest{
218+
Scopes: []codersdk.APIKeyScope{tc.requested},
219+
})
220+
require.NoError(t, err)
221+
222+
keys, err := client.Tokens(ctx, codersdk.Me, codersdk.TokensFilter{})
223+
require.NoError(t, err)
224+
require.Len(t, keys, 1)
225+
require.Equal(t, []codersdk.APIKeyScope{tc.canonical}, keys[0].Scopes)
226+
require.Equal(t, tc.requested, keys[0].Scope)
227+
})
228+
}
229+
}
230+
183231
func TestUserSetTokenDuration(t *testing.T) {
184232
t.Parallel()
185233

0 commit comments

Comments
 (0)