Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 42 additions & 8 deletions cmd/internal/testacc/login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,35 @@ 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")
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),
"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")
Expand All @@ -123,14 +152,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))
Expand Down Expand Up @@ -173,6 +195,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())
Expand Down
16 changes: 16 additions & 0 deletions internal/auth/credential/oidclogin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions internal/auth/credential/oidclogin_test.go
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -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())
})
}
2 changes: 1 addition & 1 deletion internal/auth/credential_oidclogin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
47 changes: 38 additions & 9 deletions internal/oidc/browser/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"net"
gohttp "net/http"
"os"
"slices"
"strings"
"sync"
"time"
Expand All @@ -20,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"
)

Expand Down Expand Up @@ -67,19 +67,20 @@ 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
}
chosen := login.chosenLevel()
if slices.Contains(strings.Fields(token.Scope), string(chosen.Scope())) {
return token, chosen, nil
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)
}
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())
token.RefreshToken = cmp.Or(token.RefreshToken, exchanged.RefreshToken)
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.
Expand Down Expand Up @@ -238,6 +239,34 @@ 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()
granted, ok := meshstack.AccessLevelOf(token.AccessToken.GetClaim(jwt.ScopeClaim))
switch {
case ok && granted == chosen:
return granted, nil
case !ok && chosen == meshstack.AccessFull:
return "", 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(), 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())
}

// arrive keeps the first result: a second callback, such as a reloaded tab, must not block.
func (l *loginPages) arrive(result callback) {
select {
Expand Down
75 changes: 75 additions & 0 deletions internal/oidc/browser/browser_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package browser

import (
"encoding/base64"
"fmt"
gohttp "net/http"
"net/http/httptest"
"net/url"
Expand All @@ -11,8 +13,11 @@ 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/oidc/jwt"
"github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack"
)

func newLoginPages(previous meshstack.AccessLevel) *loginPages {
Expand Down Expand Up @@ -88,3 +93,73 @@ 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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

d: Please make this an acc test case and really check it works? I've investigated this as well and I doubt it has a simple solution.

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 {
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) {
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("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

_, 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"`)
})
}
Loading