From b3c5d7190638469c78788681dd3e99a0877012a0 Mon Sep 17 00:00:00 2001 From: Stefan Tomm Date: Thu, 19 Nov 2026 13:49:19 +0100 Subject: [PATCH 1/5] fix: end a browser login that keycloak grants another access level than the chosen one Keycloak keeps one offline session per browser session and client and issues every token of it with the scopes of its first login. When that session began at Safe access, a later Full access login came back with cli-access-write. Login took the missing cli-access-full scope for a meshStack without access levels and stored no level, which reads as Full access, so the next login did not end the session either and every Full access login silently kept Safe access. A login that comes back with another level's scope now revokes the new refresh token, which ends that offline session, and fails with a message that names both levels and asks to log in again. If the revoke fails, the message names the two logins that end the session. A level is stored as empty only when the token carries no access level scope at all. Co-Authored-By: Claude Opus 5.5 --- internal/oidc/browser/browser.go | 39 +++++++++++++---- internal/oidc/browser/browser_test.go | 60 +++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 9 deletions(-) diff --git a/internal/oidc/browser/browser.go b/internal/oidc/browser/browser.go index c611e16e..06b99649 100644 --- a/internal/oidc/browser/browser.go +++ b/internal/oidc/browser/browser.go @@ -11,7 +11,6 @@ import ( "net" gohttp "net/http" "os" - "slices" "strings" "sync" "time" @@ -71,15 +70,11 @@ func Login(ctx context.Context, endpoint xurl.URL, client oidc.Client, previous if err != nil { return oidc.Token{}, "", err } - chosen := login.chosenLevel() - if slices.Contains(strings.Fields(token.Scope), string(chosen.Scope())) { - return token, chosen, nil - } - if chosen != meshstack.AccessFull { - return oidc.Token{}, "", fmt.Errorf("this meshStack does not support access levels yet: %s did not grant the access level %q, "+ - "so the login would have full access; log in again and choose %q", client.Issuer, chosen.Label(), meshstack.AccessFull.Label()) + level, err := login.grantedLevel(ctx, token) + if err != nil { + return oidc.Token{}, "", err } - return token, "", nil + return token, level, nil } // Previous is the login of the profile that a new login replaces. @@ -238,6 +233,32 @@ func (l *loginPages) receiveRedirect(w gohttp.ResponseWriter, r *gohttp.Request) l.arrive(callback{code: query.Get("code")}) } +func (l *loginPages) grantedLevel(ctx context.Context, token oidc.Token) (meshstack.AccessLevel, error) { + chosen := l.chosenLevel() + var scopes scope.Scopes + for granted := range strings.FieldsSeq(token.Scope) { + scopes = append(scopes, scope.Scope(granted)) + } + granted, ok := meshstack.AccessLevelOf(scopes) + if !ok { + if chosen == meshstack.AccessFull { + return "", nil + } + return "", fmt.Errorf("this meshStack does not support access levels yet: %s did not grant the access level %q, "+ + "so the login would have full access; log in again and choose %q", l.flow.Issuer, chosen.Label(), meshstack.AccessFull.Label()) + } + if granted == chosen { + return granted, nil + } + if err := l.flow.RevokeRefreshToken(ctx, token.RefreshToken); err != nil { + return "", fmt.Errorf("%s granted the access level %q instead of %q, because it kept the access level of an earlier login, "+ + "and cannot end that login: %w; log in once with %q, then again with %q", + l.flow.Issuer, granted.Label(), chosen.Label(), err, granted.Label(), chosen.Label()) + } + return "", fmt.Errorf("%s granted the access level %q instead of %q, because it kept the access level of an earlier login; "+ + "that login is now ended, so log in again and choose %q", l.flow.Issuer, granted.Label(), chosen.Label(), chosen.Label()) +} + // arrive keeps the first result: a second callback, such as a reloaded tab, must not block. func (l *loginPages) arrive(result callback) { select { diff --git a/internal/oidc/browser/browser_test.go b/internal/oidc/browser/browser_test.go index 44ea065e..6bd617bb 100644 --- a/internal/oidc/browser/browser_test.go +++ b/internal/oidc/browser/browser_test.go @@ -11,8 +11,10 @@ import ( "github.com/stretchr/testify/require" "github.com/meshcloud/meshstack-cli/client/types/xurl" + "github.com/meshcloud/meshstack-cli/internal/http" "github.com/meshcloud/meshstack-cli/internal/meshstack" "github.com/meshcloud/meshstack-cli/internal/oidc" + "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" ) func newLoginPages(previous meshstack.AccessLevel) *loginPages { @@ -88,3 +90,61 @@ func TestAnAccessLevelFromAnotherPageIsRefused(t *testing.T) { assert.Equal(t, gohttp.StatusBadRequest, submitAccessLevel(t, pages, "the-nonce", "admin").Code) assert.Empty(t, pages.chosenLevel()) } + +func TestALoginThatKeycloakGrantsAnotherAccessLevelIsEnded(t *testing.T) { + var revoked []string + revokeFails := false + server := httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) { + revoked = append(revoked, r.PostFormValue("token")) + if revokeFails { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(gohttp.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"error":"temporarily_unavailable","error_description":"try later"}`)) + } + })) + defer server.Close() + + pages := newLoginPages("") + pages.flow.Client.Client = http.NewClient(fakemeshstack.UserAgent) + pages.flow.Issuer = xurl.MustParsef("https://keycloak.example/realms/meshfed") + pages.flow.RevocationEndpoint = new(xurl.MustParsef("%s/revoke", server.URL)) + pages.chosen = meshstack.AccessFull + tokenWith := func(scopes string) oidc.Token { + return oidc.Token{RefreshToken: "offline-" + scopes, Scope: "openid offline_access " + scopes} + } + + t.Run("the chosen level is stored", func(t *testing.T) { + level, err := pages.grantedLevel(t.Context(), tokenWith("cli-access-full")) + + require.NoError(t, err) + assert.Equal(t, meshstack.AccessFull, level) + assert.Empty(t, revoked) + }) + + t.Run("a meshStack without access levels stores none for full access", func(t *testing.T) { + level, err := pages.grantedLevel(t.Context(), tokenWith("email")) + + require.NoError(t, err) + assert.Empty(t, level) + assert.Empty(t, revoked) + }) + + t.Run("full access granted as safe access ends the login", func(t *testing.T) { + level, err := pages.grantedLevel(t.Context(), tokenWith("cli-access-write")) + + require.ErrorContains(t, err, `granted the access level "Safe access" instead of "Full access"`) + require.ErrorContains(t, err, `log in again and choose "Full access"`) + assert.Empty(t, level) + assert.Equal(t, []string{"offline-cli-access-write"}, revoked) + }) + + t.Run("a login that cannot be ended names the two logins that fix it", func(t *testing.T) { + revokeFails = true + pages.chosen = meshstack.AccessRead + + _, err := pages.grantedLevel(t.Context(), tokenWith("cli-access-write")) + + require.ErrorContains(t, err, "try later") + require.ErrorContains(t, err, `log in once with "Safe access", then again with "Read-only"`) + }) +} From 27392e2ccb1c953c2145c594576d1556547dbc32 Mon Sep 17 00:00:00 2001 From: Stefan Tomm Date: Thu, 19 Nov 2026 14:04:53 +0100 Subject: [PATCH 2/5] fix: take the previous access level of a browser login from its tokens A login that a CLI with the bug stored without a level read as Full access, although its tokens grant Safe access. The next Full access login then skipped ending the earlier session before the redirect and failed. The previous level now comes from the scope of the login's latest cached token, so that login ends the session first and succeeds. The stored level is the fallback when there is no token, or none of them carries a level scope. A login that comes back with no access level scope when Safe access or Read-only was chosen now ends its session too. It could be a session from before access levels rather than a meshStack without them, and without ending it every retry would fail the same way. Keycloak 26.2 and later end only the revoked token's own offline session and the CLI's client session in the matching browser session. Keycloak 26.0 instead revoked the client's consent and every offline session of the user for the client. Co-Authored-By: Claude Opus 5.5 --- internal/auth/credential/oidclogin.go | 16 ++++++++++ internal/auth/credential/oidclogin_test.go | 36 ++++++++++++++++++++++ internal/auth/credential_oidclogin.go | 2 +- internal/oidc/browser/browser.go | 26 ++++++++++------ internal/oidc/browser/browser_test.go | 9 ++++++ 5 files changed, 78 insertions(+), 11 deletions(-) diff --git a/internal/auth/credential/oidclogin.go b/internal/auth/credential/oidclogin.go index bf177aff..fc5f494f 100644 --- a/internal/auth/credential/oidclogin.go +++ b/internal/auth/credential/oidclogin.go @@ -54,6 +54,22 @@ func (oidcLogin *OidcLogin) StoreLogin(oidcToken oidc.Token) { oidcLogin.Cache.ScopedTokens[tokenCacheKey(token.GetClaim(jwt.WorkspaceClaim))] = token } +func (oidcLogin *OidcLogin) GrantedLevel() meshstack.AccessLevel { + if oidcLogin.Cache == nil { + return oidcLogin.AccessLevel + } + var latest jwt.JWT + for _, token := range oidcLogin.Cache.ScopedTokens { + if token.GetClaim(jwt.ExpiryClaim).After(latest.GetClaim(jwt.ExpiryClaim).Time) { + latest = token + } + } + if level, ok := meshstack.AccessLevelOf(latest.GetClaim(jwt.ScopeClaim)); ok { + return level + } + return oidcLogin.AccessLevel +} + func (oidcLogin *OidcLogin) CachedToken(ctx context.Context, getWorkspace getWorkspaceFunc) (token jwt.JWT, found bool) { if oidcLogin.Cache == nil { return diff --git a/internal/auth/credential/oidclogin_test.go b/internal/auth/credential/oidclogin_test.go index 0fe90e17..9ef62cfb 100644 --- a/internal/auth/credential/oidclogin_test.go +++ b/internal/auth/credential/oidclogin_test.go @@ -1,13 +1,17 @@ package credential import ( + "encoding/base64" + "fmt" "testing" "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/meshcloud/meshstack-cli/internal/meshstack" "github.com/meshcloud/meshstack-cli/internal/oidc" + "github.com/meshcloud/meshstack-cli/internal/oidc/jwt" ) func TestTheWorkspaceDecidesTheCacheKeyAndTheScopesAsked(t *testing.T) { @@ -47,3 +51,35 @@ func TestALoginKeepsTheSessionEndOfItsLatestToken(t *testing.T) { login.StoreLogin(oidc.Token{RefreshToken: "rotated"}) assert.True(t, login.Cache.RefreshExpiresAt.IsZero(), "a refresh that names no limit leaves none") } + +func TestThePreviousAccessLevelIsTheOneItsLatestTokenGrants(t *testing.T) { + tokenWith := func(t *testing.T, expiry int64, scopes string) jwt.JWT { + t.Helper() + claims := fmt.Sprintf(`{"exp":%d,"scope":%q}`, expiry, scopes) + var token jwt.JWT + require.NoError(t, token.UnmarshalText([]byte("e30."+base64.RawURLEncoding.EncodeToString([]byte(claims))+".sig"))) + return token + } + login := &OidcLogin{} + + t.Run("a login without tokens keeps the stored level", func(t *testing.T) { + login.AccessLevel = meshstack.AccessRead + assert.Equal(t, meshstack.AccessRead, login.GrantedLevel()) + }) + + t.Run("a login stored as full access that its tokens grant safe access is safe access", func(t *testing.T) { + login.AccessLevel = "" + login.StoreLogin(oidc.Token{AccessToken: tokenWith(t, 1000, "openid cli-access-write")}) + assert.Equal(t, meshstack.AccessWrite, login.GrantedLevel()) + }) + + t.Run("the latest token decides", func(t *testing.T) { + login.Cache.ScopedTokens["c:demo"] = tokenWith(t, 2000, "openid cli-access-full") + assert.Equal(t, meshstack.AccessFull, login.GrantedLevel()) + }) + + t.Run("a meshStack without access levels keeps the stored level", func(t *testing.T) { + login.Cache.ScopedTokens["c:demo"] = tokenWith(t, 3000, "openid email") + assert.Empty(t, login.GrantedLevel()) + }) +} diff --git a/internal/auth/credential_oidclogin.go b/internal/auth/credential_oidclogin.go index 3c506878..b4a96f4b 100644 --- a/internal/auth/credential_oidclogin.go +++ b/internal/auth/credential_oidclogin.go @@ -21,10 +21,10 @@ func (s Session) resolveOidcLoginCredential(ctx context.Context, previous *crede } var replaced browser.Previous if previous != nil { - replaced.Level = previous.AccessLevel if err = CacheFor(s.CurrentProfile, previous).Load(ctx); err != nil { return Credential{}, err } + replaced.Level = previous.GrantedLevel() if previous.Cache != nil { replaced.RefreshToken = previous.Cache.RefreshToken } diff --git a/internal/oidc/browser/browser.go b/internal/oidc/browser/browser.go index 06b99649..c929b919 100644 --- a/internal/oidc/browser/browser.go +++ b/internal/oidc/browser/browser.go @@ -240,20 +240,26 @@ func (l *loginPages) grantedLevel(ctx context.Context, token oidc.Token) (meshst scopes = append(scopes, scope.Scope(granted)) } granted, ok := meshstack.AccessLevelOf(scopes) - if !ok { - if chosen == meshstack.AccessFull { - return "", nil - } - return "", fmt.Errorf("this meshStack does not support access levels yet: %s did not grant the access level %q, "+ - "so the login would have full access; log in again and choose %q", l.flow.Issuer, chosen.Label(), meshstack.AccessFull.Label()) - } - if granted == chosen { + switch { + case ok && granted == chosen: return granted, nil + case !ok && chosen == meshstack.AccessFull: + return "", nil } - if err := l.flow.RevokeRefreshToken(ctx, token.RefreshToken); err != nil { + revokeErr := l.flow.RevokeRefreshToken(ctx, token.RefreshToken) + switch { + case !ok && revokeErr != nil: + return "", fmt.Errorf("%s granted no access level instead of %q, so the login would have full access, and cannot end that login: %w; "+ + "log in again and choose %q, or %q if this meshStack does not support access levels yet", + l.flow.Issuer, chosen.Label(), revokeErr, chosen.Label(), meshstack.AccessFull.Label()) + case !ok: + return "", fmt.Errorf("%s granted no access level instead of %q, so the login would have full access; that login is now ended, "+ + "so log in again and choose %q, or %q if this meshStack does not support access levels yet", + l.flow.Issuer, chosen.Label(), chosen.Label(), meshstack.AccessFull.Label()) + case revokeErr != nil: return "", fmt.Errorf("%s granted the access level %q instead of %q, because it kept the access level of an earlier login, "+ "and cannot end that login: %w; log in once with %q, then again with %q", - l.flow.Issuer, granted.Label(), chosen.Label(), err, granted.Label(), chosen.Label()) + l.flow.Issuer, granted.Label(), chosen.Label(), revokeErr, granted.Label(), chosen.Label()) } return "", fmt.Errorf("%s granted the access level %q instead of %q, because it kept the access level of an earlier login; "+ "that login is now ended, so log in again and choose %q", l.flow.Issuer, granted.Label(), chosen.Label(), chosen.Label()) diff --git a/internal/oidc/browser/browser_test.go b/internal/oidc/browser/browser_test.go index 6bd617bb..d68c0cf7 100644 --- a/internal/oidc/browser/browser_test.go +++ b/internal/oidc/browser/browser_test.go @@ -138,6 +138,15 @@ func TestALoginThatKeycloakGrantsAnotherAccessLevelIsEnded(t *testing.T) { assert.Equal(t, []string{"offline-cli-access-write"}, revoked) }) + t.Run("safe access granted without any access level ends the login", func(t *testing.T) { + pages.chosen = meshstack.AccessWrite + + _, err := pages.grantedLevel(t.Context(), tokenWith("email")) + + require.ErrorContains(t, err, `granted no access level instead of "Safe access"`) + assert.Equal(t, []string{"offline-cli-access-write", "offline-email"}, revoked) + }) + t.Run("a login that cannot be ended names the two logins that fix it", func(t *testing.T) { revokeFails = true pages.chosen = meshstack.AccessRead From d384842da59f3d94dd65f8b75caca982998b47b5 Mon Sep 17 00:00:00 2001 From: Stefan Tomm Date: Thu, 19 Nov 2026 15:26:37 +0100 Subject: [PATCH 3/5] test: log in a second profile with full access in a browser that holds a safe access login This is the case behind the fix: Keycloak grants a login the access level of another profile's earlier login in the same browser session. The test checks three things: - that first login fails and ends the shared session, so the other profile's refresh token stops working too - the next login gets the level it chose, both stored and in its token - the logout test now uses the same refresh check Co-Authored-By: Claude Opus 5.5 --- cmd/internal/testacc/login_test.go | 47 +++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/cmd/internal/testacc/login_test.go b/cmd/internal/testacc/login_test.go index c1fc1652..bd95a4d8 100644 --- a/cmd/internal/testacc/login_test.go +++ b/cmd/internal/testacc/login_test.go @@ -113,6 +113,32 @@ func TestAccBrowserLogin(t *testing.T) { assert.Equal(t, "full", tokenAccessLevel(t, c), "the token keeps the access level of the earlier login") }) + t.Run("a profile that keycloak grants the access level of another profile's login gets its own on the next login", func(t *testing.T) { + browser := panelLogin(t, issuer, withWorkspace.Username, withWorkspace.Password) + loginWith := func(c *cli, level string) error { + run := startLogin(t, c, "1") + continueKeycloakLogin(t, browser, run.awaitStartURL(t), level, withWorkspace.Username) + err := run.wait() + t.Logf("`meshstack login` with %s access said:\n%s", level, run.output.String()) + return err + } + safe := newCLI(t, endpoint) + require.NoError(t, loginWith(safe, "write")) + safeRefreshToken := cachedRefreshToken(t, safe) + full := newCLI(t, endpoint) + + err := loginWith(full, "full") + require.Error(t, err, "keycloak granted full access although the browser session already holds a login with safe access") + require.ErrorContains(t, err, `granted the access level "Safe access" instead of "Full access"`) + assert.NoFileExists(t, full.credentialsJson()) + assert.Equal(t, gohttp.StatusBadRequest, refreshStatus(t, issuer, safeRefreshToken), + "ending the login with safe access must end the session the other profile shares") + + require.NoError(t, loginWith(full, "full")) + assert.Equal(t, "full", storedAccessLevel(t, full)) + assert.Equal(t, "full", tokenAccessLevel(t, full), "keycloak still grants the access level of the ended login") + }) + t.Run("a logout ends the session of the browser login", func(t *testing.T) { c := newCLI(t, endpoint) run := startLogin(t, c, "1") @@ -123,14 +149,7 @@ func TestAccBrowserLogin(t *testing.T) { output, err := c.run("", "auth", "logout") require.NoErrorf(t, err, "the logout failed:\n%s", output) - refresh := url.Values{"client_id": {"meshstack-cli"}, "grant_type": {"refresh_token"}, "refresh_token": {refreshToken}} - req, err := gohttp.NewRequestWithContext(t.Context(), gohttp.MethodPost, issuer+"/protocol/openid-connect/token", strings.NewReader(refresh.Encode())) - require.NoError(t, err) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - refreshed, err := gohttp.DefaultClient.Do(req) - require.NoError(t, err) - _ = refreshed.Body.Close() - assert.Equal(t, gohttp.StatusBadRequest, refreshed.StatusCode, "keycloak still refreshes the token of the logged out login") + assert.Equal(t, gohttp.StatusBadRequest, refreshStatus(t, issuer, refreshToken), "keycloak still refreshes the token of the logged out login") }) t.Run("a login holds the profiles until the browser comes back", browserLoginHoldsTheProfiles(endpoint, withWorkspace)) @@ -173,6 +192,18 @@ func firstLoginWithAWorkspace(t *testing.T, logins []devLogin) devLogin { return logins[found] } +func refreshStatus(t *testing.T, issuer, refreshToken string) int { + t.Helper() + refresh := url.Values{"client_id": {"meshstack-cli"}, "grant_type": {"refresh_token"}, "refresh_token": {refreshToken}} + req, err := gohttp.NewRequestWithContext(t.Context(), gohttp.MethodPost, issuer+"/protocol/openid-connect/token", strings.NewReader(refresh.Encode())) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + refreshed, err := gohttp.DefaultClient.Do(req) + require.NoError(t, err) + _ = refreshed.Body.Close() + return refreshed.StatusCode +} + func storedAccessLevel(t *testing.T, c *cli) string { t.Helper() content, err := os.ReadFile(c.credentialsJson()) From 80569efa55c11dc6031f73d3bf248dfafda296b9 Mon Sep 17 00:00:00 2001 From: Stefan Tomm Date: Thu, 19 Nov 2026 16:01:12 +0100 Subject: [PATCH 4/5] fix: read the granted access level from the access token, not the token response The acceptance test showed what really happens: a Full access login in a browser session that already held a Safe access login stored Full access, but its access token carried cli-access-write. The scope field of Keycloak's token response does not match the access token's own scope claim, and meshStack authorizes by that claim, so the login has to check the claim. Co-Authored-By: Claude Opus 5.5 --- internal/oidc/browser/browser.go | 7 ++----- internal/oidc/browser/browser_test.go | 8 +++++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/internal/oidc/browser/browser.go b/internal/oidc/browser/browser.go index c929b919..c93c736b 100644 --- a/internal/oidc/browser/browser.go +++ b/internal/oidc/browser/browser.go @@ -19,6 +19,7 @@ import ( "github.com/meshcloud/meshstack-cli/internal/io" "github.com/meshcloud/meshstack-cli/internal/meshstack" "github.com/meshcloud/meshstack-cli/internal/oidc" + "github.com/meshcloud/meshstack-cli/internal/oidc/jwt" "github.com/meshcloud/meshstack-cli/internal/oidc/scope" ) @@ -235,11 +236,7 @@ func (l *loginPages) receiveRedirect(w gohttp.ResponseWriter, r *gohttp.Request) func (l *loginPages) grantedLevel(ctx context.Context, token oidc.Token) (meshstack.AccessLevel, error) { chosen := l.chosenLevel() - var scopes scope.Scopes - for granted := range strings.FieldsSeq(token.Scope) { - scopes = append(scopes, scope.Scope(granted)) - } - granted, ok := meshstack.AccessLevelOf(scopes) + granted, ok := meshstack.AccessLevelOf(token.AccessToken.GetClaim(jwt.ScopeClaim)) switch { case ok && granted == chosen: return granted, nil diff --git a/internal/oidc/browser/browser_test.go b/internal/oidc/browser/browser_test.go index d68c0cf7..4cf22f6c 100644 --- a/internal/oidc/browser/browser_test.go +++ b/internal/oidc/browser/browser_test.go @@ -1,6 +1,8 @@ package browser import ( + "encoding/base64" + "fmt" gohttp "net/http" "net/http/httptest" "net/url" @@ -14,6 +16,7 @@ import ( "github.com/meshcloud/meshstack-cli/internal/http" "github.com/meshcloud/meshstack-cli/internal/meshstack" "github.com/meshcloud/meshstack-cli/internal/oidc" + "github.com/meshcloud/meshstack-cli/internal/oidc/jwt" "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" ) @@ -110,7 +113,10 @@ func TestALoginThatKeycloakGrantsAnotherAccessLevelIsEnded(t *testing.T) { pages.flow.RevocationEndpoint = new(xurl.MustParsef("%s/revoke", server.URL)) pages.chosen = meshstack.AccessFull tokenWith := func(scopes string) oidc.Token { - return oidc.Token{RefreshToken: "offline-" + scopes, Scope: "openid offline_access " + scopes} + claims := fmt.Sprintf(`{"scope":"openid offline_access %s"}`, scopes) + var accessToken jwt.JWT + require.NoError(t, accessToken.UnmarshalText([]byte("e30."+base64.RawURLEncoding.EncodeToString([]byte(claims))+".sig"))) + return oidc.Token{AccessToken: accessToken, RefreshToken: "offline-" + scopes, Scope: "openid offline_access cli-access-full"} } t.Run("the chosen level is stored", func(t *testing.T) { From f8352696ee10d0ddb16a483ef54e3fa58821b0e9 Mon Sep 17 00:00:00 2001 From: Stefan Tomm Date: Thu, 19 Nov 2026 16:17:12 +0100 Subject: [PATCH 5/5] fix: check the access level of a browser login on its first refresh The acceptance run on 80569ef shows a Full access login that shares its browser session with a Safe access login of another profile. Its code-exchange token passes the check: it carries either cli-access-full or no level scope, and the run cannot tell which. The workspace token that the login fetches next by a refresh grants Safe access. A refresh takes its scopes from the offline session, which the two logins share. 80569ef put the cause in a mismatch between the token response and the access token. The run does not show that. Reading the level from the access token's claim is still right, since meshStack authorizes by that claim. The login now refreshes its new token once, with openid and offline_access so it inherits no workspace, and checks the level on the refreshed token. It keeps that token, because Keycloak rotates the refresh token on every refresh. On a mismatch it revokes the refreshed refresh token. The acceptance test now names the stored level and the token's level when the Full access login passes. Co-Authored-By: Claude Opus 5.5 --- cmd/internal/testacc/login_test.go | 5 ++++- internal/oidc/browser/browser.go | 7 ++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/cmd/internal/testacc/login_test.go b/cmd/internal/testacc/login_test.go index bd95a4d8..8b870c90 100644 --- a/cmd/internal/testacc/login_test.go +++ b/cmd/internal/testacc/login_test.go @@ -128,7 +128,10 @@ func TestAccBrowserLogin(t *testing.T) { full := newCLI(t, endpoint) err := loginWith(full, "full") - require.Error(t, err, "keycloak granted full access although the browser session already holds a login with safe access") + if err == nil { + t.Fatalf("the login with full access passed, storing the level %q while its token grants %q", + storedAccessLevel(t, full), tokenAccessLevel(t, full)) + } require.ErrorContains(t, err, `granted the access level "Safe access" instead of "Full access"`) assert.NoFileExists(t, full.credentialsJson()) assert.Equal(t, gohttp.StatusBadRequest, refreshStatus(t, issuer, safeRefreshToken), diff --git a/internal/oidc/browser/browser.go b/internal/oidc/browser/browser.go index c93c736b..84b11ec6 100644 --- a/internal/oidc/browser/browser.go +++ b/internal/oidc/browser/browser.go @@ -67,10 +67,15 @@ func Login(ctx context.Context, endpoint xurl.URL, client oidc.Client, previous if err != nil { return oidc.Token{}, "", err } - token, err := login.flow.Exchange(ctx, code) + exchanged, err := login.flow.Exchange(ctx, code) if err != nil { return oidc.Token{}, "", err } + token, err := client.Refresh(ctx, exchanged.RefreshToken, scope.Scopes{scope.OpenId, scope.OfflineAccess}) + if err != nil { + return oidc.Token{}, "", fmt.Errorf("cannot renew the new login at %s to read the access level it keeps: %w", client.Issuer, err) + } + token.RefreshToken = cmp.Or(token.RefreshToken, exchanged.RefreshToken) level, err := login.grantedLevel(ctx, token) if err != nil { return oidc.Token{}, "", err