refresh the token
This commit is contained in:
parent
311d55dcc6
commit
256fd5738c
15 changed files with 458 additions and 10 deletions
|
|
@ -36,6 +36,18 @@ public sealed class AndroidChatServiceTestActivity : Activity
|
|||
ui.GetRequiredService<YavscApiClient>().Settings), "settings differ");
|
||||
Require(ReferenceEquals(Platform.BackgroundChatService, AndroidBackgroundChatService.Instance),
|
||||
"native adapter missing");
|
||||
using (var battery = AndroidBatteryOptimization.CreateIntent(this))
|
||||
{
|
||||
var power = (PowerManager)GetSystemService(PowerService)!;
|
||||
var exempt = power.IsIgnoringBatteryOptimizations(PackageName!);
|
||||
Require(exempt ? battery is null
|
||||
: battery?.Action == global::Android.Provider.Settings.ActionRequestIgnoreBatteryOptimizations,
|
||||
"battery exemption must not prompt when already granted");
|
||||
Require(battery?.DataString == (exempt ? null : "package:" + PackageName),
|
||||
"battery settings package mismatch");
|
||||
Require(CheckSelfPermission("android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS")
|
||||
== Permission.Granted, "battery exemption request permission missing");
|
||||
}
|
||||
if (OperatingSystem.IsAndroidVersionAtLeast(29))
|
||||
{
|
||||
var name = new ComponentName(this, Java.Lang.Class.FromType(typeof(ChatConnectionService)));
|
||||
|
|
|
|||
|
|
@ -20,6 +20,58 @@ namespace PostIt.Tests;
|
|||
|
||||
public sealed class MessagingSessionTests
|
||||
{
|
||||
[Fact]
|
||||
public void Only_explicit_settings_application_raises_Applied_after_successful_save()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"postit-apply-{Guid.NewGuid():N}.json");
|
||||
try
|
||||
{
|
||||
var settings = new Settings(path);
|
||||
var saves = 0;
|
||||
var applications = 0;
|
||||
settings.Saved += (_, _) => saves++;
|
||||
settings.Applied += (_, _) =>
|
||||
{
|
||||
Assert.False(settings.IsDirty);
|
||||
Assert.True(File.Exists(path));
|
||||
applications++;
|
||||
};
|
||||
settings.AndroidKeepChatConnected = true;
|
||||
settings.Save();
|
||||
Assert.Equal(0, applications);
|
||||
settings.DarkMode = true;
|
||||
Assert.True(settings.ApplyCommand.CanExecute(null));
|
||||
settings.ApplyCommand.Execute(null);
|
||||
Assert.Equal(1, applications);
|
||||
Assert.Equal(2, saves);
|
||||
Assert.False(settings.ApplyCommand.CanExecute(null));
|
||||
settings.AndroidKeepChatConnected = false;
|
||||
Assert.True(settings.ApplyCommand.CanExecute(null));
|
||||
settings.Apply();
|
||||
Assert.Equal(2, applications);
|
||||
}
|
||||
finally { File.Delete(path); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Failed_settings_save_does_not_raise_Applied()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), $"postit-apply-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
var settings = new Settings(directory);
|
||||
var applied = false;
|
||||
settings.Applied += (_, _) => applied = true;
|
||||
settings.AndroidKeepChatConnected = true;
|
||||
var failure = Record.Exception(() => settings.Apply());
|
||||
Assert.True(failure is IOException or UnauthorizedAccessException);
|
||||
Assert.False(applied);
|
||||
Assert.True(settings.IsDirty);
|
||||
}
|
||||
finally { Directory.Delete(directory); }
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
[Fact]
|
||||
public async Task Native_start_generations_reject_stale_requests_after_stop_and_timeout()
|
||||
|
|
@ -42,6 +94,9 @@ public sealed class MessagingSessionTests
|
|||
Assert.Contains("sans notification permanente", explanation);
|
||||
Assert.Contains("ne garantissent pas", explanation);
|
||||
Assert.False(checkbox.IsChecked);
|
||||
var save = Assert.Single(window.GetVisualDescendants().OfType<Button>(),
|
||||
button => Equals(button.Content, "Sauver"));
|
||||
Assert.Same(settings.ApplyCommand, save.Command);
|
||||
checkbox.IsChecked = true;
|
||||
Assert.True(settings.AndroidKeepChatConnected);
|
||||
Assert.True(settings.IsDirty);
|
||||
|
|
|
|||
|
|
@ -17,6 +17,159 @@ namespace PostIt.Tests;
|
|||
/// </summary>
|
||||
public class YavscApiClientTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(600, true, false, 540)]
|
||||
[InlineData(3600, false, true, 3540)]
|
||||
[InlineData(40, true, false, 0)]
|
||||
[InlineData(-5, true, false, 0)]
|
||||
[InlineData(600, false, false, -1)]
|
||||
public async Task Maintenance_delay_is_derived_from_the_persisted_access_token_expiry(
|
||||
int lifetimeSeconds, bool active, bool keepConnected, int expectedDelaySeconds)
|
||||
{
|
||||
var path = TokensPath();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
try
|
||||
{
|
||||
var store = new TokenStore(path);
|
||||
store.Save(new RefreshTokenRecord("access", "refresh", now.AddSeconds(lifetimeSeconds)));
|
||||
var settings = new Settings();
|
||||
await using var client = new YavscApiClient(settings, store);
|
||||
settings.AndroidKeepChatConnected = keepConnected;
|
||||
Assert.Equal(expectedDelaySeconds < 0 ? Timeout.InfiniteTimeSpan
|
||||
: TimeSpan.FromSeconds(expectedDelaySeconds), client.GetSessionRefreshDelay(now, active));
|
||||
}
|
||||
finally { File.Delete(path); }
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false, 40, 1)]
|
||||
[InlineData(false, true, 40, 1)]
|
||||
[InlineData(false, false, 40, 0)]
|
||||
[InlineData(true, true, 180, 0)]
|
||||
public async Task Session_maintenance_refreshes_before_expiry_only_while_active_or_opted_in(
|
||||
bool active, bool keepConnected, int secondsUntilExpiry, int expectedRefreshes)
|
||||
{
|
||||
using var authority = await OIDCStubAuthority.StartAsync();
|
||||
using var apiServer = new StubApiServer();
|
||||
await apiServer.StartAsync();
|
||||
var settings = BuildSettings(authority, apiServer.BaseUrl);
|
||||
settings.AndroidKeepChatConnected = keepConnected;
|
||||
var tokensPath = TokensPath();
|
||||
try
|
||||
{
|
||||
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
|
||||
var store = new TokenStore(tokensPath);
|
||||
var previous = store.Load()!;
|
||||
var expiry = DateTimeOffset.UtcNow.AddSeconds(secondsUntilExpiry);
|
||||
store.Save(previous with { AccessTokenExpiresAt = expiry });
|
||||
await using var client = new YavscApiClient(settings, store);
|
||||
await Task.WhenAll(Enumerable.Range(0, 8).Select(_ =>
|
||||
client.RefreshSessionIfNeededAsync(active, TestContext.Current.CancellationToken)));
|
||||
Assert.Equal(expectedRefreshes, authority.RefreshRequestCount);
|
||||
Assert.Equal(0, apiServer.RequestCount);
|
||||
Assert.True(expiry > DateTimeOffset.UtcNow, "Refresh must occur before expiry, not after a 401.");
|
||||
var persisted = store.Load()!;
|
||||
if (expectedRefreshes > 0)
|
||||
{
|
||||
Assert.NotEqual(previous.RefreshToken, persisted.RefreshToken);
|
||||
Assert.True(persisted.AccessTokenExpiresAt > expiry);
|
||||
}
|
||||
else Assert.Equal(previous.RefreshToken, persisted.RefreshToken);
|
||||
}
|
||||
finally { File.Delete(tokensPath); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Scheduled_maintenance_runs_without_an_API_call_and_starts_only_once()
|
||||
{
|
||||
using var authority = await OIDCStubAuthority.StartAsync();
|
||||
using var apiServer = new StubApiServer();
|
||||
await apiServer.StartAsync();
|
||||
var settings = BuildSettings(authority, apiServer.BaseUrl);
|
||||
settings.AndroidKeepChatConnected = true;
|
||||
var tokensPath = TokensPath();
|
||||
try
|
||||
{
|
||||
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
|
||||
var store = new TokenStore(tokensPath);
|
||||
store.Save(store.Load()! with { AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(62) });
|
||||
await using var client = new YavscApiClient(settings, store);
|
||||
var scheduledDelay = client.GetSessionRefreshDelay(DateTimeOffset.UtcNow, true);
|
||||
Assert.InRange(scheduledDelay.TotalSeconds, 1, 2);
|
||||
client.StartSessionMaintenance();
|
||||
client.StartSessionMaintenance();
|
||||
await Task.Delay(250, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(0, authority.RefreshRequestCount);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
while (store.Load()!.AccessTokenExpiresAt - DateTimeOffset.UtcNow < TimeSpan.FromMinutes(2))
|
||||
await Task.Delay(20, timeout.Token);
|
||||
Assert.Equal(1, authority.RefreshRequestCount);
|
||||
Assert.Equal(0, apiServer.RequestCount);
|
||||
Assert.InRange(client.GetSessionRefreshDelay(DateTimeOffset.UtcNow, true).TotalSeconds, 500, 600);
|
||||
}
|
||||
finally { File.Delete(tokensPath); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Session_maintenance_rejects_revoked_tokens_and_does_not_retry_after_logout()
|
||||
{
|
||||
using var authority = await OIDCStubAuthority.StartAsync();
|
||||
using var apiServer = new StubApiServer();
|
||||
await apiServer.StartAsync();
|
||||
var settings = BuildSettings(authority, apiServer.BaseUrl);
|
||||
var tokensPath = TokensPath();
|
||||
try
|
||||
{
|
||||
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
|
||||
var store = new TokenStore(tokensPath);
|
||||
store.Save(store.Load()! with
|
||||
{
|
||||
RefreshToken = "revoked-refresh-token",
|
||||
AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(40)
|
||||
});
|
||||
await using var client = new YavscApiClient(settings, store);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
client.SigningOut += () => client.RefreshSessionIfNeededAsync(true, ct);
|
||||
var error = await Assert.ThrowsAsync<RefreshFailedException>(() =>
|
||||
client.RefreshSessionIfNeededAsync(true, ct));
|
||||
Assert.True(error.IsPermanent);
|
||||
Assert.Null(store.Load());
|
||||
Assert.False(client.HasValidSession);
|
||||
await client.LogoutAsync();
|
||||
await client.RefreshSessionIfNeededAsync(true, ct);
|
||||
Assert.Equal(1, authority.RefreshRequestCount);
|
||||
}
|
||||
finally { File.Delete(tokensPath); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Session_maintenance_does_not_refresh_a_due_token_during_logout()
|
||||
{
|
||||
using var authority = await OIDCStubAuthority.StartAsync();
|
||||
using var apiServer = new StubApiServer();
|
||||
await apiServer.StartAsync();
|
||||
var settings = BuildSettings(authority, apiServer.BaseUrl);
|
||||
var tokensPath = TokensPath();
|
||||
try
|
||||
{
|
||||
await using var original = await LoginAndPersistAsync(settings, authority, tokensPath);
|
||||
var store = new TokenStore(tokensPath);
|
||||
store.Save(store.Load()! with { AccessTokenExpiresAt = DateTimeOffset.UtcNow.AddSeconds(40) });
|
||||
await using var client = new YavscApiClient(settings, store);
|
||||
client.SigningOut += () =>
|
||||
{
|
||||
Assert.True(client.HasValidSession);
|
||||
return client.RefreshSessionIfNeededAsync(true, TestContext.Current.CancellationToken);
|
||||
};
|
||||
await client.LogoutAsync();
|
||||
Assert.Equal(0, authority.RefreshRequestCount);
|
||||
Assert.Null(store.Load());
|
||||
Assert.False(client.HasValidSession);
|
||||
}
|
||||
finally { File.Delete(tokensPath); }
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
|
|
@ -474,7 +627,9 @@ public class YavscApiClientTests
|
|||
.Select(_ => client.TrySilentLoginAsync(null, ct)).ToArray();
|
||||
var calls = Enumerable.Range(0, 8)
|
||||
.Select(_ => client.CallAsync<List<StubApiServer.Post>>(HttpMethod.Get, "posts", ct)).ToArray();
|
||||
await Task.WhenAll(silentLogins.Cast<Task>().Concat(calls));
|
||||
var maintenance = Enumerable.Range(0, 8)
|
||||
.Select(_ => client.RefreshSessionIfNeededAsync(true, ct));
|
||||
await Task.WhenAll(silentLogins.Cast<Task>().Concat(calls).Concat(maintenance));
|
||||
|
||||
Assert.All(silentLogins, login => Assert.True(login.Result));
|
||||
Assert.All(calls, call => Assert.NotEmpty(call.Result));
|
||||
|
|
|
|||
Loading…
Reference in a new issue