| 1 |
// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 |
// Licensed under the MIT License. See LICENSE in the project root for license information. |
| 3 |
|
| 4 |
package cache |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"os" |
| 11 |
"path/filepath" |
| 12 |
"runtime" |
| 13 |
"sync" |
| 14 |
"testing" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" |
| 18 |
"github.com/stretchr/testify/require" |
| 19 |
) |
| 20 |
|
| 21 |
var ctx = context.Background() |
| 22 |
|
| 23 |
// fakeExternalCache implements accessor.Accessor to fake a persistent cache |
| 24 |
type fakeExternalCache struct { |
| 25 |
data []byte |
| 26 |
readCallback, writeCallback func() error |
| 27 |
} |
| 28 |
|
| 29 |
func (c *fakeExternalCache) Delete(context.Context) error { |
| 30 |
c.data = nil |
| 31 |
return nil |
| 32 |
} |
| 33 |
|
| 34 |
func (a *fakeExternalCache) Read(context.Context) ([]byte, error) { |
| 35 |
var err error |
| 36 |
if a.readCallback != nil { |
| 37 |
err = a.readCallback() |
| 38 |
} |
| 39 |
return a.data, err |
| 40 |
} |
| 41 |
|
| 42 |
func (a *fakeExternalCache) Write(ctx context.Context, b []byte) error { |
| 43 |
var err error |
| 44 |
if a.writeCallback != nil { |
| 45 |
err = a.writeCallback() |
| 46 |
} |
| 47 |
if err != nil { |
| 48 |
return err |
| 49 |
} |
| 50 |
cp := make([]byte, len(b)) |
| 51 |
copy(cp, b) |
| 52 |
a.data = cp |
| 53 |
return nil |
| 54 |
} |
| 55 |
|
| 56 |
// fakeInternalCache implements cache.Un/Marshaler to fake an MSAL client's in-memory cache |
| 57 |
type fakeInternalCache struct { |
| 58 |
data []byte |
| 59 |
marshalCallback, unmarshalCallback func() error |
| 60 |
} |
| 61 |
|
| 62 |
func (t *fakeInternalCache) Marshal() ([]byte, error) { |
| 63 |
var err error |
| 64 |
if t.marshalCallback != nil { |
| 65 |
err = t.marshalCallback() |
| 66 |
} |
| 67 |
return t.data, err |
| 68 |
} |
| 69 |
|
| 70 |
func (t *fakeInternalCache) Unmarshal(b []byte) error { |
| 71 |
var err error |
| 72 |
if t.unmarshalCallback != nil { |
| 73 |
err = t.unmarshalCallback() |
| 74 |
} |
| 75 |
cp := make([]byte, len(b)) |
| 76 |
copy(cp, b) |
| 77 |
t.data = cp |
| 78 |
return err |
| 79 |
} |
| 80 |
|
| 81 |
type fakeLock struct { |
| 82 |
lockErr, unlockErr error |
| 83 |
} |
| 84 |
|
| 85 |
func (l fakeLock) Lock(context.Context) error { |
| 86 |
return l.lockErr |
| 87 |
} |
| 88 |
|
| 89 |
func (l fakeLock) Unlock() error { |
| 90 |
return l.unlockErr |
| 91 |
} |
| 92 |
|
| 93 |
func TestExport(t *testing.T) { |
| 94 |
ec := &fakeExternalCache{} |
| 95 |
ic := &fakeInternalCache{} |
| 96 |
p := filepath.Join(t.TempDir(), t.Name(), "ts") |
| 97 |
c, err := New(ec, p) |
| 98 |
require.NoError(t, err) |
| 99 |
|
| 100 |
// Export should write the in-memory cache to the accessor and touch the timestamp file |
| 101 |
lastWrite := time.Time{} |
| 102 |
touched := false |
| 103 |
for i := 0; i < 3; i++ { |
| 104 |
s := fmt.Sprint(i) |
| 105 |
*ic = fakeInternalCache{data: []byte(s)} |
| 106 |
err = c.Export(ctx, ic, cache.ExportHints{}) |
| 107 |
require.NoError(t, err) |
| 108 |
require.Equal(t, []byte(s), ec.data) |
| 109 |
|
| 110 |
f, err := os.Stat(p) |
| 111 |
require.NoError(t, err) |
| 112 |
mt := f.ModTime() |
| 113 |
|
| 114 |
// Two iterations of this loop can run within one unit of system time on Windows, leaving the |
| 115 |
// modtime apparently unchanged even though Export updated it. On Windows we therefore skip |
| 116 |
// the strict test, instead requiring only that the modtime change once during this loop. |
| 117 |
if runtime.GOOS != "windows" { |
| 118 |
require.NotEqual(t, lastWrite, mt, "Export didn't update the timestamp") |
| 119 |
} |
| 120 |
if mt != lastWrite { |
| 121 |
touched = true |
| 122 |
} |
| 123 |
lastWrite = mt |
| 124 |
} |
| 125 |
require.True(t, touched, "Export didn't update the timestamp") |
| 126 |
} |
| 127 |
|
| 128 |
func TestFilenameCompat(t *testing.T) { |
| 129 |
// verify Cache uses the same lock file name as would e.g. the Python implementation |
| 130 |
p := filepath.Join(t.TempDir(), t.Name()) |
| 131 |
ec := fakeExternalCache{ |
| 132 |
// Cache should hold the file lock while calling Write |
| 133 |
writeCallback: func() error { |
| 134 |
require.FileExists(t, p+".lockfile", "missing expected lock file") |
| 135 |
return nil |
| 136 |
}, |
| 137 |
} |
| 138 |
c, err := New(&ec, p) |
| 139 |
require.NoError(t, err) |
| 140 |
|
| 141 |
err = c.Export(ctx, &fakeInternalCache{}, cache.ExportHints{}) |
| 142 |
require.NoError(t, err) |
| 143 |
} |
| 144 |
|
| 145 |
func TestLockError(t *testing.T) { |
| 146 |
c, err := New(&fakeExternalCache{}, filepath.Join(t.TempDir(), t.Name())) |
| 147 |
require.NoError(t, err) |
| 148 |
expected := errors.New("expected") |
| 149 |
c.l = fakeLock{lockErr: expected} |
| 150 |
err = c.Export(ctx, &fakeInternalCache{}, cache.ExportHints{}) |
| 151 |
require.EqualError(t, err, expected.Error()) |
| 152 |
} |
| 153 |
|
| 154 |
func TestPreservesTimestampFileContent(t *testing.T) { |
| 155 |
p := filepath.Join(t.TempDir(), t.Name()) |
| 156 |
expected := []byte("expected") |
| 157 |
err := os.WriteFile(p, expected, 0600) |
| 158 |
require.NoError(t, err) |
| 159 |
|
| 160 |
ec := fakeExternalCache{} |
| 161 |
c, err := New(&ec, p) |
| 162 |
require.NoError(t, err) |
| 163 |
|
| 164 |
ic := fakeInternalCache{data: []byte("data")} |
| 165 |
err = c.Export(ctx, &ic, cache.ExportHints{}) |
| 166 |
require.NoError(t, err) |
| 167 |
require.Equal(t, ic.data, ec.data) |
| 168 |
|
| 169 |
actual, err := os.ReadFile(p) |
| 170 |
require.NoError(t, err) |
| 171 |
require.Equal(t, expected, actual, "Cache truncated, or wrote to, the timestamp file") |
| 172 |
} |
| 173 |
|
| 174 |
func TestRace(t *testing.T) { |
| 175 |
ic := fakeInternalCache{} |
| 176 |
ec := fakeExternalCache{} |
| 177 |
c, err := New(&ec, filepath.Join(t.TempDir(), t.Name())) |
| 178 |
require.NoError(t, err) |
| 179 |
|
| 180 |
wg := sync.WaitGroup{} |
| 181 |
for i := 0; i < 100; i++ { |
| 182 |
wg.Add(1) |
| 183 |
go func(i int) { |
| 184 |
defer wg.Done() |
| 185 |
if !t.Failed() { |
| 186 |
err := c.Replace(ctx, &ic, cache.ReplaceHints{}) |
| 187 |
if err == nil { |
| 188 |
err = c.Export(ctx, &ic, cache.ExportHints{}) |
| 189 |
} |
| 190 |
if err != nil { |
| 191 |
t.Errorf("%d: %s", i, err) |
| 192 |
} |
| 193 |
} |
| 194 |
}(i) |
| 195 |
} |
| 196 |
wg.Wait() |
| 197 |
} |
| 198 |
|
| 199 |
func TestReplace(t *testing.T) { |
| 200 |
ic := fakeInternalCache{} |
| 201 |
ec := fakeExternalCache{} |
| 202 |
p := filepath.Join(t.TempDir(), t.Name()) |
| 203 |
|
| 204 |
c, err := New(&ec, p) |
| 205 |
require.NoError(t, err) |
| 206 |
require.Empty(t, ic) |
| 207 |
|
| 208 |
// Replace should read data from the accessor (external cache) into the in-memory cache, observing the timestamp file |
| 209 |
f, err := os.Create(p) |
| 210 |
require.NoError(t, err) |
| 211 |
require.NoError(t, f.Close()) |
| 212 |
for i := uint8(0); i < 4; i++ { |
| 213 |
ec.data = []byte{i} |
| 214 |
err = c.Replace(ctx, &ic, cache.ReplaceHints{}) |
| 215 |
require.NoError(t, err) |
| 216 |
require.EqualValues(t, ec.data, ic.data) |
| 217 |
// touch the timestamp file to indicate another accessor wrote data. Backdating ensures the |
| 218 |
// timestamp changes between iterations even when one executes faster than file time resolution |
| 219 |
tm := time.Now().Add(-time.Duration(i+1) * time.Second) |
| 220 |
require.NoError(t, os.Chtimes(p, tm, tm)) |
| 221 |
} |
| 222 |
|
| 223 |
// Replace should return in-memory data when the timestamp indicates no intervening write to the persistent cache |
| 224 |
for i := 0; i < 4; i++ { |
| 225 |
err = c.Replace(ctx, &ic, cache.ReplaceHints{}) |
| 226 |
require.NoError(t, err) |
| 227 |
// ec.data hasn't changed; ic.data shouldn't change either |
| 228 |
require.EqualValues(t, ec.data, ic.data) |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
func TestReplaceErrors(t *testing.T) { |
| 233 |
realDelay := retryDelay |
| 234 |
retryDelay = 0 |
| 235 |
t.Cleanup(func() { retryDelay = realDelay }) |
| 236 |
expected := errors.New("expected") |
| 237 |
|
| 238 |
t.Run("read", func(t *testing.T) { |
| 239 |
ec := &fakeExternalCache{readCallback: func() error { |
| 240 |
return expected |
| 241 |
}} |
| 242 |
p := filepath.Join(t.TempDir(), t.Name()) |
| 243 |
c, err := New(ec, p) |
| 244 |
require.NoError(t, err) |
| 245 |
|
| 246 |
err = c.Replace(ctx, &fakeInternalCache{}, cache.ReplaceHints{}) |
| 247 |
require.Equal(t, expected, err) |
| 248 |
}) |
| 249 |
|
| 250 |
for _, transient := range []bool{true, false} { |
| 251 |
name := "unmarshal error" |
| 252 |
if transient { |
| 253 |
name = "transient " + name |
| 254 |
} |
| 255 |
t.Run(name, func(t *testing.T) { |
| 256 |
tries := 0 |
| 257 |
ic := fakeInternalCache{unmarshalCallback: func() error { |
| 258 |
tries++ |
| 259 |
if transient && tries > 1 { |
| 260 |
return nil |
| 261 |
} |
| 262 |
return expected |
| 263 |
}} |
| 264 |
ec := &fakeExternalCache{} |
| 265 |
|
| 266 |
p := filepath.Join(t.TempDir(), t.Name()) |
| 267 |
c, err := New(ec, p) |
| 268 |
require.NoError(t, err) |
| 269 |
|
| 270 |
cx, cancel := context.WithTimeout(ctx, time.Millisecond) |
| 271 |
defer cancel() |
| 272 |
err = c.Replace(cx, &ic, cache.ReplaceHints{}) |
| 273 |
// err should be nil if the unmarshaling error was transient, non-nil if it wasn't |
| 274 |
require.Equal(t, transient, err == nil) |
| 275 |
}) |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
func TestUnlockError(t *testing.T) { |
| 280 |
p := filepath.Join(t.TempDir(), t.Name()) |
| 281 |
a := fakeExternalCache{} |
| 282 |
c, err := New(&a, p) |
| 283 |
require.NoError(t, err) |
| 284 |
|
| 285 |
// Export should return an error from Unlock()... |
| 286 |
unlockErr := errors.New("unlock error") |
| 287 |
c.l = fakeLock{unlockErr: unlockErr} |
| 288 |
err = c.Export(ctx, &fakeInternalCache{}, cache.ExportHints{}) |
| 289 |
require.Equal(t, unlockErr, err) |
| 290 |
|
| 291 |
// ...unless another of its calls returned an error |
| 292 |
writeErr := errors.New("write error") |
| 293 |
a.writeCallback = func() error { return writeErr } |
| 294 |
err = c.Export(ctx, &fakeInternalCache{}, cache.ExportHints{}) |
| 295 |
require.Equal(t, writeErr, err) |
| 296 |
} |