Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,9 @@ await freedom.EnrolAsync(FreedomProof.ExistingSession(fellowshipDeviceToken));
whose secret flag changed. **Removed keys** are those held but not
listed.
4. **Fetch the stale keys**, up to 100 per request.
- A request that gets no answer or an error **abandons the start**:
nothing is applied, not even earlier batches or removals, and it is
reported exactly as the manifest request would have been.
- Plain values come as they are.
- Secrets are opened with the private key. A secret whose inner key or
version is not the one it arrived under is refused.
Expand Down Expand Up @@ -221,11 +224,22 @@ That is what makes overrides work with no bookkeeping on the device:

### The ETag is saved last

A sync interrupted part-way (a batch that failed, a secret that would not
open, a value that changed again mid-sync) leaves the ETag unsaved. The
next start therefore sees a manifest that differs and repairs it. A store
whose contents still exactly match an older ETag keeps that one, which is
harmless.
A sync interrupted part-way (a secret that would not open, a value that
changed again mid-sync) leaves the ETag unsaved. The next start therefore
sees a manifest that differs and repairs it. A store whose contents still
exactly match an older ETag keeps that one, which is harmless.

**A values request that fails changes nothing at all.** The usual cause is
the app going to the background between the manifest and the values, and
the connection dropping under it. The store is left exactly as its ETag
describes it, and the start reports `Offline` (or `ServerError`, for an
error status), as it would had the manifest request been the one to fail.

Android's `AndroidMessageHandler` reports a dropped connection as a
`WebException` (inner `Java.Net.SocketException`), not the
`HttpRequestException` the managed handler throws. Both, and a bare
`IOException`, are read as no answer. Until 2026-10-04 the `WebException`
was not, and escaped `SyncAsync` on the Register tablet.

## Offline is normal

Expand All @@ -242,6 +256,9 @@ A tablet in a church hall with no signal starts with what it has.
| gets `401` | `Revoked` | cleared |
| gets `403 freedom_not_authorised` / `freedom_tablet_blocked` | `NotAuthorised` | cleared |

A values request, after a manifest that did arrive, is read by the same
table.

Reads retry twice on a network error, a 5xx or a 429, half a second apart.
That is deliberately few: a start that waits half a minute on a server
that is down is worse than one that carries on.
Expand Down
16 changes: 15 additions & 1 deletion TheBleedingDeacons.Freedom.Client/FreedomApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ private async Task<ApiResponse<T>> SendAsync<T>(Func<HttpRequestMessage> build,
{
response = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (e is HttpRequestException || (e is TaskCanceledException && !cancellationToken.IsCancellationRequested))
catch (Exception e) when (IsTransportFailure(e, cancellationToken))
{
_logger.LogWarning("Freedom: {Method} {Path} could not reach the server ({Reason})", request.Method, request.RequestUri?.AbsolutePath, e.GetType().Name);

Expand Down Expand Up @@ -316,6 +316,20 @@ private async Task<ApiResponse<T>> SendAsync<T>(Func<HttpRequestMessage> build,
}
}

/// <summary>
/// Whether an exception from the handler means no answer came back, as
/// opposed to a bug. The managed handler reports a dropped connection as
/// <see cref="HttpRequestException"/>; Android's <c>AndroidMessageHandler</c>
/// reports it as <see cref="WebException"/> (inner
/// <c>Java.Net.SocketException: Software caused connection abort</c>, seen
/// 2026-10-04 when Register was backgrounded mid-sync), and other handlers
/// let a bare <see cref="IOException"/> through. A timeout is a
/// <see cref="TaskCanceledException"/> the caller did not ask for.
/// </summary>
private static bool IsTransportFailure(Exception e, CancellationToken cancellationToken) =>
e is HttpRequestException or WebException or IOException
|| (e is TaskCanceledException && !cancellationToken.IsCancellationRequested);

/// <summary>
/// Whether a 403 is a web server's or firewall's page rather than the
/// plugin's JSON refusal. integrity-sharp's rule: no Content-Type is not
Expand Down
33 changes: 20 additions & 13 deletions TheBleedingDeacons.Freedom.Client/FreedomClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ namespace TheBleedingDeacons.Freedom.Client;
/// is off.</para>
/// <para><b>The ETag is saved last</b>, and only when every stale key was
/// applied, so a sync interrupted part-way is repaired by the next start
/// rather than mistaken for current.</para>
/// rather than mistaken for current. A values request that gets no answer or
/// an error applies nothing at all, and is reported as the manifest request
/// would have been.</para>
/// <para>Calls are serialised: two overlapping syncs, or a sync overlapping a
/// sign-in, run one after the other.</para>
/// </remarks>
Expand Down Expand Up @@ -338,10 +340,14 @@ private async Task<SyncResult> ApplyManifestAsync(Manifest manifest, FreedomSnap

if (!response.Success || response.Data is null)
{
// Keep what the other batches brought; the ETag stays unsaved,
// so the next start asks again.
complete = false;
continue;
// No answer, or an error: abandon the whole sync, including
// what earlier batches brought and the removals. The store is
// left exactly as its ETag describes it, and the next start
// sees a manifest that differs and fetches everything stale
// again. A connection dropping as the app is backgrounded is
// the usual cause, and the start reports Offline, as it would
// had the manifest request been the one to fail.
return await RefusedOrKeptAsync(response, snapshot, cancellationToken).ConfigureAwait(false);
}

if (response.Data.Missing.Count > 0 || response.Data.Unreadable.Count > 0)
Expand Down Expand Up @@ -400,30 +406,31 @@ private async Task<SyncResult> ApplyManifestAsync(Manifest manifest, FreedomSnap
return new SyncResult(status, updatedKeys, removed, [], now, complete ? "Configuration is current." : "Configuration was partly updated; the rest follows at the next start.");
}

private async Task<SyncResult> RefusedOrKeptAsync(ApiResponse<Manifest> manifest, FreedomSnapshot snapshot, CancellationToken cancellationToken)
private async Task<SyncResult> RefusedOrKeptAsync<T>(ApiResponse<T> response, FreedomSnapshot snapshot, CancellationToken cancellationToken)
where T : class
{
var code = manifest.Error?.Code ?? string.Empty;
var code = response.Error?.Code ?? string.Empty;

if (manifest.Unreachable)
if (response.Unreachable)
{
return SyncResult.Nothing(SyncStatus.Offline, snapshot.VerifiedAt, "The server could not be reached; keeping the configuration held.");
}

if (manifest.StatusCode == HttpStatusCode.Unauthorized)
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
await ClearOnRefusalAsync(cancellationToken).ConfigureAwait(false);
return SyncResult.Nothing(SyncStatus.Revoked, snapshot.VerifiedAt, "This device is no longer signed in.");
}

if (manifest.StatusCode == HttpStatusCode.Forbidden && string.Equals(code, "freedom_application_disabled", StringComparison.Ordinal))
if (response.StatusCode == HttpStatusCode.Forbidden && string.Equals(code, "freedom_application_disabled", StringComparison.Ordinal))
{
return SyncResult.Nothing(SyncStatus.Suspended, snapshot.VerifiedAt, manifest.Error?.Message ?? "The application is not currently available.");
return SyncResult.Nothing(SyncStatus.Suspended, snapshot.VerifiedAt, response.Error?.Message ?? "The application is not currently available.");
}

if (manifest.StatusCode == HttpStatusCode.Forbidden && code is "freedom_not_authorised" or "freedom_tablet_blocked")
if (response.StatusCode == HttpStatusCode.Forbidden && code is "freedom_not_authorised" or "freedom_tablet_blocked")
{
await ClearOnRefusalAsync(cancellationToken).ConfigureAwait(false);
return SyncResult.Nothing(SyncStatus.NotAuthorised, snapshot.VerifiedAt, manifest.Error?.Message ?? "This device may no longer use the application.");
return SyncResult.Nothing(SyncStatus.NotAuthorised, snapshot.VerifiedAt, response.Error?.Message ?? "This device may no longer use the application.");
}

// Anything else — a 5xx, a 429, a 403 from a firewall, an answer that
Expand Down
34 changes: 34 additions & 0 deletions TheBleedingDeacons.Freedom.Specs/Features/Offline.feature
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,40 @@ Feature: Starting without the server
And the device holds "smtp.host" as "mail.example.org"
And the device knows how old its configuration is

Rule: A connection lost part-way through a start changes nothing

The manifest arrives, and the connection drops before the values do —
typically because the app was sent to the background. Seen on the
Register tablet on 2026-10-04, where Android reported it in a way the
client did not recognise and the start threw instead.

Scenario: The connection drops while the values are fetched
Given the application has "smtp.host" set to "mail.example.org"
And the application has "legacy.flag" set to "on"
And the device has signed in
And the value of "smtp.host" changes to "smtp.example.org"
And "legacy.flag" is removed from the application
And the connection drops during every values request
When the app starts
Then the start reports Offline
And the device holds "smtp.host" as "mail.example.org"
And the device holds "legacy.flag" as "on"
And the configuration is not marked current at the new manifest

Scenario: The next start finishes the job
Given the application has "smtp.host" set to "mail.example.org"
And the application has "legacy.flag" set to "on"
And the device has signed in
And the value of "smtp.host" changes to "smtp.example.org"
And "legacy.flag" is removed from the application
And the connection drops during every values request
And the app has started
And the server answers values requests normally again
When the app starts
Then the start reports Updated
And the device holds "smtp.host" as "smtp.example.org"
And the device does not hold "legacy.flag"

Rule: A server error is not a refusal

Scenario Outline: The site is unwell
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ Feature: Every start
And the value of "smtp.host" changes to "smtp.example.org"
And the server answers every values request with 500
When the app starts
Then the device holds "smtp.host" as "mail.example.org"
Then the start reports ServerError
And the device holds "smtp.host" as "mail.example.org"
And the configuration is not marked current at the new manifest

Scenario: The next start repairs it
Expand Down
10 changes: 9 additions & 1 deletion TheBleedingDeacons.Freedom.Specs/Steps/ServerSteps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Reqnroll;
using TheBleedingDeacons.Freedom.Client.Crypto;
using TheBleedingDeacons.Freedom.Specs.Support;
using TheBleedingDeacons.Freedom.Tests.Support;

namespace TheBleedingDeacons.Freedom.Specs.Steps;

Expand Down Expand Up @@ -35,7 +36,14 @@ public sealed class ServerSteps(World world)
public void ValuesStatus(int status) => world.Server.ValuesStatus = (HttpStatusCode)status;

[Given(@"^the server answers values requests normally again$")]
public void ValuesNormal() => world.Server.ValuesStatus = null;
public void ValuesNormal()
{
world.Server.ValuesStatus = null;
world.Server.ValuesFailure = null;
}

[Given(@"^the connection drops during every values request$")]
public void ValuesDropped() => world.Server.ValuesFailure = FakeFreedomServer.ConnectionAborted();

[Given(@"^the server will refuse the sign-in in the browser with ""(.+)""$")]
public void BrowserRefusal(string error) => world.Server.BrowserRefusal = error;
Expand Down
46 changes: 46 additions & 0 deletions TheBleedingDeacons.Freedom.Tests/FreedomApiTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,40 @@ public async Task NoNetworkIsUnreachableNotAnException()
Assert.Equal(3, server.Requests.Count);
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task AConnectionDroppedAsAndroidReportsItIsUnreachableNotAnException(bool asAndroid)
{
// AndroidMessageHandler throws WebException, not HttpRequestException,
// when the connection drops — as it does when the app is backgrounded
// mid-request. Seen on the Register tablet 2026-10-04, escaping a sync.
Exception thrown = asAndroid ? FakeFreedomServer.ConnectionAborted() : new IOException("Broken pipe");
var handler = new ThrowingHandler(thrown);
using var api = new FreedomApi(new Uri(FakeFreedomServer.BaseUrl), new HttpClient(handler), retryDelay: TimeSpan.Zero);

var read = await api.GetValuesAsync("t", ["smtp.host"], Ct);
Assert.True(read.Unreachable);
Assert.False(read.Success);
Assert.Equal(3, handler.Calls);

handler.Calls = 0;
var write = await api.ReportKeyFaultAsync("t", Ct);
Assert.True(write.Unreachable);
Assert.Equal(1, handler.Calls);
}

[Fact]
public async Task ACallersOwnCancellationIsNotMistakenForNoNetwork()
{
using var cancelled = new CancellationTokenSource();
await cancelled.CancelAsync();
var handler = new ThrowingHandler(new TaskCanceledException());
using var api = new FreedomApi(new Uri(FakeFreedomServer.BaseUrl), new HttpClient(handler), retryDelay: TimeSpan.Zero);

await Assert.ThrowsAnyAsync<OperationCanceledException>(() => api.GetManifestAsync("t", null, cancelled.Token));
}

[Fact]
public async Task AnErrorComesBackInTheServersWords()
{
Expand Down Expand Up @@ -234,6 +268,18 @@ private static async Task<string> EnrolAsync(FakeFreedomServer server, FreedomAp
return enrolled.Data!.Token;
}

private sealed class ThrowingHandler(Exception exception) : HttpMessageHandler
{
public int Calls { get; set; }

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Calls++;

throw exception;
}
}

private sealed class SequenceHandler(params HttpStatusCode[] statuses) : HttpMessageHandler
{
public int Calls { get; set; }
Expand Down
Loading
Loading