diff --git a/Directory.Build.props b/Directory.Build.props
index 8b4c77e..8c87ab3 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -29,7 +29,7 @@
https://github.com/managedcode/Storage
https://github.com/managedcode/Storage
Managed Code - Storage
- 10.1.16
+ 10.1.17
diff --git a/ManagedCode.Storage.Core/Primitives/VerifiedContentSnapshot.cs b/ManagedCode.Storage.Core/Primitives/VerifiedContentSnapshot.cs
index 81a3014..0fe800e 100644
--- a/ManagedCode.Storage.Core/Primitives/VerifiedContentSnapshot.cs
+++ b/ManagedCode.Storage.Core/Primitives/VerifiedContentSnapshot.cs
@@ -10,7 +10,7 @@
namespace ManagedCode.Storage.Core.Primitives;
-/// Creates a bounded local snapshot only when length and SHA-256 match.
+/// Creates bounded exact-length snapshots and computes or verifies their SHA-256.
public static class VerifiedContentSnapshot
{
private const int Sha256HexLength = 64;
@@ -55,6 +55,27 @@ internal static async Task> ReadFromStorageAsync(
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(expectedSha256);
+ var captured = await CaptureExactAsync(source, expectedLength, cancellationToken).ConfigureAwait(false);
+ if (captured is not { } snapshot)
+ {
+ return null;
+ }
+
+ if (string.Equals(snapshot.Sha256, expectedSha256, StringComparison.Ordinal))
+ {
+ return snapshot.Content;
+ }
+
+ await snapshot.Content.DisposeAsync().ConfigureAwait(false);
+ return null;
+ }
+
+ /// Captures exactly the expected byte length and computes the SHA-256 in one pass.
+ /// The caller owns source and must dispose the returned content on success.
+ public static async Task<(Stream Content, string Sha256)?> CaptureExactAsync(
+ Stream source, long expectedLength, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(source);
if (expectedLength < 0)
{
return null;
@@ -63,14 +84,15 @@ internal static async Task> ReadFromStorageAsync(
Stream snapshot = OperatingSystem.IsBrowser() ? new MemoryStream() : CreateFileSnapshot();
try
{
- if (!await CopyExactAsync(source, snapshot, expectedLength, expectedSha256, cancellationToken).ConfigureAwait(false))
+ var sha256 = await CopyExactAsync(source, snapshot, expectedLength, cancellationToken).ConfigureAwait(false);
+ if (sha256 is null)
{
await snapshot.DisposeAsync().ConfigureAwait(false);
return null;
}
snapshot.Position = 0;
- return snapshot;
+ return (snapshot, sha256);
}
catch
{
@@ -96,8 +118,8 @@ private static FileStream CreateFileSnapshot()
return new FileStream(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()), options);
}
- private static async Task CopyExactAsync(Stream source, Stream snapshot, long expectedLength,
- string expectedSha256, CancellationToken cancellationToken)
+ private static async Task CopyExactAsync(Stream source, Stream snapshot, long expectedLength,
+ CancellationToken cancellationToken)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
using var buffer = MemoryPool.Shared.Rent();
@@ -111,12 +133,11 @@ private static async Task CopyExactAsync(Stream source, Stream snapshot, l
var read = await source.ReadAsync(requested, cancellationToken).ConfigureAwait(false);
if (read == 0)
{
- return length == expectedLength &&
- string.Equals(Convert.ToHexStringLower(hash.GetHashAndReset()), expectedSha256, StringComparison.Ordinal);
+ return length == expectedLength ? Convert.ToHexStringLower(hash.GetHashAndReset()) : null;
}
if (read > remaining)
{
- return false;
+ return null;
}
length += read;
diff --git a/README.md b/README.md
index e8d00da..105e36d 100644
--- a/README.md
+++ b/README.md
@@ -181,7 +181,7 @@ Every provider supports `IStorage.ReadVerifiedAsync(fileName, expectedLength, ex
For a Google Workspace document use `IGoogleDriveStorage.ReadDocumentAsync` with its exact Drive file ID. Metadata must confirm the same version and current copy/download rights before and after a text export. Configure the provider's authorized SDK client or create an instance with `GoogleDriveStorage.FromTransport` and an owned `HttpMessageHandler`. No vendor client is required in a consumer that already supplies a scoped transport. [Google Drive export documentation](https://developers.google.com/workspace/drive/api/guides/manage-downloads)
-For a known OneDrive file, `IOneDriveStorage.GetItemRevisionAsync` returns the exact item ID, drive ID and current ETag. `ReadItemRevisionAsync` checks that revision again around the same byte verification. [OneDrive revision reads](docs/Features/provider-onedrive.md)
+For a known OneDrive file, `IOneDriveStorage.GetItemRevisionAsync` returns the exact item ID, drive ID and current ETag. `CaptureItemRevisionAsync` reads that selected revision within a caller-supplied byte limit and returns its SHA-256. `ReadItemRevisionAsync` rechecks the revision and a trusted SHA-256. [OneDrive revision reads](docs/Features/provider-onedrive.md)
### Configuring OneDrive, Google Drive, Dropbox, and CloudKit
diff --git a/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.ItemRevisions.cs b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.ItemRevisions.cs
index 4653fc1..ff042ee 100644
--- a/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.ItemRevisions.cs
+++ b/Storages/ManagedCode.Storage.OneDrive/Clients/GraphOneDriveClient.ItemRevisions.cs
@@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Linq;
+using System.Net;
using System.Threading;
using System.Threading.Tasks;
using ManagedCode.Communication;
@@ -22,33 +23,68 @@ internal async Task> GetItemRevisionAsync(
return revision is null ? MissingItem() : Result.Succeed(revision);
}
+ internal async Task> CaptureItemRevisionAsync(
+ string configuredDriveId, string root, OneDriveItemCapture request, CancellationToken cancellationToken)
+ {
+ var pinned = await ReadPinnedRevisionAsync(configuredDriveId, root, request.DriveId, request.ItemId, request.ExpectedETag,
+ cancellationToken).ConfigureAwait(false);
+ if (pinned.IsFailed)
+ {
+ return Result.Fail(pinned.Problem);
+ }
+
+ if (pinned.Value.Length > request.MaximumBytes)
+ {
+ return Result.Fail("OneDrive item is too large", "The selected revision exceeds the requested byte limit.",
+ HttpStatusCode.RequestEntityTooLarge);
+ }
+
+ return await CaptureContentAsync(pinned.Value, root, null, cancellationToken).ConfigureAwait(false);
+ }
+
internal async Task> ReadItemRevisionAsync(
string configuredDriveId, string root, OneDriveItemRead request, CancellationToken cancellationToken)
{
- var drive = await ResolveDriveIdAsync(configuredDriveId, cancellationToken).ConfigureAwait(false);
- if (!string.Equals(drive, request.DriveId, StringComparison.Ordinal))
+ var pinned = await ReadPinnedRevisionAsync(configuredDriveId, root, request.DriveId, request.ItemId, request.ExpectedETag,
+ cancellationToken).ConfigureAwait(false);
+ if (pinned.IsFailed)
{
- return MissingItem();
+ return Result.Fail(pinned.Problem);
}
- var revision = await ReadRevisionAsync(drive, root, request.ItemId, cancellationToken).ConfigureAwait(false);
- if (revision is null)
+ if (pinned.Value.Length != request.ExpectedLength)
+ {
+ return ChangedRevision();
+ }
+
+ var captured = await CaptureContentAsync(pinned.Value, root, request.ExpectedSha256, cancellationToken).ConfigureAwait(false);
+ return captured.IsFailed ? Result.Fail(captured.Problem) : Result.Succeed(captured.Value.Content);
+ }
+
+ private async Task> ReadPinnedRevisionAsync(
+ string configuredDriveId, string root, string driveId, string itemId, string expectedETag, CancellationToken cancellationToken)
+ {
+ var drive = await ResolveDriveIdAsync(configuredDriveId, cancellationToken).ConfigureAwait(false);
+ if (!string.Equals(drive, driveId, StringComparison.Ordinal))
{
- return MissingItem();
+ return MissingItem();
}
- if (!string.Equals(revision.ETag, request.ExpectedETag, StringComparison.Ordinal) || revision.Length != request.ExpectedLength)
+ var revision = await ReadRevisionAsync(drive, root, itemId, cancellationToken).ConfigureAwait(false);
+ if (revision is null)
{
- return ChangedRevision();
+ return MissingItem();
}
- return await ReadContentAsync(revision, root, request.ExpectedSha256, cancellationToken).ConfigureAwait(false);
+ return string.Equals(revision.ETag, expectedETag, StringComparison.Ordinal)
+ ? Result.Succeed(revision)
+ : ChangedRevision();
}
- private async Task> ReadContentAsync(OneDriveItemRevision expected, string root, string sha256,
- CancellationToken cancellationToken)
+ private async Task> CaptureContentAsync(
+ OneDriveItemRevision expected, string root, string? expectedSha256, CancellationToken cancellationToken)
{
- Stream? snapshot = null;
+ (Stream Content, string Sha256)? snapshot = null;
try
{
var item = _graphServiceClient.Drives[expected.DriveId].Items[expected.ItemId];
@@ -56,38 +92,39 @@ private async Task> ReadContentAsync(OneDriveItemRevision expecte
{
if (remote is null)
{
- return MissingItem();
+ return MissingItem();
}
- snapshot = await VerifiedContentSnapshot.CreateAsync(remote, expected.Length, sha256.ToLowerInvariant(),
- cancellationToken).ConfigureAwait(false);
+ snapshot = await VerifiedContentSnapshot.CaptureExactAsync(remote, expected.Length, cancellationToken).ConfigureAwait(false);
}
- if (snapshot is null)
+ if (snapshot is not { } captured || (expectedSha256 is not null &&
+ !string.Equals(captured.Sha256, expectedSha256, StringComparison.OrdinalIgnoreCase)))
{
- return ChangedRevision();
+ return ChangedRevision();
}
var current = await ReadRevisionAsync(expected.DriveId, root, expected.ItemId, cancellationToken).ConfigureAwait(false);
if (current is null)
{
- return MissingItem();
+ return MissingItem();
}
if (current != expected)
{
- return ChangedRevision();
+ return ChangedRevision();
}
- var result = Result.Succeed(snapshot);
+ cancellationToken.ThrowIfCancellationRequested();
+ var result = Result.Succeed(new OneDriveItemSnapshot(expected, captured.Sha256, captured.Content));
snapshot = null;
return result;
}
finally
{
- if (snapshot is not null)
+ if (snapshot is { } unclaimed)
{
- await snapshot.DisposeAsync().ConfigureAwait(false);
+ await unclaimed.Content.DisposeAsync().ConfigureAwait(false);
}
}
}
@@ -137,6 +174,6 @@ private static bool IsWithinRoot(ItemReference parent, string root)
private static Result MissingItem() => Result.FailNotFound("The OneDrive item is not available.");
- private static Result ChangedRevision() =>
- Result.Fail("OneDrive revision changed", "The OneDrive item differs from the requested revision.", System.Net.HttpStatusCode.Conflict);
+ private static Result ChangedRevision() =>
+ Result.Fail("OneDrive revision changed", "The OneDrive item differs from the requested revision.", HttpStatusCode.Conflict);
}
diff --git a/Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs b/Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs
index ec78c1c..6c72ace 100644
--- a/Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs
+++ b/Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs
@@ -13,6 +13,10 @@ public interface IOneDriveStorage : IStorageReads the current metadata of one file in the configured drive and root.
Task> GetItemRevisionAsync(string itemId, CancellationToken cancellationToken = default);
+ /// Captures the selected revision within a byte limit and computes its SHA-256.
+ /// The caller must dispose the returned snapshot content.
+ Task> CaptureItemRevisionAsync(OneDriveItemCapture request, CancellationToken cancellationToken = default);
+
/// Reads verified bytes of one file using a previously observed drive, item and revision.
/// The returned stream belongs to the caller.
Task> ReadItemRevisionAsync(OneDriveItemRead request, CancellationToken cancellationToken = default);
diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveItemRevision.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveItemRevision.cs
index f898afe..56ec731 100644
--- a/Storages/ManagedCode.Storage.OneDrive/OneDriveItemRevision.cs
+++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveItemRevision.cs
@@ -1,3 +1,5 @@
+using System.IO;
+
namespace ManagedCode.Storage.OneDrive;
/// The current provider metadata for an exact OneDrive file.
@@ -5,3 +7,10 @@ public sealed record OneDriveItemRevision(string DriveId, string ItemId, string
/// Identifies the permitted OneDrive item and the bytes expected from that revision.
public sealed record OneDriveItemRead(string DriveId, string ItemId, string ExpectedETag, long ExpectedLength, string ExpectedSha256);
+
+/// Identifies the permitted OneDrive item, selected revision and maximum capture size in bytes.
+public sealed record OneDriveItemCapture(string DriveId, string ItemId, string ExpectedETag, long MaximumBytes);
+
+/// The selected revision and its captured bytes and lowercase SHA-256.
+/// The caller owns and must dispose .
+public sealed record OneDriveItemSnapshot(OneDriveItemRevision Revision, string Sha256, Stream Content);
diff --git a/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.ItemRevisions.cs b/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.ItemRevisions.cs
index ea608c1..8a0fcce 100644
--- a/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.ItemRevisions.cs
+++ b/Storages/ManagedCode.Storage.OneDrive/OneDriveStorage.ItemRevisions.cs
@@ -26,6 +26,20 @@ public Task> GetItemRevisionAsync(string itemId, Ca
return ReadGraphAsync((client, drive, root) => client.GetItemRevisionAsync(drive, root, itemId, cancellationToken), cancellationToken);
}
+ public Task> CaptureItemRevisionAsync(
+ OneDriveItemCapture request, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+ if (!IsValidNativeIdentifier(request.DriveId) || !IsValidNativeIdentifier(request.ItemId) ||
+ string.IsNullOrWhiteSpace(request.ExpectedETag) || request.MaximumBytes <= 0)
+ {
+ return Task.FromResult(Result.FailBadRequest(
+ "An exact OneDrive drive, item, ETag, and positive maximum byte length are required."));
+ }
+
+ return ReadGraphAsync((client, drive, root) => client.CaptureItemRevisionAsync(drive, root, request, cancellationToken), cancellationToken);
+ }
+
public Task> ReadItemRevisionAsync(OneDriveItemRead request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
diff --git a/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveItemCaptureTests.cs b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveItemCaptureTests.cs
new file mode 100644
index 0000000..a1fea26
--- /dev/null
+++ b/Tests/ManagedCode.Storage.Tests/Storages/CloudDrive/GraphOneDriveItemCaptureTests.cs
@@ -0,0 +1,89 @@
+using System;
+using System.IO;
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading.Tasks;
+using ManagedCode.Storage.OneDrive;
+using Shouldly;
+using Xunit;
+
+namespace ManagedCode.Storage.Tests.Storages.CloudDrive;
+
+public partial class GraphOneDriveClientTests
+{
+ [Fact]
+ public async Task CaptureItemRevisionAsync_CapturesTheSelectedGraphRevisionForSubsequentVerification()
+ {
+ using var provider = new RevisionGraphHandler();
+ using IOneDriveStorage storage = RevisionStorage(provider);
+ var token = TestContext.Current.CancellationToken;
+
+ var metadata = await storage.GetItemRevisionAsync(RevisionItemId, token);
+ metadata.IsSuccess.ShouldBeTrue();
+ provider.ContentRequests.ShouldBe(0);
+ var revision = metadata.Value;
+ var request = new OneDriveItemCapture(revision.DriveId, revision.ItemId, revision.ETag, revision.Length);
+
+ var captured = await storage.CaptureItemRevisionAsync(request, token);
+
+ captured.IsSuccess.ShouldBeTrue();
+ captured.Value.Revision.ShouldBe(revision);
+ captured.Value.Sha256.ShouldBe(Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(RevisionBody))));
+ await using var capturedContent = captured.Value.Content;
+ using var captureReader = new StreamReader(capturedContent, leaveOpen: true);
+ (await captureReader.ReadToEndAsync(token)).ShouldBe(RevisionBody);
+ provider.ContentRequests.ShouldBe(1);
+ provider.MetadataRequests.ShouldBe(3);
+
+ var read = await storage.ReadItemRevisionAsync(
+ new OneDriveItemRead(revision.DriveId, revision.ItemId, revision.ETag, revision.Length, captured.Value.Sha256), token);
+
+ read.IsSuccess.ShouldBeTrue();
+ await using var verifiedContent = read.Value;
+ using var verifiedReader = new StreamReader(verifiedContent, leaveOpen: true);
+ (await verifiedReader.ReadToEndAsync(token)).ShouldBe(RevisionBody);
+ provider.ContentRequests.ShouldBe(2);
+ provider.MetadataRequests.ShouldBe(5);
+ }
+
+ [Theory]
+ [InlineData(RevisionFailure.WrongDrive, HttpStatusCode.NotFound, 0)]
+ [InlineData(RevisionFailure.OutsideRoot, HttpStatusCode.NotFound, 0)]
+ [InlineData(RevisionFailure.WrongItem, HttpStatusCode.NotFound, 0)]
+ [InlineData(RevisionFailure.StaleTag, HttpStatusCode.Conflict, 0)]
+ [InlineData(RevisionFailure.ContentDenied, HttpStatusCode.NotFound, 1)]
+ [InlineData(RevisionFailure.ChangedAfterContent, HttpStatusCode.Conflict, 1)]
+ [InlineData(RevisionFailure.RevokedAfterContent, HttpStatusCode.NotFound, 1)]
+ [InlineData(RevisionFailure.TooManyBytes, HttpStatusCode.Conflict, 1)]
+ public async Task CaptureItemRevisionAsync_DoesNotReturnContentAfterScopeAuthorityOrRevisionFailure(
+ RevisionFailure failure, HttpStatusCode expectedStatus, int contentRequests)
+ {
+ using var provider = new RevisionGraphHandler { Failure = failure };
+ using IOneDriveStorage storage = RevisionStorage(provider);
+ var request = new OneDriveItemCapture(
+ failure == RevisionFailure.WrongDrive ? "other-drive" : RevisionDriveId, RevisionItemId,
+ failure == RevisionFailure.StaleTag ? SecondTag : FirstTag, Encoding.UTF8.GetByteCount(RevisionBody));
+
+ var capture = await storage.CaptureItemRevisionAsync(request, TestContext.Current.CancellationToken);
+
+ capture.IsFailed.ShouldBeTrue();
+ capture.Problem.StatusCode.ShouldBe((int)expectedStatus);
+ provider.ContentRequests.ShouldBe(contentRequests);
+ }
+
+ [Fact]
+ public async Task CaptureItemRevisionAsync_RejectsAnOversizeRevisionBeforeOpeningContent()
+ {
+ using var provider = new RevisionGraphHandler();
+ using IOneDriveStorage storage = RevisionStorage(provider);
+ var request = new OneDriveItemCapture(RevisionDriveId, RevisionItemId, FirstTag, Encoding.UTF8.GetByteCount(RevisionBody) - 1);
+
+ var captured = await storage.CaptureItemRevisionAsync(request, TestContext.Current.CancellationToken);
+
+ captured.IsFailed.ShouldBeTrue();
+ captured.Problem.StatusCode.ShouldBe((int)HttpStatusCode.RequestEntityTooLarge);
+ provider.MetadataRequests.ShouldBe(1);
+ provider.ContentRequests.ShouldBe(0);
+ }
+}
diff --git a/docs/Architecture.md b/docs/Architecture.md
index 65aad72..9a0e695 100644
--- a/docs/Architecture.md
+++ b/docs/Architecture.md
@@ -73,6 +73,10 @@ memory in place, copying only memory without a backing array. Verified writes
accept an optional expected SHA-256 and throw `StorageUploadDigestException`
before commit when the staged content differs.
+OneDrive initial revision capture uses the same bounded content snapshot to compute
+SHA-256 between two checks of the selected Graph item and ETag. The verified read for
+a revision with an independently known digest remains available.
+
## Cartograph artifact provider
`ManagedCode.Storage.Cartograph` is a separate provider for reading catalogued files
diff --git a/docs/Features/provider-onedrive.md b/docs/Features/provider-onedrive.md
index 032ddd6..36a05b2 100644
--- a/docs/Features/provider-onedrive.md
+++ b/docs/Features/provider-onedrive.md
@@ -70,6 +70,14 @@ builder.Services.AddOneDriveStorageAsDefault(options =>
## Read an exact item revision
+Use `CaptureItemRevisionAsync(new OneDriveItemCapture(driveId, itemId, expectedETag, maximumBytes))`
+for the first content read after selecting a revision with `GetItemRevisionAsync`.
+The SDK uses the currently authorized Graph client, checks the configured drive and root, and
+rejects an oversized item before opening its content. It reads exactly the metadata byte length,
+computes a lowercase SHA-256 and confirms the same revision and current access again before
+returning `OneDriveItemSnapshot`. Dispose the returned `Content` stream after use. This
+operation requires live permission to download the bytes as well as read the metadata.
+
Use `IOneDriveStorage.GetItemRevisionAsync(itemId)` with the opaque native ID
of a selected file. The result includes its actual drive ID, item ID, ETag,
name, size, and media type from Microsoft Graph. IDs are verified against the