-
Notifications
You must be signed in to change notification settings - Fork 347
/
Copy pathStorage.cs
242 lines (219 loc) · 9.47 KB
/
Storage.cs
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Identity.Extensions;
namespace Microsoft.Identity.Client.Extensions.Msal
{
/// <summary>
/// Wrapper over persistence layer. Does not use cross-process locking. To add cross-process locking, wrap calls
/// with <see cref="CrossPlatLock"/>
/// </summary>
/// <remarks>Consider using the higher level <see cref="MsalCacheHelper"/></remarks>
public class Storage
{
private readonly TraceSourceLogger _logger;
internal /* internal for test only */ ICacheAccessor CacheAccessor { get; }
/// <summary>
/// The storage creation properties used to create this storage
/// </summary>
internal StorageCreationProperties StorageCreationProperties { get; }
internal const string PersistenceValidationDummyData = "msal_persistence_test";
/// <summary>
/// A default logger for use if the user doesn't want to provide their own.
/// </summary>
private static readonly Lazy<TraceSourceLogger> s_staticLogger = new Lazy<TraceSourceLogger>(() =>
{
return new TraceSourceLogger(EnvUtils.GetNewTraceSource(nameof(MsalCacheHelper) + "Singleton"));
});
/// <summary>
/// Initializes a new instance of the <see cref="Storage"/> class.
/// The actual cache reading and writing is OS specific:
/// <list type="bullet">
/// <item>
/// <term>Windows</term>
/// <description>DPAPI encrypted file on behalf of the user. </description>
/// </item>
/// <item>
/// <term>Mac</term>
/// <description>Cache is stored in KeyChain. </description>
/// </item>
/// <item>
/// <term>Linux</term>
/// <description>Cache is stored in Gnome KeyRing - https://developer.gnome.org/libsecret/0.18/ </description>
/// </item>
/// </list>
/// </summary>
/// <param name="creationProperties">Properties for creating the cache storage on disk</param>
/// <param name="logger">logger</param>
/// <returns></returns>
public static Storage Create(StorageCreationProperties creationProperties, TraceSource logger = null)
{
TraceSourceLogger actualLogger = logger == null ? s_staticLogger.Value : new TraceSourceLogger(logger);
ICacheAccessor cacheAccessor;
if (creationProperties.UseUnencryptedFallback)
{
cacheAccessor = new FileAccessor(creationProperties.CacheFilePath, setOwnerOnlyPermissions: true, logger: actualLogger);
}
else
{
if (SharedUtilities.IsWindowsPlatform())
{
cacheAccessor = new DpApiEncryptedFileAccessor(creationProperties.CacheFilePath, logger: actualLogger);
}
else if (SharedUtilities.IsMacPlatform())
{
cacheAccessor = new MacKeychainAccessor(
creationProperties.CacheFilePath,
creationProperties.MacKeyChainServiceName,
creationProperties.MacKeyChainAccountName,
actualLogger);
}
else if (SharedUtilities.IsLinuxPlatform())
{
if (creationProperties.UseLinuxUnencryptedFallback)
{
cacheAccessor = new FileAccessor(creationProperties.CacheFilePath, setOwnerOnlyPermissions: true, actualLogger);
}
else
{
cacheAccessor = new LinuxKeyringAccessor(
creationProperties.CacheFilePath,
creationProperties.KeyringCollection,
creationProperties.KeyringSchemaName,
creationProperties.KeyringSecretLabel,
creationProperties.KeyringAttribute1.Key,
creationProperties.KeyringAttribute1.Value,
creationProperties.KeyringAttribute2.Key,
creationProperties.KeyringAttribute2.Value,
actualLogger);
}
}
else
{
throw new PlatformNotSupportedException();
}
}
return new Storage(creationProperties, cacheAccessor, actualLogger);
}
internal /* internal for test, otherwise private */ Storage(
StorageCreationProperties creationProperties,
ICacheAccessor cacheAccessor,
TraceSourceLogger logger)
{
StorageCreationProperties = creationProperties;
_logger = logger;
CacheAccessor = cacheAccessor;
_logger.LogInformation($"Initialized '{nameof(Storage)}'");
}
/// <summary>
/// Read and unprotect cache data
/// </summary>
/// <returns>Unprotected cache data</returns>
public byte[] ReadData()
{
byte[] data = null;
try
{
_logger.LogInformation($"Reading Data");
data = CacheAccessor.Read();
_logger.LogInformation($"Got '{data?.Length ?? 0}' bytes from file storage");
}
catch (Exception e)
{
_logger.LogError($"An exception was encountered while reading data from the {nameof(Storage)} : {e}");
throw;
}
return data ?? new byte[0];
}
/// <summary>
/// Protect and write cache data to file. It overrides existing data.
/// </summary>
/// <param name="data">Cache data</param>
public void WriteData(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
try
{
_logger.LogInformation($"Got '{data?.Length}' bytes to write to storage");
CacheAccessor.Write(data);
}
catch (Exception e)
{
_logger.LogError($"An exception was encountered while writing data to {nameof(Storage)} : {e}");
throw;
}
}
/// <summary>
/// Delete cache file
/// </summary>
/// <param name="ignoreExceptions">Throw on exceptions</param>
public void Clear(bool ignoreExceptions = false)
{
try
{
_logger.LogInformation("Clearing the cache file");
CacheAccessor.Clear();
}
catch (Exception e)
{
_logger.LogError($"An exception was encountered while clearing data from {nameof(Storage)} : {e}");
if (!ignoreExceptions)
throw;
}
}
/// <summary>
/// Tries to write -> read -> clear a secret from the underlying persistence mechanism
/// </summary>
public void VerifyPersistence()
{
// do not use the _cacheAccessor for writing dummy data, as it might overwrite an actual token cache
var persitenceValidatationAccessor = CacheAccessor.CreateForPersistenceValidation();
try
{
_logger.LogInformation($"[Verify Persistence] Writing Data ");
persitenceValidatationAccessor.Write(Encoding.UTF8.GetBytes(PersistenceValidationDummyData));
_logger.LogInformation($"[Verify Persistence] Reading Data ");
var data = persitenceValidatationAccessor.Read();
if (data == null || data.Length == 0)
{
throw new MsalCachePersistenceException(
"Persistence check failed. Data was written but it could not be read. " +
"Possible cause: on Linux, LibSecret is installed but D-Bus isn't running because it cannot be started over SSH.");
}
string dataRead = Encoding.UTF8.GetString(data);
if (!string.Equals(PersistenceValidationDummyData, dataRead, StringComparison.Ordinal))
{
throw new MsalCachePersistenceException(
$"Persistence check failed. Data written {PersistenceValidationDummyData} is different from data read {dataRead}");
}
}
catch (InteropException e)
{
throw new MsalCachePersistenceException(
$"Persistence check failed. Reason: {e.Message}. OS error code {e.ErrorCode}.", e);
}
catch (Exception ex) when (!(ex is MsalCachePersistenceException))
{
throw new MsalCachePersistenceException("Persistence check failed. Inspect inner exception for details", ex);
}
finally
{
try
{
_logger.LogInformation($"[Verify Persistence] Clearing data");
persitenceValidatationAccessor.Clear();
}
catch (Exception e)
{
_logger.LogError($"[Verify Persistence] Could not clear the test data: " + e);
}
}
}
}
}