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
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<RepositoryUrl>https://github.com/managedcode/Storage</RepositoryUrl>
<PackageProjectUrl>https://github.com/managedcode/Storage</PackageProjectUrl>
<Product>Managed Code - Storage</Product>
<Version>10.1.16</Version>
<Version>10.1.17</Version>

</PropertyGroup>

Expand Down
37 changes: 29 additions & 8 deletions ManagedCode.Storage.Core/Primitives/VerifiedContentSnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

namespace ManagedCode.Storage.Core.Primitives;

/// <summary>Creates a bounded local snapshot only when length and SHA-256 match.</summary>
/// <summary>Creates bounded exact-length snapshots and computes or verifies their SHA-256.</summary>
public static class VerifiedContentSnapshot
{
private const int Sha256HexLength = 64;
Expand Down Expand Up @@ -55,6 +55,27 @@ internal static async Task<Result<Stream>> 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;
}

/// <summary>Captures exactly the expected byte length and computes the SHA-256 in one pass.</summary>
/// <remarks>The caller owns source and must dispose the returned content on success.</remarks>
public static async Task<(Stream Content, string Sha256)?> CaptureExactAsync(
Stream source, long expectedLength, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(source);
if (expectedLength < 0)
{
return null;
Expand All @@ -63,14 +84,15 @@ internal static async Task<Result<Stream>> 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
{
Expand All @@ -96,8 +118,8 @@ private static FileStream CreateFileSnapshot()
return new FileStream(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()), options);
}

private static async Task<bool> CopyExactAsync(Stream source, Stream snapshot, long expectedLength,
string expectedSha256, CancellationToken cancellationToken)
private static async Task<string?> CopyExactAsync(Stream source, Stream snapshot, long expectedLength,
CancellationToken cancellationToken)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
using var buffer = MemoryPool<byte>.Shared.Rent();
Expand All @@ -111,12 +133,11 @@ private static async Task<bool> 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;
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -22,72 +23,108 @@ internal async Task<Result<OneDriveItemRevision>> GetItemRevisionAsync(
return revision is null ? MissingItem<OneDriveItemRevision>() : Result<OneDriveItemRevision>.Succeed(revision);
}

internal async Task<Result<OneDriveItemSnapshot>> 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<OneDriveItemSnapshot>.Fail(pinned.Problem);
}

if (pinned.Value.Length > request.MaximumBytes)
{
return Result<OneDriveItemSnapshot>.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<Result<Stream>> 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<Stream>();
return Result<Stream>.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<Stream>();
}

var captured = await CaptureContentAsync(pinned.Value, root, request.ExpectedSha256, cancellationToken).ConfigureAwait(false);
return captured.IsFailed ? Result<Stream>.Fail(captured.Problem) : Result<Stream>.Succeed(captured.Value.Content);
}

private async Task<Result<OneDriveItemRevision>> 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<Stream>();
return MissingItem<OneDriveItemRevision>();
}

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<OneDriveItemRevision>();
}

return await ReadContentAsync(revision, root, request.ExpectedSha256, cancellationToken).ConfigureAwait(false);
return string.Equals(revision.ETag, expectedETag, StringComparison.Ordinal)
? Result<OneDriveItemRevision>.Succeed(revision)
: ChangedRevision<OneDriveItemRevision>();
}

private async Task<Result<Stream>> ReadContentAsync(OneDriveItemRevision expected, string root, string sha256,
CancellationToken cancellationToken)
private async Task<Result<OneDriveItemSnapshot>> 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];
await using (var remote = await item.Content.GetAsync(cancellationToken: cancellationToken).ConfigureAwait(false))
{
if (remote is null)
{
return MissingItem<Stream>();
return MissingItem<OneDriveItemSnapshot>();
}

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<OneDriveItemSnapshot>();
}

var current = await ReadRevisionAsync(expected.DriveId, root, expected.ItemId, cancellationToken).ConfigureAwait(false);
if (current is null)
{
return MissingItem<Stream>();
return MissingItem<OneDriveItemSnapshot>();
}

if (current != expected)
{
return ChangedRevision();
return ChangedRevision<OneDriveItemSnapshot>();
}

var result = Result<Stream>.Succeed(snapshot);
cancellationToken.ThrowIfCancellationRequested();
var result = Result<OneDriveItemSnapshot>.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);
}
}
}
Expand Down Expand Up @@ -137,6 +174,6 @@ private static bool IsWithinRoot(ItemReference parent, string root)

private static Result<T> MissingItem<T>() => Result<T>.FailNotFound("The OneDrive item is not available.");

private static Result<Stream> ChangedRevision() =>
Result<Stream>.Fail("OneDrive revision changed", "The OneDrive item differs from the requested revision.", System.Net.HttpStatusCode.Conflict);
private static Result<T> ChangedRevision<T>() =>
Result<T>.Fail("OneDrive revision changed", "The OneDrive item differs from the requested revision.", HttpStatusCode.Conflict);
}
4 changes: 4 additions & 0 deletions Storages/ManagedCode.Storage.OneDrive/IOneDriveStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ public interface IOneDriveStorage : IStorage<IOneDriveClient, OneDriveStorageOpt
/// <summary>Reads the current metadata of one file in the configured drive and root.</summary>
Task<Result<OneDriveItemRevision>> GetItemRevisionAsync(string itemId, CancellationToken cancellationToken = default);

/// <summary>Captures the selected revision within a byte limit and computes its SHA-256.</summary>
/// <remarks>The caller must dispose the returned snapshot content.</remarks>
Task<Result<OneDriveItemSnapshot>> CaptureItemRevisionAsync(OneDriveItemCapture request, CancellationToken cancellationToken = default);

/// <summary>Reads verified bytes of one file using a previously observed drive, item and revision.</summary>
/// <remarks>The returned stream belongs to the caller.</remarks>
Task<Result<Stream>> ReadItemRevisionAsync(OneDriveItemRead request, CancellationToken cancellationToken = default);
Expand Down
9 changes: 9 additions & 0 deletions Storages/ManagedCode.Storage.OneDrive/OneDriveItemRevision.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
using System.IO;

namespace ManagedCode.Storage.OneDrive;

/// <summary>The current provider metadata for an exact OneDrive file.</summary>
public sealed record OneDriveItemRevision(string DriveId, string ItemId, string ETag, string Name, long Length, string? ContentType);

/// <summary>Identifies the permitted OneDrive item and the bytes expected from that revision.</summary>
public sealed record OneDriveItemRead(string DriveId, string ItemId, string ExpectedETag, long ExpectedLength, string ExpectedSha256);

/// <summary>Identifies the permitted OneDrive item, selected revision and maximum capture size in bytes.</summary>
public sealed record OneDriveItemCapture(string DriveId, string ItemId, string ExpectedETag, long MaximumBytes);

/// <summary>The selected revision and its captured bytes and lowercase SHA-256.</summary>
/// <remarks>The caller owns and must dispose <see cref="Content"/>.</remarks>
public sealed record OneDriveItemSnapshot(OneDriveItemRevision Revision, string Sha256, Stream Content);
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ public Task<Result<OneDriveItemRevision>> GetItemRevisionAsync(string itemId, Ca
return ReadGraphAsync((client, drive, root) => client.GetItemRevisionAsync(drive, root, itemId, cancellationToken), cancellationToken);
}

public Task<Result<OneDriveItemSnapshot>> 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<OneDriveItemSnapshot>.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<Result<Stream>> ReadItemRevisionAsync(OneDriveItemRead request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading
Loading