|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/base64" |
| 5 | + "encoding/json" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/brevdev/brev-cli/pkg/entity" |
| 9 | + "github.com/brevdev/brev-cli/pkg/store" |
| 10 | + "github.com/spf13/afero" |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | + "github.com/stretchr/testify/require" |
| 13 | +) |
| 14 | + |
| 15 | +// fakeJWT builds an unsigned JWT with the given claims (header.payload.signature). |
| 16 | +func fakeJWT(t *testing.T, claims map[string]interface{}) string { |
| 17 | + t.Helper() |
| 18 | + header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none","typ":"JWT"}`)) |
| 19 | + payload, err := json.Marshal(claims) |
| 20 | + require.NoError(t, err) |
| 21 | + return header + "." + base64.RawURLEncoding.EncodeToString(payload) + "." |
| 22 | +} |
| 23 | + |
| 24 | +func newTestFileStore(t *testing.T) *store.FileStore { |
| 25 | + t.Helper() |
| 26 | + fs := afero.NewMemMapFs() |
| 27 | + err := fs.MkdirAll("/home/testuser/.brev", 0o755) |
| 28 | + require.NoError(t, err) |
| 29 | + return store.NewBasicStore().WithFileSystem(fs).WithUserHomeDirGetter( |
| 30 | + func() (string, error) { return "/home/testuser", nil }, |
| 31 | + ) |
| 32 | +} |
| 33 | + |
| 34 | +func TestEmailCachingAuthStore_SaveCachesEmail(t *testing.T) { |
| 35 | + fs := newTestFileStore(t) |
| 36 | + s := &emailCachingAuthStore{ |
| 37 | + MemoryAuthStore: store.NewMemoryAuthStore(), |
| 38 | + fileStore: fs, |
| 39 | + } |
| 40 | + |
| 41 | + token := fakeJWT(t, map[string]interface{}{"email": "user@example.com"}) |
| 42 | + err := s.SaveAuthTokens(entity.AuthTokens{AccessToken: token}) |
| 43 | + require.NoError(t, err) |
| 44 | + |
| 45 | + cached, err := fs.GetCachedEmail() |
| 46 | + require.NoError(t, err) |
| 47 | + assert.Equal(t, "user@example.com", cached) |
| 48 | +} |
| 49 | + |
| 50 | +func TestEmailCachingAuthStore_NoEmailInToken(t *testing.T) { |
| 51 | + fs := newTestFileStore(t) |
| 52 | + s := &emailCachingAuthStore{ |
| 53 | + MemoryAuthStore: store.NewMemoryAuthStore(), |
| 54 | + fileStore: fs, |
| 55 | + } |
| 56 | + |
| 57 | + token := fakeJWT(t, map[string]interface{}{"sub": "12345"}) |
| 58 | + err := s.SaveAuthTokens(entity.AuthTokens{AccessToken: token}) |
| 59 | + require.NoError(t, err) |
| 60 | + |
| 61 | + cached, err := fs.GetCachedEmail() |
| 62 | + require.NoError(t, err) |
| 63 | + assert.Equal(t, "", cached) |
| 64 | +} |
| 65 | + |
| 66 | +func TestEmailCachingAuthStore_EmptyAccessToken(t *testing.T) { |
| 67 | + fs := newTestFileStore(t) |
| 68 | + s := &emailCachingAuthStore{ |
| 69 | + MemoryAuthStore: store.NewMemoryAuthStore(), |
| 70 | + fileStore: fs, |
| 71 | + } |
| 72 | + |
| 73 | + err := s.SaveAuthTokens(entity.AuthTokens{AccessToken: ""}) |
| 74 | + require.Error(t, err) |
| 75 | +} |
0 commit comments