-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathWorldPermissionsService.cs
More file actions
321 lines (278 loc) · 12.7 KB
/
Copy pathWorldPermissionsService.cs
File metadata and controls
321 lines (278 loc) · 12.7 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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
using CommunicationData.URLHelpers;
using Cysharp.Threading.Tasks;
using DCL.Diagnostics;
using DCL.Multiplayer.Connections.DecentralandUrls;
using DCL.Web3.Identities;
using DCL.WebRequests;
using Newtonsoft.Json;
using System;
using System.Threading;
namespace DCL.PrivateWorlds
{
public enum WorldAccessCheckResult
{
Allowed,
PasswordRequired,
AccessDenied,
CheckFailed
}
/// <summary>
/// Contains the result of an access check along with additional context.
/// </summary>
public struct WorldAccessCheckContext
{
public WorldAccessCheckResult Result { get; set; }
public WorldAccessInfo? AccessInfo { get; set; }
public string? ErrorMessage { get; set; }
}
/// <summary>
/// Interface for the world permissions service.
/// </summary>
public interface IWorldPermissionsService
{
/// <summary>
/// Fetches and checks if the current user has access to a world.
/// </summary>
/// <param name="worldName">The world name (e.g., "my-world.dcl.eth")</param>
/// <param name="ct">Cancellation token</param>
/// <returns>Access check result with context</returns>
UniTask<WorldAccessCheckContext> CheckWorldAccessAsync(string worldName, CancellationToken ct);
/// <summary>
/// Fetches the raw permissions data for a world.
/// </summary>
/// <param name="worldName">The world name</param>
/// <param name="ct">Cancellation token</param>
/// <returns>Parsed world access info</returns>
UniTask<WorldAccessInfo> GetWorldPermissionsAsync(string worldName, CancellationToken ct);
/// <summary>
/// Validates a password for a world. Returns success and optional error message from the backend (e.g. max attempts exceeded).
/// </summary>
UniTask<ValidatePasswordResult> ValidatePasswordAsync(string worldName, string password, CancellationToken ct);
}
/// <summary>
/// Result of password validation. Backend may return an error message (e.g. max attempts exceeded).
/// </summary>
public readonly struct ValidatePasswordResult
{
public bool Success { get; }
public string? ErrorMessage { get; }
public ValidatePasswordResult(bool success, string? errorMessage = null)
{
Success = success;
ErrorMessage = errorMessage;
}
public static ValidatePasswordResult Ok => new (true);
public static ValidatePasswordResult Fail(string? errorMessage) => new (false, errorMessage);
}
/// <summary>
/// Service for fetching and checking world access permissions.
/// </summary>
public class WorldPermissionsService : IWorldPermissionsService
{
private const int VALIDATE_PASSWORD_TIMEOUT_SECONDS = 30;
private readonly IWebRequestController webRequestController;
private readonly IDecentralandUrlsSource urlsSource;
private readonly IWeb3IdentityCache web3IdentityCache;
private readonly ICommunityMembershipChecker communityMembershipChecker;
public WorldPermissionsService(
IWebRequestController webRequestController,
IDecentralandUrlsSource urlsSource,
IWeb3IdentityCache web3IdentityCache,
ICommunityMembershipChecker communityMembershipChecker)
{
this.webRequestController = webRequestController;
this.urlsSource = urlsSource;
this.web3IdentityCache = web3IdentityCache;
this.communityMembershipChecker = communityMembershipChecker;
}
public async UniTask<WorldAccessCheckContext> CheckWorldAccessAsync(string worldName, CancellationToken ct)
{
var context = new WorldAccessCheckContext();
try
{
WorldAccessInfo accessInfo = await GetWorldPermissionsAsync(worldName, ct);
context.AccessInfo = accessInfo;
switch (accessInfo.AccessType)
{
case WorldAccessType.Unknown:
ReportHub.LogWarning(ReportCategory.REALM,
$"Unsupported world access type received for '{worldName}'. Failing access check safely.");
context.Result = WorldAccessCheckResult.CheckFailed;
context.ErrorMessage = "Unsupported world access type";
break;
case WorldAccessType.Unrestricted:
context.Result = WorldAccessCheckResult.Allowed;
break;
case WorldAccessType.SharedSecret:
string? currentWallet = web3IdentityCache.Identity?.Address;
if (!string.IsNullOrEmpty(currentWallet) &&
currentWallet.Equals(accessInfo.OwnerAddress, StringComparison.OrdinalIgnoreCase))
{
context.Result = WorldAccessCheckResult.Allowed;
}
else
{
context.Result = WorldAccessCheckResult.PasswordRequired;
}
break;
case WorldAccessType.AllowList:
bool hasAccess = await CheckAllowListAccessAsync(accessInfo, ct);
context.Result = hasAccess ? WorldAccessCheckResult.Allowed : WorldAccessCheckResult.AccessDenied;
break;
default:
ReportHub.LogWarning(ReportCategory.REALM,
$"Unhandled WorldAccessType '{accessInfo.AccessType}' for '{worldName}'. Failing access check safely.");
context.Result = WorldAccessCheckResult.CheckFailed;
context.ErrorMessage = "Unhandled world access type";
break;
}
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
ReportHub.LogWarning(ReportCategory.REALM, $"Failed to check world permissions for '{worldName}': {e.Message}");
context.Result = WorldAccessCheckResult.CheckFailed;
context.ErrorMessage = e.Message;
}
return context;
}
public async UniTask<WorldAccessInfo> GetWorldPermissionsAsync(string worldName, CancellationToken ct)
{
try
{
string baseUrl = urlsSource.Url(DecentralandUrl.WorldPermissions);
string url = string.Format(baseUrl, worldName);
// NOTE: address allocations from serialization (either increasing check
// NOTE: or doing something else
var response = await webRequestController
.GetAsync(new CommonArguments(URLAddress.FromString(url)), ct, ReportCategory.REALM)
.CreateFromJson<WorldPermissionsResponse>(WRJsonParser.Newtonsoft);
return WorldAccessInfo.FromResponse(response);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
ReportHub.LogWarning(ReportCategory.REALM, $"Failed to fetch world permissions for '{worldName}': {e.Message}");
throw;
}
}
public async UniTask<ValidatePasswordResult> ValidatePasswordAsync(string worldName, string password, CancellationToken ct)
{
try
{
string baseUrl = urlsSource.Url(DecentralandUrl.WorldComms);
string url = string.Format(baseUrl, worldName);
string metadata = BuildValidatePasswordMetadataJson(password);
var commonArguments = new CommonArguments(
URLAddress.FromString(url),
RetryPolicy.NONE,
timeout: VALIDATE_PASSWORD_TIMEOUT_SECONDS);
long statusCode = await webRequestController
.SignedFetchPostAsync(commonArguments, metadata, ct)
.StatusCodeAsync();
ReportHub.Log(ReportCategory.REALM, $"[WorldPermissionsService] ValidatePassword for '{worldName}': status {statusCode}");
return statusCode >= 200 && statusCode < 300 ? ValidatePasswordResult.Ok : ValidatePasswordResult.Fail(null);
}
catch (UnityWebRequestException e)
{
ReportHub.Log(ReportCategory.REALM,
$"[WorldPermissionsService] ValidatePassword for '{worldName}': status {e.ResponseCode}, response: {e.Text}");
string? backendError = GetBackendErrorMessage(e);
return ValidatePasswordResult.Fail(backendError);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
ReportHub.LogWarning(ReportCategory.REALM, $"[WorldPermissionsService] ValidatePassword for '{worldName}' failed: {e.Message}");
return ValidatePasswordResult.Fail(e.Message);
}
}
/// <summary>
/// Extracts a user-facing error message from the backend response.
/// - 403 (wrong password): return null so caller shows "Incorrect password. Please try again."
/// - 429 (too many attempts): show backend "error" message or fallback "Too many attempts. Try again later."
/// - Other: show backend JSON "error" field, raw body, or exception message.
/// </summary>
private static string? GetBackendErrorMessage(UnityWebRequestException e)
{
if (e.ResponseCode == 403)
return null; // caller shows standard "Incorrect password" message
if (!string.IsNullOrWhiteSpace(e.Text))
{
string trimmed = e.Text.Trim();
try
{
var parsed = JsonConvert.DeserializeObject<BackendErrorResponse>(trimmed);
if (!string.IsNullOrWhiteSpace(parsed?.Error))
return parsed.Error;
}
catch { /* not JSON or missing field, fall through */ }
return trimmed;
}
return e.Message;
}
[Serializable]
private class BackendErrorResponse
{
[JsonProperty("error")]
public string? Error { get; set; }
}
private static string BuildValidatePasswordMetadataJson(string password) =>
CommsHandshakeMetadata.BuildWorldJson(password);
private async UniTask<bool> CheckAllowListAccessAsync(WorldAccessInfo accessInfo, CancellationToken ct)
{
// Check if current user's wallet is in the allow list
string? currentWallet = web3IdentityCache.Identity?.Address;
if (!string.IsNullOrEmpty(currentWallet))
{
if (accessInfo.IsWalletAllowed(currentWallet))
return true;
// Owner always has access
if (currentWallet.Equals(accessInfo.OwnerAddress, StringComparison.OrdinalIgnoreCase))
return true;
}
if (accessInfo.AllowedCommunities.Count > 0)
{
var membershipChecks = new UniTask<bool>[accessInfo.AllowedCommunities.Count];
for (int i = 0; i < accessInfo.AllowedCommunities.Count; i++)
{
string communityId = accessInfo.AllowedCommunities[i];
membershipChecks[i] = IsCommunityMembershipAllowedAsync(communityId, ct);
}
bool[] membershipResults = await UniTask.WhenAll(membershipChecks);
foreach (bool isMember in membershipResults)
{
if (isMember)
return true;
}
}
return false;
async UniTask<bool> IsCommunityMembershipAllowedAsync(string communityId, CancellationToken token)
{
try
{
return await communityMembershipChecker.IsMemberOfCommunityAsync(communityId, token);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
ReportHub.LogWarning(ReportCategory.REALM,
$"Failed to check community membership for '{communityId}': {e.Message}");
return false;
}
}
}
}
}