-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUID2Client.cs
More file actions
171 lines (147 loc) · 6.19 KB
/
UID2Client.cs
File metadata and controls
171 lines (147 loc) · 6.19 KB
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
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace UID2.Client
{
[Obsolete("Please use BidstreamClient or SharingClient instead")]
internal class UID2Client : IUID2Client
{
public static readonly HttpMethod RefreshHttpMethod = HttpMethod.Post;
private readonly string _endpoint;
private readonly string _authKey;
private readonly byte[] _secretKey;
private readonly IdentityScope _identityScope;
private readonly HttpClient _client;
private KeyContainer _container;
public UID2Client(string endpoint, string authKey, string secretKey, IdentityScope identityScope)
{
_client = new HttpClient();
_endpoint = endpoint;
_authKey = authKey;
_secretKey = Convert.FromBase64String(secretKey);
_identityScope = identityScope;
}
public DecryptionResponse Decrypt(string token)
{
return Decrypt(token, DateTime.UtcNow, null, ClientType.LegacyWithoutDomainOrAppNameCheck);
}
public DecryptionResponse Decrypt(string token, DateTime utcNow)
{
return Decrypt(token, utcNow, null, ClientType.LegacyWithoutDomainOrAppNameCheck);
}
public DecryptionResponse Decrypt(string token, string domainOrAppNameFromBidRequest)
{
return Decrypt(token, DateTime.UtcNow, domainOrAppNameFromBidRequest, ClientType.LegacyWithDomainOrAppNameCheck);
}
private DecryptionResponse Decrypt(string token, DateTime now, string domainOrAppNameFromBidRequest, ClientType clientType)
{
var container = Volatile.Read(ref _container);
if (container == null)
{
return DecryptionResponse.MakeError(DecryptionStatus.NotInitialized);
}
if (!container.IsValid(now))
{
return DecryptionResponse.MakeError(DecryptionStatus.KeysNotSynced);
}
try
{
var tokenDetails = UID2Encryption.DecryptTokenDetails(token, container, now, domainOrAppNameFromBidRequest, _identityScope, clientType);
return TokenHelper.TokenDetailsToDecryptionResponse(tokenDetails);
}
catch (Exception)
{
return DecryptionResponse.MakeError(DecryptionStatus.InvalidPayload);
}
}
public EncryptionDataResponse Encrypt(string rawUid)
{
return Encrypt(rawUid, DateTime.UtcNow);
}
internal EncryptionDataResponse Encrypt(string rawUid, DateTime now)
{
return UID2Encryption.Encrypt(rawUid, Volatile.Read(ref _container), _identityScope, now);
}
public EncryptionDataResponse EncryptData(EncryptionDataRequest request)
{
return UID2Encryption.EncryptData(request, Volatile.Read(ref _container), _identityScope);
}
public DecryptionDataResponse DecryptData(String encryptedData)
{
var container = Volatile.Read(ref _container);
if (container == null)
{
return DecryptionDataResponse.MakeError(DecryptionStatus.NotInitialized);
}
if (!container.IsValid(DateTime.UtcNow))
{
return DecryptionDataResponse.MakeError(DecryptionStatus.KeysNotSynced);
}
try
{
return UID2Encryption.DecryptData(Convert.FromBase64String(encryptedData), container, _identityScope);
}
catch (Exception)
{
return DecryptionDataResponse.MakeError(DecryptionStatus.InvalidPayload);
}
}
public RefreshResponse Refresh()
{
return RefreshInternal(CancellationToken.None).Result;
}
public RefreshResponse RefreshJson(string json)
{
try
{
Volatile.Write(ref _container, KeyParser.Parse(json));
return RefreshResponse.MakeSuccess();
}
catch (Exception e)
{
return RefreshResponse.MakeError(e.Message);
}
}
public async Task<RefreshResponse> RefreshAsync(CancellationToken token)
{
return await RefreshInternal(token).ConfigureAwait(false);
}
private async Task<RefreshResponse> RefreshInternal(CancellationToken token)
{
var request = new HttpRequestMessage(RefreshHttpMethod, _endpoint + "/v2/key/sharing");
request.Headers.Add("Authorization", $"Bearer {_authKey}");
request.Headers.Add("X-UID2-Client-Version", $"{Uid2ClientHelper.GetAssemblyNameAndVersion()}");
HttpStatusCode? statusCode = null;
try
{
var (body, nonce) = V2Helper.MakeEnvelope(_secretKey, DateTime.UtcNow);
request.Content = new StringContent(body, Encoding.ASCII);
using (var response = await _client.SendAsync(request, token).ConfigureAwait(false))
{
statusCode = response.StatusCode;
response.EnsureSuccessStatusCode();
var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
using (var reader = new StreamReader(responseStream))
{
var responseBody = await reader.ReadToEndAsync().ConfigureAwait(false);
var responseBytes = V2Helper.ParseResponse(responseBody, _secretKey, nonce);
Volatile.Write(ref _container, KeyParser.Parse(Encoding.UTF8.GetString(responseBytes)));
}
return RefreshResponse.MakeSuccess();
}
}
catch (HttpRequestException webEx)
{
return RefreshResponse.MakeError($"Web error: HttpStatus={statusCode}, {webEx.Message}");
}
catch (Exception parserEx)
{
return RefreshResponse.MakeError(parserEx.Message);
}
}
}
}