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