From 7f6923ec94deb07ee00f9a6a896c25add4bc14dd Mon Sep 17 00:00:00 2001 From: Paul Fresquet Date: Fri, 13 Nov 2026 17:47:42 +0100 Subject: [PATCH 1/8] [fix] Enforce relay identity and local filesystem boundaries --- docs/client-security-architecture.md | 6 +- docs/security-boundaries.md | 163 ++++++ .../Actions/Shared/SharedActionsGroup.cs | 13 +- .../Business/Actions/Shared/SharedDataPart.cs | 13 +- .../Downloading/DownloadTarget.cs | 10 +- .../Configurations/ApplicationSettings.cs | 8 +- .../DataSources/LocalSourcePermission.cs | 12 + .../Synchronizations/MultiUploadZip.cs | 6 +- .../DependencyInjection/ServiceRegistrar.cs | 4 +- .../Factories/InventoryBuilderFactory.cs | 3 +- .../Http/ICloudSessionApiClient.cs | 4 +- .../Controls/Communications/IFileUploader.cs | 3 +- .../Controls/Encryptions/ISlicerEncrypter.cs | 4 +- .../Inventories/IDataSourceService.cs | 3 +- .../ILocalSourceAuthorizationService.cs | 15 + .../Models/Inventories/InventoryPart.cs | 4 +- .../Actions/SynchronizationDataSaver.cs | 4 +- .../Applications/EnvironmentService.cs | 4 +- .../Communications/Api/AuthApiClient.cs | 20 +- .../Api/CloudSessionApiClient.cs | 8 +- .../Communications/ConnectionService.cs | 4 +- .../Communications/PublicKeysTruster.cs | 4 +- .../PushReceivers/DataNodePushReceiver.cs | 6 +- .../PushReceivers/DataSourcePushReceiver.cs | 11 +- .../Transfers/Downloading/DownloadManager.cs | 5 +- .../Downloading/DownloadTargetBuilder.cs | 28 +- .../Transfers/Downloading/FileDownloader.cs | 3 +- .../SynchronizationDownloadFinalizer.cs | 59 ++- .../Transfers/Uploading/FileUploader.cs | 6 +- .../Services/Encryptions/MergerDecrypter.cs | 10 +- .../Services/Encryptions/SlicerEncrypter.cs | 6 +- .../Services/Inventories/DataNodeService.cs | 9 +- .../Services/Inventories/DataSourceService.cs | 18 +- .../Services/Inventories/InventoryBuilder.cs | 3 +- .../Inventories/InventoryFileAnalyzer.cs | 11 +- .../Services/Inventories/InventoryLoader.cs | 38 +- .../Services/Inventories/InventorySaver.cs | 6 +- .../Services/Inventories/InventoryService.cs | 7 +- .../LocalSourceAuthorizationService.cs | 141 +++++ .../SessionProfileLocalDataManager.cs | 6 +- .../Profiles/SessionProfileManager.cs | 5 +- .../Sessions/CloudSessionLocalDataManager.cs | 19 +- .../Connecting/AfterJoinSessionService.cs | 9 +- .../Connecting/Joining/JoinSessionService.cs | 6 +- .../Services/Synchronizations/DeltaManager.cs | 20 +- .../Synchronizations/FileDatesSetter.cs | 20 +- .../Synchronizations/LocalPathSafety.cs | 368 +++++++++++++ .../SynchronizationActionHandler.cs | 36 +- .../SynchronizationActionRemoteUploader.cs | 8 +- .../SynchronizationDataReceiver.cs | 12 +- .../SynchronizationService.cs | 9 +- .../SynchronizationStartFactory.cs | 9 +- .../Synchronizations/TemporaryFileManager.cs | 53 +- .../Business/Auth/AuthenticationChallenge.cs | 10 + .../Business/Auth/AuthenticationProtocol.cs | 49 ++ .../Business/Auth/InitialConnectionStatus.cs | 3 +- .../Business/Auth/LoginData.cs | 9 +- .../Profiles/CloudSessionProfileSlot.cs | 3 +- .../SharedFiles/SharedFileDefinition.cs | 4 +- .../Business/Versions/ProtocolVersion.cs | 7 +- .../Middlewares/ErrorHandlingMiddleware.cs | 14 +- .../Helpers/Middlewares/JwtMiddleware.cs | 11 +- src/ByteSync.Functions/Http/AuthFunction.cs | 21 +- .../Http/CloudSessionFunction.cs | 22 +- .../Http/CloudSessionProfileFunction.cs | 3 + .../Http/InventoryFunction.cs | 6 +- src/ByteSync.Functions/Http/LobbyFunction.cs | 3 + .../Http/SessionMemberFunction.cs | 5 +- .../Http/SynchronizationFunction.cs | 3 +- src/ByteSync.Functions/Program.cs | 8 +- .../SignalR/SignalREntryFunction.cs | 11 +- .../Business/Auth/AuthConstants.cs | 4 +- .../Business/Auth/Client.cs | 5 +- .../Business/Auth/RefreshToken.cs | 4 +- .../Business/Sessions/CloudSessionData.cs | 5 +- .../Business/Sessions/SessionMemberData.cs | 10 +- .../AuthenticateCommandHandler.cs | 23 +- .../RefreshTokensCommandHandler.cs | 5 +- .../AskJoinCloudSessionRequest.cs | 5 +- .../AskPasswordExchangeKeyRequest.cs | 5 +- .../BeginJoinSessionCommandHandler.cs | 18 + .../CloudSessions/BeginJoinSessionRequest.cs | 11 + .../FinalizeJoinCloudSessionCommandHandler.cs | 18 +- .../FinalizeJoinCloudSessionRequest.cs | 7 +- ...eCloudSessionPasswordExchangeKeyRequest.cs | 5 +- .../InformPasswordIsWrongRequest.cs | 3 +- .../CloudSessions/QuitSessionRequest.cs | 5 +- .../CloudSessions/ResetSessionRequest.cs | 3 +- .../UpdateSessionSettingsRequest.cs | 5 +- .../ValidateJoinCloudSessionCommandHandler.cs | 2 +- .../ValidateJoinCloudSessionRequest.cs | 11 +- .../AssertDownloadIsFinishedRequest.cs | 3 +- .../AssertFilePartIsDownloadedRequest.cs | 3 +- .../AssertFilePartIsUploadedRequest.cs | 3 +- .../AssertUploadIsFinishedRequest.cs | 3 +- ...wnloadFileStorageLocationCommandHandler.cs | 2 +- .../GetDownloadFileStorageLocationRequest.cs | 3 +- .../GetDownloadFileUrlRequest.cs | 3 +- ...UploadFileStorageLocationCommandHandler.cs | 2 +- .../GetUploadFileStorageLocationRequest.cs | 3 +- .../FileTransfers/GetUploadFileUrlRequest.cs | 3 +- .../Inventories/AddDataNodeCommandHandler.cs | 1 + .../Inventories/AddDataNodeRequest.cs | 3 +- .../AddDataSourceCommandHandler.cs | 3 +- .../Inventories/AddDataSourceRequest.cs | 5 +- .../Inventories/GetDataNodesRequest.cs | 11 +- .../Inventories/GetDataSourcesRequest.cs | 11 +- .../Inventories/RemoveDataNodeRequest.cs | 3 +- .../Inventories/RemoveDataSourceRequest.cs | 5 +- .../Inventories/StartInventoryRequest.cs | 5 +- .../Lobbies/QuitLobbyCommandHandler.cs | 4 +- .../Lobbies/TryJoinLobbyCommandHandler.cs | 9 +- .../GetMembersInstanceIdsRequest.cs | 9 +- .../SessionMembers/GetMembersRequest.cs | 9 +- .../SessionMembers/SetGeneralStatusRequest.cs | 5 +- .../Synchronizations/DateIsCopiedRequest.cs | 3 +- .../DirectoryIsCreatedRequest.cs | 3 +- .../FileOrDirectoryIsDeletedRequest.cs | 3 +- .../LocalCopyIsDoneRequest.cs | 3 +- .../MemberHasFinishedRequest.cs | 3 +- .../RequestSynchronizationAbortRequest.cs | 3 +- .../StartSynchronizationRequest.cs | 3 +- .../SynchronizationErrorsRequest.cs | 3 +- .../GiveMemberPublicKeyCheckDataRequest.cs | 7 +- ...nformProtocolVersionIncompatibleRequest.cs | 5 +- ...ormPublicKeyValidationIsFinishedRequest.cs | 5 +- .../Trusts/RequestTrustPublicKeyRequest.cs | 7 +- .../SendDigitalSignaturesCommandHandler.cs | 8 +- .../Commands/Trusts/SetAuthCheckedRequest.cs | 7 +- .../Commands/Trusts/StartTrustCheckRequest.cs | 7 +- .../Entities/CloudSessionProfileEntity.cs | 2 + src/ByteSync.ServerCommon/Entities/Lobby.cs | 2 + .../Factories/ClientsGroupIdFactory.cs | 8 +- .../Factories/LobbyFactory.cs | 3 +- .../Helpers/JwtHelper.cs | 21 +- .../IAuthenticationChallengeService.cs | 9 + .../Services/ICloudSessionsService.cs | 6 +- .../Services/ITransferAuthorizationService.cs | 9 + .../Factories/ICloudflareR2ClientFactory.cs | 2 +- .../Security/ClientAuthentication.cs | 19 + .../Security/IFileTransferRequest.cs | 8 + .../Security/ISessionRequest.cs | 9 + .../Security/SessionAuthorizationBehavior.cs | 172 +++++++ .../AuthenticationChallengeService.cs | 62 +++ .../Clients/ClientsGroupsHubService.cs | 36 +- .../Services/Clients/ClientsService.cs | 5 +- .../Services/Clients/InvokeClientsService.cs | 4 +- .../Services/CloudSessionProfileService.cs | 25 +- .../Services/CloudSessionsService.cs | 24 +- .../Services/LobbyService.cs | 11 +- .../Services/SharedFilesService.cs | 19 +- .../Storage/AzureBlobStorageService.cs | 17 +- .../Services/Storage/CloudflareR2Service.cs | 7 +- .../Factories/CloudflareR2ClientFactory.cs | 2 +- .../Services/TokensFactory.cs | 9 +- .../Services/TransferAuthorizationService.cs | 76 +++ .../Services/TransferLocationService.cs | 14 +- .../Applications/EnvironmentService_Tests.cs | 2 +- .../FullInventoryRunner_IntegrationTests.cs | 2 +- ...yBuilderAccessHandling_IntegrationTests.cs | 16 +- .../Inventories/TestInventoryBuilder.cs | 2 +- .../TestSynchronizationActionHandler.cs | 73 ++- .../TestHelpers/ComparisonResultPreparer.cs | 4 +- .../TestHelpers/SharedDataPartTestFactory.cs | 10 +- .../DataNodePushReceiverTests.cs | 4 +- .../DataSourcePushReceiverTests.cs | 2 +- .../Downloading/DownloadTargetBuilderTests.cs | 2 +- .../SynchronizationDownloadFinalizerTests.cs | 5 + .../Comparisons/IdentityBuilderTests.cs | 4 +- .../Inventories/DataNodeServiceTests.cs | 2 +- .../Inventories/DataSourceServiceTests.cs | 2 +- .../LocalSourceAuthorizationSecurityTests.cs | 486 ++++++++++++++++++ .../Sessions/SynchronizationServiceTests.cs | 18 +- .../Business/Versions/ProtocolVersionTests.cs | 10 +- .../Http/CloudSessionFunctionTests.cs | 2 +- .../Http/CloudSessionProfileFunctionTests.cs | 6 +- .../Http/InventoryFunctionTests.cs | 4 +- .../Business/SessionMemberDataTests.cs | 4 +- .../AuthenticateCommandHandlerTests.cs | 11 +- .../RefreshTokensCommandHandlerTests.cs | 7 +- ...lizeJoinCloudSessionCommandHandlerTests.cs | 3 + ...endDigitalSignaturesCommandHandlerTests.cs | 9 +- .../AuthenticationEpochSecurityTests.cs | 91 ++++ .../Security/AuthenticationSecurityTests.cs | 141 +++++ .../Security/JoinProofSecurityTests.cs | 81 +++ .../LoginIdentityBindingSecurityTests.cs | 53 ++ .../ProfileAuthorizationSecurityTests.cs | 81 +++ .../SessionAuthorizationSecurityTests.cs | 218 ++++++++ .../SignalRAuthorizationSecurityTests.cs | 72 +++ .../Security/StorageUrlScopeSecurityTests.cs | 59 +++ .../TransferAuthorizationSecurityTests.cs | 166 ++++++ .../Services/SharedFilesServiceTests.cs | 8 +- 192 files changed, 3590 insertions(+), 440 deletions(-) create mode 100644 docs/security-boundaries.md create mode 100644 src/ByteSync.Client/Business/DataSources/LocalSourcePermission.cs create mode 100644 src/ByteSync.Client/Interfaces/Controls/Inventories/ILocalSourceAuthorizationService.cs create mode 100644 src/ByteSync.Client/Services/Inventories/LocalSourceAuthorizationService.cs create mode 100644 src/ByteSync.Client/Services/Synchronizations/LocalPathSafety.cs create mode 100644 src/ByteSync.Common/Business/Auth/AuthenticationChallenge.cs create mode 100644 src/ByteSync.Common/Business/Auth/AuthenticationProtocol.cs create mode 100644 src/ByteSync.ServerCommon/Commands/CloudSessions/BeginJoinSessionCommandHandler.cs create mode 100644 src/ByteSync.ServerCommon/Commands/CloudSessions/BeginJoinSessionRequest.cs create mode 100644 src/ByteSync.ServerCommon/Interfaces/Services/IAuthenticationChallengeService.cs create mode 100644 src/ByteSync.ServerCommon/Interfaces/Services/ITransferAuthorizationService.cs create mode 100644 src/ByteSync.ServerCommon/Security/ClientAuthentication.cs create mode 100644 src/ByteSync.ServerCommon/Security/IFileTransferRequest.cs create mode 100644 src/ByteSync.ServerCommon/Security/ISessionRequest.cs create mode 100644 src/ByteSync.ServerCommon/Security/SessionAuthorizationBehavior.cs create mode 100644 src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs create mode 100644 src/ByteSync.ServerCommon/Services/TransferAuthorizationService.cs create mode 100644 tests/ByteSync.Client.UnitTests/Services/Security/LocalSourceAuthorizationSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/AuthenticationEpochSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/JoinProofSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/LoginIdentityBindingSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/ProfileAuthorizationSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/SessionAuthorizationSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/SignalRAuthorizationSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/StorageUrlScopeSecurityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/TransferAuthorizationSecurityTests.cs diff --git a/docs/client-security-architecture.md b/docs/client-security-architecture.md index abb3fb399..aa3931cad 100644 --- a/docs/client-security-architecture.md +++ b/docs/client-security-architecture.md @@ -1,5 +1,7 @@ # ByteSync Client Security Architecture +> Historical overview. For the current relay identity protocol, authorization boundary, local filesystem permissions, migration and validation status, see [Security boundary changes](security-boundaries.md). The short legacy ClientId described below is a display/trust alias and is not an authenticated identity. + **Last Updated:** November 6, 2025 **Analyzed Codebase:** ByteSync.Client (.NET 8.0) @@ -52,14 +54,14 @@ public void InitializeRsa() ### Client Identifier -The `ClientId` is cryptographically derived from the RSA public key: +The legacy display `ClientId` is derived from the RSA public key: ``` ClientId = Base26(SHA256(InstallationId + SHA256(PublicKeyRSA))) Format: XXXX-XXX-XXX (e.g., "ABCD-EFG-HIJ") ``` -This creates a stable, human-readable identifier that is unique to each client's cryptographic identity. +This creates a human-readable alias. Its numeric reduction does not provide a collision-resistant security identity; the current protocol uses the full SHA-256 fingerprint described in the security boundary document. ### Local Key Storage diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md new file mode 100644 index 000000000..3f40cb05d --- /dev/null +++ b/docs/security-boundaries.md @@ -0,0 +1,163 @@ +# Security boundary changes + +Date: 2026-11-13. Local implementation on `fix/security-boundaries`, based on `397a1d1d781ae9eaa979d3cfe48b9ac7256f99d4`. A read-only check of `origin/master` returned the same commit before changes. The checkout was initially clean. The actual solution targets .NET 10; validation used SDK 10.0.204 on Windows. + +This is an implementation and local validation report, not evidence of a deployed fix or of a compromise. No hosted service was tested. Security-word design, AEAD migration and update signing remain separate work. + +## Implemented relay boundary + +### Possession, identity and authentication epoch + +`AuthenticationProtocol` derives the identity from SHA-256 of canonical DER SubjectPublicKeyInfo after fully importing the existing PKCS#1 RSA public key. The full uppercase 64-character fingerprint is the security identity. Keys must be 2048–8192 bits; trailing key data is rejected. Instance identifiers consist of that fingerprint, an underscore and a canonical GUID. Multiple instances can prove possession of the same durable key independently. + +The client retains its existing RSA private key. Login first obtains a random 256-bit server nonce with a two-minute lifetime, then signs a length-prefixed canonical binary message with RSA-PSS/SHA-256. The message binds the domain, authentication epoch, relay audience, protocol version, challenge ID, nonce, expiry, fingerprint, instance, software version and platform. The relay stores the exact binding, consumes the Redis challenge using atomic `GETDEL`, then verifies the signature. Failed verification does not issue tokens or adopt an existing instance. Redis 6.2 or newer, or a compatible service implementing GETDEL, is a deployment prerequisite. + +The current authentication epoch is 1 and protocol is V3. Software version remains a separate compatibility check and cannot substitute for proof of possession. The legacy short `ApplicationSettings.ClientId` remains a display/trust alias; it cannot claim a server identity or an old instance. There is no first-key-wins migration of old aliases. Existing mismatched or legacy instance records are rejected. + +JWTs carry fingerprint and epoch claims. Both JWT validation paths check signature, HS256, issuer, audience, lifetime and the live record/claim association. Refresh records also carry the epoch; an old refresh token cannot mint a verified JWT. No weak login fallback was added. Public challenge/login/refresh endpoints are POST; announcements remain public. The local key and trusted-key lists are not regenerated or silently cleared. + +### Session authorization and joining + +The registered MediatR `SessionAuthorizationBehavior` protects session, inventory, member, synchronization, trust and transfer requests before their handlers run. It checks verified identity, session existence/removal, session epoch/protocol, current membership or an eligible expiring prejoin attempt, allowed state, and operation-specific resource ownership. A reflection test enumerates all session request types and detects missing authorization markers. Profile/lobby operations have their own ownership checks because their authorization context differs from a session. + +Members can still read other members' inventories/sources within their session. Source/node mutations must address the caller's resources, including collision checks inside the repository update. Action acknowledgements must reference the real source/target node. Route/body identifiers are compared for session, member, profile and lobby endpoints. All referenced actions are preflighted before batch handlers run. + +`beginJoin` creates a controlled five-minute prejoin attempt before the legitimate trust exchange and returns only instance IDs. Detailed membership remains restricted to current members. The attempt binds the verified requester, public key and chosen current validator. Repeated password-exchange setup preserves an eligible existing attempt and its trust checks. The validator must equal the authenticated caller. Finalization requires the authenticated joiner, matching validator, session, identity, nonempty unique proof and expiry. Finalization consumes the proof while holding the session Redis lock across transaction commit; notifications follow successful commit. The old short-ID prefix shortcut was removed. Same-key shortcuts require the full verified fingerprint and instance namespace. + +Profile slots identify their original instance in addition to the durable fingerprint, preserving distinct slots for multiple instances of one identity. New profiles and lobbies carry the current epoch. Legacy remote relationships cannot silently become verified relationships. Local profile files are preserved. + +### SignalR + +Negotiation binds the SignalR user to `epoch:instance`; connection callbacks refuse legacy users and unverified records. Client/session/lobby group names include the authentication epoch. Reconnection rechecks saved session/lobby subscriptions against current membership and epoch, rather than trusting persisted group names. Joining/quitting applies group changes to all known distinct connections of the instance. Token-bearing negotiation responses and session credential payloads are no longer logged. + +There are no client-invocable synchronization mutations over SignalR in this serverless design; mutations enter authenticated HTTP/MediatR handlers. SignalR connection callbacks still depend on the deployment's trusted Azure upstream configuration. A live Azure test has not been performed. + +### Storage object authority + +A transfer must match its authorized route/session, verified upload owner, type, action ownership and allowed part range. The relay creates or loads an immutable file record, chooses a random storage object ID, snapshots recipients and provider, and replaces the request's free-form object selection with the stored definition. Synchronization downloads require the recipient to be a target of every action in the transferred archive, as well as a current session member. Other transfer types snapshot the other current members. Downloads require an uploaded registered part. Totals cannot contradict recorded parts. + +Azure/R2 object keys are formed only from the server-generated ID and validated part number. URLs are scoped to one part and one operation: Azure blob write/read SAS or R2 PUT/GET, with five-minute expiry. The record's provider is used even if the default provider configuration later changes. Part bytes may be deleted after acknowledgement, but the authorization record is retained until session cleanup or its existing two-day cache expiry so the final acknowledgement remains authorized. A caller cannot substitute another session's object by changing body path fields. + +Signed URLs remain bearer capabilities until expiry. Membership revocation prevents new URLs; it does not revoke a previously issued URL. Upload owners can overwrite their own part while a write URL is valid. Provider-level immutability, signed content hashes and AEAD are separate decisions. + +## Implemented client filesystem boundary + +### Local permissions and replicated representations + +`LocalSourceAuthorizationService` owns local permissions independently of replicated sources, inventories and profile contents. Local application settings persist exact `(key fingerprint, canonical root, file/directory type)` permissions. A runtime grant additionally binds the current session object, session ID, source ID, real node, local instance and root/type snapshot. A reused short session ID cannot inherit a previous session object's grants. + +Only explicit local source selection creates a new permission. Network sources are checked against the authenticated DTO owner and actual node owner. A network echo of a local source must match an existing grant; it cannot change its root or type. Initial source/node loading after join has the same checks. Profile restoration can attach a new runtime source ID only to an already persisted exact local permission. Therefore unattended profiles remain possible after local enrollment, without prompting on every sync. Old profiles need their sources selected locally once; paths from profile contents do not grant themselves authority. Explicit local removal revokes the permission. + +Inventory parts and action parts now carry `SourceId`; action parts also carry a strict source-relative path. Remote inventory ownership, source identifiers and logical relative paths are validated, and parent inventory references are rebuilt from the authoritative top-level inventory. This prevents a malicious inventory from acquiring local authority when an honest creator computes and forwards the plan. + +### Plan validation and execution + +The complete received/generated plan is checked before installation, organization or execution. Structural validation includes unique safe action IDs, valid operators/types, required timestamps/synchronization mode, complete part bindings and valid relative paths. Local parts are resolved from the local grant, never from a peer's root. Resolver callbacks are excluded from JSON and installed only after every action passes. A file grant accepts only the empty relative path, so it cannot authorize siblings. Directory checks use a separator boundary and the platform's casing rules. + +Execution resolves again and rechecks permission. The boundary covers content reads/fingerprints/uploads, full copy staging and replacement, delta basis/output/replacement, deletes, directory creation, file timestamps, downloaded archives and finalization. Upload slicing and download merging/finalization repeat access checks. Multi-file archives are completely checked for unexpected IDs, duplicate entries and path forms before extraction. + +Internal cache/profile/session components are validated separately; a peer machine name is no longer used to select a cache path. Temporary replacements use random sibling names and exclusive creation. An invalid complete plan performs no synchronization mutation. This is validation atomicity, not a transactional filesystem: a valid batch that later loses permission or encounters I/O failure may have completed earlier authorized actions. + +### Native access and deliberate restrictions + +`LocalPathSafety` combines strict path syntax, reparse/link rejection and native operations. It does not treat two textual checks as a filesystem race solution. + +* Windows traverses directories with no-delete/no-write sharing leases, opens leaves with OPEN_REPARSE_POINT, checks the opened handle and rejects hard-linked files. Replacement pins the source and parent handles and uses handle-relative NT rename within the same parent. Parent directory pinning and a nonempty parent protect that replacement against directory substitution. Real full-copy/delta, junction, hard-link and directory-substitution tests ran on this Windows host. +* Linux/macOS use component-wise openat with O_NOFOLLOW and directory descriptors, fstat of the opened leaf, mkdirat/unlinkat, and relative native rename with exclusive no-overwrite flags when requested. File streams use the opened descriptor. Linux x64/arm64 and macOS x64/arm64 ABI layouts were inspected against platform headers; they have not been executed here. Unsupported Linux architectures fail closed. +* Symlinks, junctions/reparse points and hard-linked file content are refused, including links beneath an authorized directory. UNC/device sources are refused. Backslash, colon, absolute paths, empty/dot/dot-dot components and controls are refused in the portable relative representation. Windows additionally rejects device names, invalid characters and trailing dots/spaces. This excludes some valid Unix filenames and network-drive/link workflows; there is no automatic fallback. +* Directory deletion is nonrecursive. Empty directories can be removed, but a nonempty tree must be represented by individual authorized child operations before its directory is removed. Timestamp operations apply to regular files; unsupported special files fail closed. + +Microsoft documents that a directory must be empty to establish a reparse point: [Reparse points](https://learn.microsoft.com/en-us/windows/win32/fileio/reparse-points). Native declarations were checked against [Apple stat.h](https://github.com/apple-oss-distributions/xnu/blob/main/bsd/sys/stat.h), [Apple stdio.h](https://github.com/apple-oss-distributions/xnu/blob/main/bsd/sys/stdio.h) and [glibc Linux stat layout](https://github.com/bminor/glibc/blob/master/sysdeps/unix/sysv/linux/x86/bits/struct_stat.h). These checks are static evidence, not cross-platform runtime validation. + +## Architecture choices and rejected alternatives + +| Choice | Alternative rejected | Reason | +| --- | --- | --- | +| Durable RSA possession and full canonical fingerprint | Trust a supplied instance/short alias, or JWT validation alone | Validation of a token cannot repair an unproved initial identity. | +| Atomic expiring Redis challenge | Process-local nonce or read-then-delete | Multiple workers must agree on single consumption. | +| Explicit epoch/protocol break | Keep the old login beside the new one | A weak reachable login would retain the vulnerability. | +| Recreate legacy remote relationships | Let the first key claim a legacy alias/profile | There is no authenticated legacy binding to migrate automatically. | +| Local grants plus SourceId resolution | Import permissions from a profile/source echo or sanitize peer roots | Replicated data cannot be the authority for local access. | +| Persist locally enrolled permissions | Ask for confirmation at every sync | Local permissions preserve unattended operation without substituting prompts for enforcement. | +| Native no-follow access and initial link refusal | GetFullPath/StartsWith or repeated path checks alone | Text does not pin the filesystem object accessed. Supporting links safely needs additional design. | + +## Validation + +The final non-incremental build and each test command were run separately. Final commands and result counts are recorded below. TRX and coverage artifacts are retained locally under `artifacts/security-boundaries/`; build/test logs are local ignored files. They contain no intentionally logged tokens, private keys or session secrets. Test keys and sentinels are synthetic. + +| Final suite | Passed | Failed | Not executed (TRX, including OS exclusions) | +| --- | ---: | ---: | ---: | +| server | 364 | 0 | 0 | +| client | 1232 | 0 | 12 | +| functions | 66 | 0 | 0 | +| common | 53 | 0 | 0 | +| local-integration | 40 | 0 | 6 | + +**1755 passed, zero failures; 186 security cases are included in these totals. 18 cases did not execute.** NUnit console totals exclude some OS-filtered cases; the table counts every NotExecuted TRX result. Build: zero errors, 670 warnings (including existing nullable, obsolete API and dependency vulnerability warnings). `git diff --check` passed. + +Reproduction (build and tests are separate commands): + +```powershell +rtk proxy dotnet build ByteSync.sln --no-incremental --no-restore --verbosity quiet +rtk proxy dotnet test tests/ByteSync.ServerCommon.Tests/ByteSync.ServerCommon.Tests.csproj --no-build --no-restore --filter 'FullyQualifiedName!~.Repositories.' --collect 'XPlat Code Coverage' +rtk proxy dotnet test tests/ByteSync.Client.UnitTests/ByteSync.Client.UnitTests.csproj --no-build --no-restore --collect 'XPlat Code Coverage' +rtk proxy dotnet test tests/ByteSync.Functions.UnitTests/ByteSync.Functions.UnitTests.csproj --no-build --no-restore +rtk proxy dotnet test tests/ByteSync.Common.Tests/ByteSync.Common.Tests.csproj --no-build --no-restore +rtk proxy dotnet test tests/ByteSync.Client.IntegrationTests/ByteSync.Client.IntegrationTests.csproj --no-build --no-restore --filter 'FullyQualifiedName~TestSynchronizationActionHandler|FullyQualifiedName~EnvironmentService_Tests|FullyQualifiedName~FullInventoryRunner_IntegrationTests|FullyQualifiedName~InventoryBuilderAccessHandling_IntegrationTests' +``` + +Do not run a coverage collector and another test process against the same output assembly concurrently. Final collection used one process per test output. Superseded trial output is under the separate `history-*` directory; only `final/validation.json` and its referenced reports are authoritative. + +Line coverage of selected boundary source files, merging duplicate/state-machine sequence points within each report (not whole-project or Sonar new-code coverage): + +| Source | Covered / executable lines | Coverage | +| --- | ---: | ---: | +| `AuthenticationProtocol.cs` | 28 / 29 | 96.6% | +| `AuthenticationChallengeService.cs` | 41 / 41 | 100.0% | +| `CloudSessionProfileService.cs` | 79 / 84 | 94.0% | +| `TransferAuthorizationService.cs` | 51 / 59 | 86.4% | +| `ClientAuthentication.cs` | 8 / 8 | 100.0% | +| `SessionAuthorizationBehavior.cs` | 114 / 127 | 89.8% | +| `LocalPathSafety.cs` | 153 / 243 | 63.0% | +| `LocalSourceAuthorizationService.cs` | 104 / 110 | 94.5% | + +The 85% target is **not met for LocalPathSafety** on this Windows host, in particular because native POSIX branches did not execute. No exclusions were added to hide those branches. The PR-wide 80% Sonar gate has **not been demonstrated**. Cross-platform runtime tests and the actual new-code analysis remain release gates. + +Machine-readable evidence: [final validation summary](../artifacts/security-boundaries/final/validation.json). + +Security tests cover real RSA proofs, expiry/replay, concurrent consumption (30 attempts, one winner using an atomic Redis fake), instance binding, old token/refresh rejection, real registered JWT bearer authentication, creation, join proof binding/replay, profile ownership/multiple-instance slots, current SignalR subscriptions, every session request's outsider rejection, transfer ownership/parts/lifecycle and offline Azure SAS scope. Client cases exercise exact file grants, hostile paths and source/node impersonation, forged inventory propagation, XML permission persistence, revocation, complete-plan rejection, links/junctions/hardlinks, real copy/delta and locally enrolled automated restore. Existing local integration tests now explicitly grant their fixture sources through the real registry. + +### Validation not performed + +* No tests against production, staging or hosted ByteSync, Redis, Azure SignalR, Blob Storage or R2. Server repository and Functions integration suites require configured services and were excluded. R2 upload/download and resume integration classes were excluded explicitly. +* Atomic Redis behavior is implemented with GETDEL and tested with a fake; a real supported Redis deployment, RedLock/transaction failure and failover behavior must be exercised in an isolated environment. +* Docker is installed but its engine was unavailable; no ready Linux/macOS runner was available. POSIX native syscall/ABI behavior, filesystem-specific edge cases and packaged applications need runtime tests on each supported OS/architecture. +* Windows ACL-denial integration cases self-skipped because this host did not enforce their synthetic permission changes. POSIX-only tests cannot run on Windows. +* No Sonar PR analysis, production-scale/load/rate-limit evaluation, complete UI/manual trust exchange, or live multi-machine automatic synchronization was run. Local tests do not establish a production security certification. + +## Future rollout proposal (not executed) + +1. Review this patch and approve the breaking protocol, restrictions and enrollment experience. Complete native multi-platform CI, isolated Redis/SignalR/storage end-to-end tests, load/abuse checks and the coverage gate. Confirm the Redis version before rollout. Back up local RSA/settings/trust/profile data through the existing supported process; do not collect private keys centrally. +2. Prepare matched V3 clients and relay together in an isolated environment. Verify manual join, multiple instances, reconnection, profile automation, full/delta transfers and expiration/revocation. Distribute the compatible clients before the cutover window if desired, accepting that they will refuse the old relay protocol until cutover. A separate explicitly selected legacy client can remain outside the new service only under a separately approved risk decision; coexistence does not close the old login flaw. +3. During an announced maintenance window, stop/drain the old relay writers and synchronization jobs. Disable the old login path on every reachable relay instance. Do not run mixed old/new relay workers against a shared authorization namespace. Invalidate old refresh/JWT assurance through the epoch checks; rotate signing secrets as an additional operational measure if approved. Terminate old SignalR connections or provision a fresh hub and switch upstream endpoints; epoch groups isolate new delivery but do not sanitize an old reachable relay. Wait for previously issued legacy SAS/R2 URLs to expire or revoke them operationally before declaring cutover complete. +4. Deploy the matched relay/client V3 pair. Create fresh sessions; epoch-0 sessions cannot continue. Reauthenticate with the existing private key, recreate cloud profile/lobby relationships, and perform the normal peer trust exchange using retained local trusted keys. Do not map a legacy alias to whichever key appears first. Old profile files remain available for manual reconstruction; migration of remote relationships would require a separately designed proof-based process. +5. Enroll each local source through local selection once. Subsequent profile restore must match the stored permission exactly and can run unattended. Explain rejected link/UNC/special-name workflows before enabling automated jobs. Verify fresh full and delta syncs, reconnection and all instances before enabling scheduled work. +6. Observe proof/epoch/authorization failures using identifiers and status codes only. Monitor retry behavior, Redis consumption, transfer metadata retention and grant failures. Never add request-body, JWT, private-key, credential or signed-URL logging for diagnostics. + +Old clients fail the challenge/epoch/protocol boundary; claiming a newer software version does not help. Existing sessions, transfers, remote profiles/lobbies and SignalR subscriptions are not silently promoted. The constants are code-level epoch controls; a later epoch requires a coordinated code release and the same operational invalidation steps. + +### Safe rollback + +Keep the strong authentication/authorization boundary active. Roll back to a previously tested V3 build or disable the affected operation/service while correcting it. Preserve keys, trust lists, settings, local grants and profile files; do not downgrade their meaning or auto-import profile paths. Quarantine or expire failed-epoch server state and issue fresh tokens/sessions after recovery. Do not restore an old vulnerable login, lower the minimum protocol/epoch, remove membership checks, or fall back to raw peer paths. If no compatible build exists, fail closed and keep synchronization unavailable until repaired. A deployment/database rollback to the old relay is not a safe security rollback. + +## Residual risks and decisions for Paul + +Approval is still needed for the coordinated downtime and client/relay release; recreation of existing sessions and remote profiles; the initial local source enrollment UX and user communication; rejecting links, UNC sources, hard links, special names and recursive empty-tree deletion; five-minute URL expiry and retained transfer metadata; and the supported native OS/filesystem/architecture matrix. No such rollout decision was executed here. + +The local settings and durable private key remain trusted local state. Malware running as the user, a privileged local filesystem/mount adversary, or a compromised client can alter that state. Native handle/descriptor access prevents following substituted links, but does not promise rollback of already opened I/O or protection against every concurrent directory relocation/mount change. On Unix a directory pinned by descriptor can itself be renamed by another process; operations then refer to the pinned object. Hard links created after the opened-file check, and arbitrary privileged local renames, require a stronger OS isolation policy if they are included in the threat model. Inventory metadata enumeration still uses existing scanner APIs; content reads are constrained, but concurrent Unix metadata enumeration has not been proven race-free. Local revocation blocks subsequent resolutions and transfer slices, not bytes already read or written. + +Relay authorization checks use current repository state before dispatch; they do not make every handler, notification and concurrent membership change one serializable transaction. Final join-proof consumption is locked/transactional. Already issued URLs and in-flight requests retain their bounded capabilities. Distributed state, failover and departure/reconnect races require isolated integration validation. + +HTTP bodies/archives still need a broader resource-abuse budget/rate-limit review. Peer possession proves control of a key, not that the key owner is honest. A session member may still request destructive actions within sources the local user authorized. The relay cannot inspect encrypted file contents. Cryptographic content integrity/AEAD, security-word entropy and update authenticity remain separate tracked work. Existing dependency vulnerability warnings were observed during build; this patch does not update those packages. + +No push, public PR, publication, deployment, production configuration change or external message was performed. Network use was limited to read-only repository-head/documentation checks; all executed tests used local files, synthetic credentials, fakes or offline signing. diff --git a/src/ByteSync.Client/Business/Actions/Shared/SharedActionsGroup.cs b/src/ByteSync.Client/Business/Actions/Shared/SharedActionsGroup.cs index 6245dee73..f25c7f423 100644 --- a/src/ByteSync.Client/Business/Actions/Shared/SharedActionsGroup.cs +++ b/src/ByteSync.Client/Business/Actions/Shared/SharedActionsGroup.cs @@ -76,17 +76,8 @@ public HashSet GetTargetsFullNames(ByteSyncEndpoint endpoint) public string GetFullName(SharedDataPart sharedDataPart) { - string sourceFileName; - if (sharedDataPart.InventoryPartType == FileSystemTypes.Directory) - { - sourceFileName = IOUtils.Combine(sharedDataPart.RootPath, sharedDataPart.RelativePath!); - } - else - { - sourceFileName = sharedDataPart.RootPath; - } - - return sourceFileName; + return sharedDataPart.LocalPathResolver?.Invoke() + ?? throw new UnauthorizedAccessException("Action has no local source authorization"); } private bool Equals(SharedActionsGroup other) diff --git a/src/ByteSync.Client/Business/Actions/Shared/SharedDataPart.cs b/src/ByteSync.Client/Business/Actions/Shared/SharedDataPart.cs index 4295399be..ba09efba0 100644 --- a/src/ByteSync.Client/Business/Actions/Shared/SharedDataPart.cs +++ b/src/ByteSync.Client/Business/Actions/Shared/SharedDataPart.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Inventories; +using ByteSync.Common.Business.Inventories; using ByteSync.Models.Inventories; namespace ByteSync.Business.Actions.Shared; @@ -20,6 +20,9 @@ public SharedDataPart(string name, Inventory inventory, InventoryPart inventoryP InventoryCodeAndId = inventory.CodeAndId; NodeId = inventory.NodeId; RootPath = inventoryPart.RootPath; + SourceId = inventoryPart.SourceId; + SourceRelativePath = inventoryPart.InventoryPartType == FileSystemTypes.File ? "" : + (relativePath?.StartsWith('/') == true ? relativePath[1..] : relativePath); RelativePath = relativePath; SignatureGuid = signatureGuid; SignatureHash = signatureHash; @@ -37,6 +40,10 @@ public SharedDataPart(string name, Inventory inventory, InventoryPart inventoryP public string? NodeId { get; set; } public string RootPath { get; set; } = null!; + public string? SourceId { get; set; } + public string? SourceRelativePath { get; set; } + [System.Text.Json.Serialization.JsonIgnore] + public Func? LocalPathResolver { get; set; } public string? RelativePath { get; set; } @@ -48,7 +55,9 @@ public SharedDataPart(string name, Inventory inventory, InventoryPart inventoryP protected bool Equals(SharedDataPart other) { - return Equals(ClientInstanceId, other.ClientInstanceId) && + return Equals(SourceId, other.SourceId) && Equals(NodeId, other.NodeId) && + Equals(SourceRelativePath, other.SourceRelativePath) && + Equals(ClientInstanceId, other.ClientInstanceId) && RootPath.Equals(other.RootPath, StringComparison.InvariantCultureIgnoreCase) && Equals (RelativePath, other.RelativePath); } diff --git a/src/ByteSync.Client/Business/Communications/Downloading/DownloadTarget.cs b/src/ByteSync.Client/Business/Communications/Downloading/DownloadTarget.cs index de207bb3e..f4da8c7b1 100644 --- a/src/ByteSync.Client/Business/Communications/Downloading/DownloadTarget.cs +++ b/src/ByteSync.Client/Business/Communications/Downloading/DownloadTarget.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using ByteSync.Common.Business.SharedFiles; using ByteSync.Interfaces.Controls.Synchronizations; @@ -16,6 +16,14 @@ public DownloadTarget(SharedFileDefinition sharedFileDefinition, LocalSharedFile MemoryStreams = new Dictionary(); } + public Action? ValidateAccess { get; set; } + + public void CheckAccess() + { + if (SharedFileDefinition.IsSynchronization && ValidateAccess == null) throw new UnauthorizedAccessException("Missing download authorization"); + ValidateAccess?.Invoke(); + } + public SharedFileDefinition SharedFileDefinition { get; set; } public LocalSharedFile? LocalSharedFile { get; } diff --git a/src/ByteSync.Client/Business/Configurations/ApplicationSettings.cs b/src/ByteSync.Client/Business/Configurations/ApplicationSettings.cs index 6672358f9..c3d950927 100644 --- a/src/ByteSync.Client/Business/Configurations/ApplicationSettings.cs +++ b/src/ByteSync.Client/Business/Configurations/ApplicationSettings.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.ObjectModel; using System.Security.Cryptography; using System.Text.RegularExpressions; @@ -11,6 +11,8 @@ namespace ByteSync.Business.Configurations; public class ApplicationSettings : ICloneable { + public List LocalSourcePermissions { get; set; } = new(); + private string? _rsaPrivateKey; public ApplicationSettings() @@ -229,7 +231,9 @@ public List DecodedAcknowledgedAnnouncementIds public object Clone() { - return this.MemberwiseClone(); + var clone = (ApplicationSettings)MemberwiseClone(); + clone.LocalSourcePermissions = LocalSourcePermissions.Select(p => p with { }).ToList(); + return clone; } public void SetEncryptionPassword(string encryptionPassword) diff --git a/src/ByteSync.Client/Business/DataSources/LocalSourcePermission.cs b/src/ByteSync.Client/Business/DataSources/LocalSourcePermission.cs new file mode 100644 index 000000000..6185339cb --- /dev/null +++ b/src/ByteSync.Client/Business/DataSources/LocalSourcePermission.cs @@ -0,0 +1,12 @@ +using ByteSync.Common.Business.Inventories; + +namespace ByteSync.Business.DataSources; + +public record LocalSourcePermission +{ + public LocalSourcePermission() { } + public LocalSourcePermission(string identity, string path, FileSystemTypes type) { Identity = identity; Path = path; Type = type; } + public string Identity { get; set; } = ""; + public string Path { get; set; } = ""; + public FileSystemTypes Type { get; set; } +} diff --git a/src/ByteSync.Client/Business/Synchronizations/MultiUploadZip.cs b/src/ByteSync.Client/Business/Synchronizations/MultiUploadZip.cs index 09af56f16..665408991 100644 --- a/src/ByteSync.Client/Business/Synchronizations/MultiUploadZip.cs +++ b/src/ByteSync.Client/Business/Synchronizations/MultiUploadZip.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using ByteSync.Common.Business.Misc; using ByteSync.Common.Business.SharedFiles; @@ -28,6 +28,7 @@ public MultiUploadZip(string key, SharedFileDefinition sharedFileDefinition) ActionsGroupIdsConcatenationLength = 0; } + public List AccessValidators { get; } = new(); public string Key { get; } public SharedFileDefinition SharedFileDefinition { get; } @@ -57,7 +58,8 @@ public bool CanAdd(FileInfo fileInfo, string actionsGroupId) public void AddEntry(FileInfo fileInfo, string actionsGroupId) { // https://stackoverflow.com/questions/22339260/how-do-i-add-files-to-an-existing-zip-archive - ZipArchive.CreateEntryFromFile(fileInfo.FullName, actionsGroupId, CompressionLevel.Fastest); + using (var input = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(fileInfo.FullName)) + using (var output = ZipArchive.CreateEntry(actionsGroupId, CompressionLevel.Fastest).Open()) input.CopyTo(output); ActionGroupsIds.Add(actionsGroupId); FilesFullNames.Add(fileInfo.FullName); diff --git a/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs b/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs index d7712b31e..5cb5d8cba 100644 --- a/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs +++ b/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs @@ -1,4 +1,4 @@ -using Autofac; +using Autofac; using Avalonia.ReactiveUI; using ByteSync.Business.Arguments; using ByteSync.DependencyInjection.Modules; @@ -86,7 +86,7 @@ private static void FeedClientId(this IContainer container) var environmentService = scope.Resolve(); var applicationSettings = applicationSettingsRepository.GetCurrentApplicationSettings(); - environmentService.SetClientId(applicationSettings.ClientId); + environmentService.SetClientId(ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(applicationSettings.DecodedRsaPublicKey!)); } private static void LogBootstrapHeader(this IContainer container) diff --git a/src/ByteSync.Client/Factories/InventoryBuilderFactory.cs b/src/ByteSync.Client/Factories/InventoryBuilderFactory.cs index daa517ac8..90d5706e4 100644 --- a/src/ByteSync.Client/Factories/InventoryBuilderFactory.cs +++ b/src/ByteSync.Client/Factories/InventoryBuilderFactory.cs @@ -1,4 +1,4 @@ -using Autofac; +using Autofac; using ByteSync.Business; using ByteSync.Business.DataNodes; using ByteSync.Business.Inventories; @@ -59,6 +59,7 @@ public IInventoryBuilder CreateInventoryBuilder(DataNode dataNode) { try { + _context.Resolve().CheckNetworkSource(dataSource, dataSource.ClientInstanceId); inventoryBuilder.AddInventoryPart(dataSource); } catch (Exception ex) diff --git a/src/ByteSync.Client/Interfaces/Controls/Communications/Http/ICloudSessionApiClient.cs b/src/ByteSync.Client/Interfaces/Controls/Communications/Http/ICloudSessionApiClient.cs index 5e25ac095..403455edc 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Communications/Http/ICloudSessionApiClient.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Communications/Http/ICloudSessionApiClient.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; using System.Threading.Tasks; using ByteSync.Common.Business.Sessions; using ByteSync.Common.Business.Sessions.Cloud; @@ -14,6 +14,8 @@ public interface ICloudSessionApiClient Task ResetCloudSession(string sessionId); + Task> BeginJoin(AskCloudSessionPasswordExchangeKeyParameters parameters, CancellationToken cancellationToken = default); + Task AskPasswordExchangeKey(AskCloudSessionPasswordExchangeKeyParameters parameters, CancellationToken cancellationToken = default); diff --git a/src/ByteSync.Client/Interfaces/Controls/Communications/IFileUploader.cs b/src/ByteSync.Client/Interfaces/Controls/Communications/IFileUploader.cs index 7ee7e4d84..3d36f02bc 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Communications/IFileUploader.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Communications/IFileUploader.cs @@ -1,8 +1,9 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; namespace ByteSync.Interfaces.Controls.Communications; public interface IFileUploader { + Action? ValidateAccess { get; set; } Task Upload(); } \ No newline at end of file diff --git a/src/ByteSync.Client/Interfaces/Controls/Encryptions/ISlicerEncrypter.cs b/src/ByteSync.Client/Interfaces/Controls/Encryptions/ISlicerEncrypter.cs index ece38f935..1a55ffa35 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Encryptions/ISlicerEncrypter.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Encryptions/ISlicerEncrypter.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading.Tasks; using ByteSync.Business.Communications.Transfers; using ByteSync.Common.Business.SharedFiles; @@ -7,6 +7,8 @@ namespace ByteSync.Interfaces.Controls.Encryptions; public interface ISlicerEncrypter : IDisposable { + Action? ValidateAccess { get; set; } + void Initialize(FileInfo fileToEncrypt, SharedFileDefinition sharedFileDefinition); void Initialize(MemoryStream fileToEncrypt, SharedFileDefinition sharedFileDefinition); diff --git a/src/ByteSync.Client/Interfaces/Controls/Inventories/IDataSourceService.cs b/src/ByteSync.Client/Interfaces/Controls/Inventories/IDataSourceService.cs index 08690548a..fd4266cbc 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Inventories/IDataSourceService.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Inventories/IDataSourceService.cs @@ -1,4 +1,4 @@ -using ByteSync.Business.DataNodes; +using ByteSync.Business.DataNodes; using ByteSync.Business.DataSources; using ByteSync.Common.Business.Inventories; @@ -7,6 +7,7 @@ namespace ByteSync.Interfaces.Controls.Inventories; public interface IDataSourceService { Task TryAddDataSource(DataSource dataSource); + Task RestoreDataSource(string path, FileSystemTypes type, DataNode node); Task CreateAndTryAddDataSource(string path, FileSystemTypes fileSystemType, DataNode dataNode); diff --git a/src/ByteSync.Client/Interfaces/Controls/Inventories/ILocalSourceAuthorizationService.cs b/src/ByteSync.Client/Interfaces/Controls/Inventories/ILocalSourceAuthorizationService.cs new file mode 100644 index 000000000..24413bd6d --- /dev/null +++ b/src/ByteSync.Client/Interfaces/Controls/Inventories/ILocalSourceAuthorizationService.cs @@ -0,0 +1,15 @@ +using ByteSync.Business.Actions.Shared; +using ByteSync.Business.DataSources; + +namespace ByteSync.Interfaces.Controls.Inventories; + +public interface ILocalSourceAuthorizationService +{ + void Grant(DataSource source, bool restoreOnly = false); + void Revoke(DataSource source); + void CheckNetworkSource(DataSource source, string sender); + string Resolve(SharedDataPart part); + void ValidatePlan(IEnumerable groups); + void ValidatePath(string path); + void ValidateDestination(SharedActionsGroup group, string destination); +} diff --git a/src/ByteSync.Client/Models/Inventories/InventoryPart.cs b/src/ByteSync.Client/Models/Inventories/InventoryPart.cs index c2ebbe6bd..360082b85 100644 --- a/src/ByteSync.Client/Models/Inventories/InventoryPart.cs +++ b/src/ByteSync.Client/Models/Inventories/InventoryPart.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Inventories; +using ByteSync.Common.Business.Inventories; using ByteSync.Common.Business.Misc; using ByteSync.Models.FileSystems; @@ -23,6 +23,8 @@ public InventoryPart(Inventory inventory, string rootPath, FileSystemTypes inven public Inventory Inventory { get; set; } public string RootPath { get; set; } + + public string? SourceId { get; set; } public FileSystemTypes InventoryPartType { get; set; } diff --git a/src/ByteSync.Client/Services/Actions/SynchronizationDataSaver.cs b/src/ByteSync.Client/Services/Actions/SynchronizationDataSaver.cs index 19d582f01..628c19428 100644 --- a/src/ByteSync.Client/Services/Actions/SynchronizationDataSaver.cs +++ b/src/ByteSync.Client/Services/Actions/SynchronizationDataSaver.cs @@ -14,7 +14,7 @@ public SynchronizationDataSaver() public void Save(string localPath, SharedSynchronizationStartData sharedSynchronizationStartData) { - using ZipArchive zipArchive = ZipFile.Open(localPath, ZipArchiveMode.Create); + using ZipArchive zipArchive = new ZipArchive(ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(localPath), ZipArchiveMode.Create); string json = JsonHelper.Serialize(sharedSynchronizationStartData); @@ -27,7 +27,7 @@ public void Save(string localPath, SharedSynchronizationStartData sharedSynchron public SharedSynchronizationStartData Load(string localPath) { - using ZipArchive zipArchive = ZipFile.OpenRead(localPath); + using ZipArchive zipArchive = new ZipArchive(ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(localPath), ZipArchiveMode.Read); var synchronizationActionsFile = zipArchive.GetEntry("synchronization_start_data.json"); diff --git a/src/ByteSync.Client/Services/Applications/EnvironmentService.cs b/src/ByteSync.Client/Services/Applications/EnvironmentService.cs index 16e1450c8..d455d7823 100644 --- a/src/ByteSync.Client/Services/Applications/EnvironmentService.cs +++ b/src/ByteSync.Client/Services/Applications/EnvironmentService.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.InteropServices; using ByteSync.Business.Arguments; using ByteSync.Business.Misc; @@ -229,6 +229,8 @@ public Version ApplicationVersion public void SetClientId(string clientId) { + if (!ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf($"{clientId}_{Guid.Empty:D}", clientId)) + throw new ArgumentException("A full RSA key fingerprint is required", nameof(clientId)); ClientId = clientId; ClientInstanceId = $"{ClientId}_{Guid.NewGuid():D}"; } diff --git a/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs b/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs index ed2876265..46356eba9 100644 --- a/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs +++ b/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs @@ -1,4 +1,7 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using ByteSync.Interfaces; +using ByteSync.Common.Business.Versions; using System.Threading.Tasks; using ByteSync.Common.Business.Auth; using ByteSync.Interfaces.Controls.Communications.Http; @@ -10,15 +13,28 @@ public class AuthApiClient : IAuthApiClient { private readonly IApiInvoker _apiInvoker; - public AuthApiClient(IApiInvoker apiInvoker) + private readonly IApplicationSettingsRepository _settings; + + public AuthApiClient(IApiInvoker apiInvoker, IApplicationSettingsRepository settings) { _apiInvoker = apiInvoker!; + _settings = settings; } public async Task Login(LoginData loginData) { try { + var settings = _settings.GetCurrentApplicationSettings(); + loginData.PublicKey = settings.DecodedRsaPublicKey!; + loginData.Identity = AuthenticationProtocol.GetIdentity(loginData.PublicKey); + loginData.AuthenticationEpoch = AuthenticationProtocol.Epoch; + loginData.ProtocolVersion = ProtocolVersion.CURRENT; + var challenge = await _apiInvoker.PostAsync("auth/challenge", loginData) + ?? throw new CryptographicException("Missing authentication challenge"); + loginData.ChallengeId = challenge.Id; + loginData.Signature = settings.PrivateRsa.SignData(AuthenticationProtocol.GetMessage(loginData, challenge), + HashAlgorithmName.SHA256, RSASignaturePadding.Pss); var result = await _apiInvoker.PostAsync($"auth/login", loginData); return result; diff --git a/src/ByteSync.Client/Services/Communications/Api/CloudSessionApiClient.cs b/src/ByteSync.Client/Services/Communications/Api/CloudSessionApiClient.cs index 6bee9df69..174afcbf9 100644 --- a/src/ByteSync.Client/Services/Communications/Api/CloudSessionApiClient.cs +++ b/src/ByteSync.Client/Services/Communications/Api/CloudSessionApiClient.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using ByteSync.Common.Business.Sessions; @@ -62,6 +62,12 @@ public async Task ResetCloudSession(string sessionId) } } + public async Task> BeginJoin(AskCloudSessionPasswordExchangeKeyParameters parameters, CancellationToken cancellationToken = default) + { + return await _apiInvoker.PostAsync>($"session/{parameters.SessionId}/beginJoin", parameters, cancellationToken) + ?? throw new UnauthorizedAccessException("Join attempt could not be created"); + } + public async Task AskPasswordExchangeKey(AskCloudSessionPasswordExchangeKeyParameters parameters, CancellationToken cancellationToken = default) { diff --git a/src/ByteSync.Client/Services/Communications/ConnectionService.cs b/src/ByteSync.Client/Services/Communications/ConnectionService.cs index 1979dfc06..7b2a9900f 100644 --- a/src/ByteSync.Client/Services/Communications/ConnectionService.cs +++ b/src/ByteSync.Client/Services/Communications/ConnectionService.cs @@ -73,7 +73,7 @@ public async Task StartConnectionAsync() var retryDelaySleepDurationProvider = RetryDelaySleepDurationProvider; var retryPolicy = Policy - .Handle(ex => !(ex is BuildConnectionException bce && bce.InitialConnectionStatus == InitialConnectionStatus.VersionNotAllowed)) + .Handle(ex => !(ex is BuildConnectionException bce && bce.InitialConnectionStatus is InitialConnectionStatus.VersionNotAllowed or InitialConnectionStatus.InvalidProof)) .WaitAndRetryForeverAsync( retryAttempt => retryDelaySleepDurationProvider?.Invoke(retryAttempt) ?? TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (exception, _, _) => @@ -102,7 +102,7 @@ await retryPolicy.ExecuteAsync(async () => } else { - if (result.AuthenticateResponseStatus == InitialConnectionStatus.VersionNotAllowed) + if (result.AuthenticateResponseStatus is InitialConnectionStatus.VersionNotAllowed or InitialConnectionStatus.InvalidProof) { ConnectionStatusSubject.OnNext(ConnectionStatuses.NotConnected); } diff --git a/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs b/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs index de085ca69..7cba4efc9 100644 --- a/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs +++ b/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs @@ -1,4 +1,4 @@ -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using System.Threading; using ByteSync.Assets.Resources; using ByteSync.Business; @@ -274,7 +274,7 @@ private async Task InitiateAndWaitForTrustCheck(string sessio return JoinSessionResult.BuildFrom(JoinSessionStatus.SessionNotFound); } - memberIdsToCheck.RemoveAll(id => id.StartsWith(_environmentService.ClientId)); + memberIdsToCheck.RemoveAll(id => ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf(id, _environmentService.ClientId)); if (memberIdsToCheck.Count == 0) { return JoinSessionResult.BuildProcessingNormally(); diff --git a/src/ByteSync.Client/Services/Communications/PushReceivers/DataNodePushReceiver.cs b/src/ByteSync.Client/Services/Communications/PushReceivers/DataNodePushReceiver.cs index 2ed1258cf..ea95fd4d1 100644 --- a/src/ByteSync.Client/Services/Communications/PushReceivers/DataNodePushReceiver.cs +++ b/src/ByteSync.Client/Services/Communications/PushReceivers/DataNodePushReceiver.cs @@ -27,7 +27,8 @@ public DataNodePushReceiver(ISessionService sessionService, IDataEncrypter dataE .Subscribe(dto => { var dataNode = _dataEncrypter.DecryptDataNode(dto.EncryptedDataNode); - dataNode.ClientInstanceId = dto.ClientInstanceId; + if (dataNode.ClientInstanceId != dto.ClientInstanceId || dataNode.Id != dto.EncryptedDataNode.Id) + throw new UnauthorizedAccessException("Node owner or id mismatch"); _dataNodeService.ApplyAddDataNodeLocally(dataNode); }); @@ -36,7 +37,8 @@ public DataNodePushReceiver(ISessionService sessionService, IDataEncrypter dataE .Subscribe(dto => { var dataNode = _dataEncrypter.DecryptDataNode(dto.EncryptedDataNode); - dataNode.ClientInstanceId = dto.ClientInstanceId; + if (dataNode.ClientInstanceId != dto.ClientInstanceId || dataNode.Id != dto.EncryptedDataNode.Id) + throw new UnauthorizedAccessException("Node owner or id mismatch"); _dataNodeService.ApplyRemoveDataNodeLocally(dataNode); }); } diff --git a/src/ByteSync.Client/Services/Communications/PushReceivers/DataSourcePushReceiver.cs b/src/ByteSync.Client/Services/Communications/PushReceivers/DataSourcePushReceiver.cs index 01a54932f..28d342afb 100644 --- a/src/ByteSync.Client/Services/Communications/PushReceivers/DataSourcePushReceiver.cs +++ b/src/ByteSync.Client/Services/Communications/PushReceivers/DataSourcePushReceiver.cs @@ -1,4 +1,4 @@ -using System.Reactive.Linq; +using System.Reactive.Linq; using ByteSync.Interfaces.Communications; using ByteSync.Interfaces.Controls.Communications.SignalR; using ByteSync.Interfaces.Controls.Encryptions; @@ -9,14 +9,17 @@ namespace ByteSync.Services.Communications.PushReceivers; public class DataSourcePushReceiver : IPushReceiver { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISessionService _sessionService; private readonly IDataEncrypter _dataEncrypter; private readonly IHubPushHandler2 _hubPushHandler2; private readonly IDataSourceService _dataSourceService; public DataSourcePushReceiver(ISessionService sessionService, IDataEncrypter dataEncrypter, - IHubPushHandler2 hubPushHandler2, IDataSourceService dataSourceService) + IHubPushHandler2 hubPushHandler2, IDataSourceService dataSourceService, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sessionService = sessionService; _dataEncrypter = dataEncrypter; _hubPushHandler2 = hubPushHandler2; @@ -27,6 +30,8 @@ public DataSourcePushReceiver(ISessionService sessionService, IDataEncrypter dat .Subscribe(dto => { var dataSource = _dataEncrypter.DecryptDataSource(dto.EncryptedDataSource); + if (dataSource.Id != dto.EncryptedDataSource.Id) throw new UnauthorizedAccessException("Source id mismatch"); + _authorization.CheckNetworkSource(dataSource, dto.ClientInstanceId); _dataSourceService.ApplyAddDataSourceLocally(dataSource); }); @@ -35,6 +40,8 @@ public DataSourcePushReceiver(ISessionService sessionService, IDataEncrypter dat .Subscribe(dto => { var dataSource = _dataEncrypter.DecryptDataSource(dto.EncryptedDataSource); + if (dataSource.Id != dto.EncryptedDataSource.Id) throw new UnauthorizedAccessException("Source id mismatch"); + _authorization.CheckNetworkSource(dataSource, dto.ClientInstanceId); _dataSourceService.ApplyRemoveDataSourceLocally(dataSource); }); } diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadManager.cs b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadManager.cs index 28a1d8146..7e5c15256 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadManager.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadManager.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.SharedFiles; +using ByteSync.Common.Business.SharedFiles; using ByteSync.Interfaces.Controls.Communications; using ByteSync.Interfaces.Controls.Communications.Http; @@ -59,16 +59,19 @@ public async Task OnFileReadyToFinalize(SharedFileDefinition sharedFileDefinitio await fileDownloader.WaitForFileFullyExtracted(); + downloadTarget.CheckAccess(); if (downloadTarget.TemporaryFileManagers != null) { foreach (var tempFileHelper in downloadTarget.TemporaryFileManagers) { + downloadTarget.CheckAccess(); tempFileHelper.ValidateTemporaryFile(); } } } catch (Exception ex) { + downloadTarget.CheckAccess(); if (downloadTarget.TemporaryFileManagers != null) { foreach (var tempFileHelper in downloadTarget.TemporaryFileManagers) diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadTargetBuilder.cs b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadTargetBuilder.cs index dfa973bfc..9eda39b99 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadTargetBuilder.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/DownloadTargetBuilder.cs @@ -1,4 +1,5 @@ -using System.Reactive.Linq; +using ByteSync.Interfaces.Controls.Inventories; +using System.Reactive.Linq; using ByteSync.Business.Communications; using ByteSync.Business.Communications.Downloading; using ByteSync.Business.Sessions; @@ -16,6 +17,8 @@ namespace ByteSync.Services.Communications.Transfers.Downloading; public class DownloadTargetBuilder : IDownloadTargetBuilder, IDisposable { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ICloudSessionLocalDataManager _cloudSessionLocalDataManager; private readonly ISessionProfileLocalDataManager _sessionProfileLocalDataManager; private readonly ISharedActionsGroupRepository _sharedActionsGroupRepository; @@ -34,8 +37,9 @@ public class DownloadTargetBuilder : IDownloadTargetBuilder, IDisposable public DownloadTargetBuilder(ICloudSessionLocalDataManager cloudSessionLocalDataManager, ISessionProfileLocalDataManager sessionProfileLocalDataManager, ISharedActionsGroupRepository sharedActionsGroupRepository, IConnectionService connectionService, - ITemporaryFileManagerFactory temporaryFileManagerFactory, ISessionService sessionService) + ITemporaryFileManagerFactory temporaryFileManagerFactory, ISessionService sessionService, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _cloudSessionLocalDataManager = cloudSessionLocalDataManager; _sessionProfileLocalDataManager = sessionProfileLocalDataManager; _sharedActionsGroupRepository = sharedActionsGroupRepository; @@ -55,9 +59,13 @@ public DownloadTargetBuilder(ICloudSessionLocalDataManager cloudSessionLocalData public DownloadTarget BuildDownloadTarget(SharedFileDefinition sharedFileDefinition) { + if (sharedFileDefinition.SessionId != _sessionService.SessionId) throw new UnauthorizedAccessException("Transfer session mismatch"); // Check cache first if (_downloadTargetCache.TryGetValue(sharedFileDefinition.Id, out var existing)) + { + existing.CheckAccess(); return existing; + } LocalSharedFile? sharedFile = null; var downloadDestinations = new HashSet(); @@ -158,6 +166,22 @@ public DownloadTarget BuildDownloadTarget(SharedFileDefinition sharedFileDefinit downloadTarget.LastWriteTimeUtcPerActionsGroupId = datesPerActionsGroupId; downloadTarget.TemporaryFileManagers = temporaryFileManagers; + if (sharedFileDefinition.IsSynchronization) + { + downloadTarget.ValidateAccess = () => + { + foreach (var id in sharedFileDefinition.ActionsGroupIds!) + { + var group = _sharedActionsGroupRepository.GetSharedActionsGroup(id) ?? throw new UnauthorizedAccessException(); + if (group.Source?.ClientInstanceId != sharedFileDefinition.ClientInstanceId || + !group.NeedsOperatingOnSourceAndTargets) throw new UnauthorizedAccessException("Transfer source mismatch"); + foreach (var destination in downloadTarget.FinalDestinationsPerActionsGroupId![id]) + _authorization.ValidateDestination(group, destination); + } + foreach (var path in downloadTarget.DownloadDestinations) ByteSync.Services.Synchronizations.LocalPathSafety.AssertNoLinks(path); + }; + downloadTarget.CheckAccess(); + } // Store in cache _downloadTargetCache[sharedFileDefinition.Id] = downloadTarget; diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/FileDownloader.cs b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/FileDownloader.cs index bb3028f75..da3e8a02e 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/FileDownloader.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/FileDownloader.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; using Autofac.Features.Indexed; using ByteSync.Business.Communications.Downloading; @@ -74,6 +74,7 @@ await Task.Run(() => var partToMerge = await _partsCoordinator.MergeChannel.Reader.ReadAsync(); try { + DownloadTarget.CheckAccess(); await _fileMerger.MergeAsync(partToMerge); } finally diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizer.cs b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizer.cs index cdce8e2ed..cbe6cbcc9 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizer.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizer.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using ByteSync.Business.Communications.Downloading; using ByteSync.Common.Business.SharedFiles; @@ -23,9 +23,10 @@ public SynchronizationDownloadFinalizer(IDeltaManager deltaManager, ITemporaryFi _fileDatesSetter = fileDatesSetter; _logger = logger; } - + public async Task FinalizeSynchronization(SharedFileDefinition sharedFileDefinition, DownloadTarget downloadTarget) { + downloadTarget.CheckAccess(); if (downloadTarget.IsMultiFileZip) { await HandleSynchronizationZipMultiFile(sharedFileDefinition, downloadTarget); @@ -35,31 +36,35 @@ public async Task FinalizeSynchronization(SharedFileDefinition sharedFileDefinit await HandleSynchronizationMonoFile(sharedFileDefinition, downloadTarget); } } - + private async Task HandleSynchronizationZipMultiFile(SharedFileDefinition sharedFileDefinition, DownloadTarget downloadTarget) { var downloadDestination = downloadTarget.DownloadDestinations.Single(); - using (var zipArchive = ZipFile.Open(downloadDestination, ZipArchiveMode.Read)) + using (var zipArchive = new ZipArchive(ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(downloadDestination), ZipArchiveMode.Read)) { + if (zipArchive.Entries.Any(e => e.FullName != e.Name || !downloadTarget.FinalDestinationsPerActionsGroupId!.ContainsKey(e.Name)) || + zipArchive.Entries.Select(e => e.Name).Distinct().Count() != zipArchive.Entries.Count) + throw new UnauthorizedAccessException("Unexpected archive entries"); foreach (var entry in zipArchive.Entries) { var finalDestinations = downloadTarget.FinalDestinationsPerActionsGroupId![entry.Name]; var downloadTargetDates = downloadTarget.GetTargetDates(entry.Name); - + if (sharedFileDefinition.IsDeltaSynchronization) { // Synchro delta foreach (var finalDestination in finalDestinations) { - _logger.LogInformation("{SharedFileDefinitionId}: Extracting and applying delta on {FinalDestination}", + downloadTarget.CheckAccess(); + _logger.LogInformation("{SharedFileDefinitionId}: Extracting and applying delta on {FinalDestination}", sharedFileDefinition.Id, finalDestination); - + await using (var stream = entry.Open()) { using (var reader = new MemoryStream()) { await stream.CopyToAsync(reader); - + await _deltaManager.ApplyDelta(finalDestination, reader); } } @@ -71,21 +76,24 @@ private async Task HandleSynchronizationZipMultiFile(SharedFileDefinition shared { foreach (var finalDestination in finalDestinations) { - _logger.LogInformation("{SharedFileDefinitionId}: Extracting to :{FinalDestination}", + downloadTarget.CheckAccess(); + _logger.LogInformation("{SharedFileDefinitionId}: Extracting to :{FinalDestination}", sharedFileDefinition.Id, finalDestination); - + var fileInfo = new FileInfo(finalDestination); if (fileInfo.Directory is { Exists: false }) { - fileInfo.Directory.Create(); + ByteSync.Services.Synchronizations.LocalPathSafety.CreateDirectory(fileInfo.Directory.FullName); } var temporaryFileManager = _temporaryFileManagerFactory.Create(finalDestination); var destinationTemporaryPath = temporaryFileManager.GetDestinationTemporaryPath(); - + try { - entry.ExtractToFile(destinationTemporaryPath); //NOSONAR + using (var input = entry.Open()) + using (var output = ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(destinationTemporaryPath, true)) input.CopyTo(output); + downloadTarget.CheckAccess(); temporaryFileManager.ValidateTemporaryFile(); await _fileDatesSetter.SetDates(sharedFileDefinition, finalDestination, downloadTargetDates); } @@ -98,50 +106,51 @@ private async Task HandleSynchronizationZipMultiFile(SharedFileDefinition shared } } } - + DeleteTemporaryDownloadedFile(downloadDestination); } - + private async Task HandleSynchronizationMonoFile(SharedFileDefinition sharedFileDefinition, DownloadTarget downloadTarget) { var actionsGroupId = sharedFileDefinition.ActionsGroupIds!.Single(); - + var downloadTargetDates = downloadTarget.GetTargetDates(actionsGroupId); if (sharedFileDefinition.IsDeltaSynchronization) { var downloadDestination = downloadTarget.DownloadDestinations.Single(); - + var deltaFullName = downloadDestination; var finalDestinations = downloadTarget.FinalDestinationsPerActionsGroupId![actionsGroupId]; foreach (var finalDestination in finalDestinations) { - _logger.LogInformation("{SharedFileDefinitionId}: Applying delta on {FinalDestination}", + downloadTarget.CheckAccess(); + _logger.LogInformation("{SharedFileDefinitionId}: Applying delta on {FinalDestination}", sharedFileDefinition.Id, finalDestination); - + await _deltaManager.ApplyDelta(finalDestination, deltaFullName); await _fileDatesSetter.SetDates(sharedFileDefinition, finalDestination, downloadTargetDates); } - + DeleteTemporaryDownloadedFile(downloadDestination); } else { var tasks = new List(); - + foreach (var downloadDestination in downloadTarget.AllFinalDestinations) { tasks.Add(_fileDatesSetter.SetDates(sharedFileDefinition, downloadDestination, downloadTargetDates)); } - + await Task.WhenAll(tasks); } } - + private void DeleteTemporaryDownloadedFile(string temporaryDownloadedFile) { _logger.LogInformation("Deleting temporary downloaded file {temporaryDownloadedFile}", temporaryDownloadedFile); - File.Delete(temporaryDownloadedFile); + ByteSync.Services.Synchronizations.LocalPathSafety.Delete(temporaryDownloadedFile); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Services/Communications/Transfers/Uploading/FileUploader.cs b/src/ByteSync.Client/Services/Communications/Transfers/Uploading/FileUploader.cs index 0b6998e42..ec41979c8 100644 --- a/src/ByteSync.Client/Services/Communications/Transfers/Uploading/FileUploader.cs +++ b/src/ByteSync.Client/Services/Communications/Transfers/Uploading/FileUploader.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using ByteSync.Business.Communications.Transfers; using ByteSync.Common.Business.SharedFiles; using ByteSync.Interfaces.Controls.Communications; @@ -37,6 +37,8 @@ public FileUploader( SharedFileDefinition = sharedFileDefinition ?? throw new NullReferenceException("SharedFileDefinition is null"); } + public Action? ValidateAccess { get; set; } + public int? MaxSliceLength { get; set; } private SharedFileDefinition SharedFileDefinition { get; set; } private string? LocalFileToUpload { get; set; } @@ -49,6 +51,8 @@ public FileUploader( public Task Upload() { + ValidateAccess?.Invoke(); + _slicerEncrypter.ValidateAccess = ValidateAccess; if (LocalFileToUpload != null) { return UploadFile(); diff --git a/src/ByteSync.Client/Services/Encryptions/MergerDecrypter.cs b/src/ByteSync.Client/Services/Encryptions/MergerDecrypter.cs index 461c4c1c9..33e8543cc 100644 --- a/src/ByteSync.Client/Services/Encryptions/MergerDecrypter.cs +++ b/src/ByteSync.Client/Services/Encryptions/MergerDecrypter.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; @@ -50,12 +50,13 @@ private void Initialize(string finalFile, DownloadTarget downloadTarget, Cancell CancellationTokenSource = cancellationTokenSource; + DownloadTarget.CheckAccess(); var fileInfo = new FileInfo(FinalFile); if (fileInfo.Directory != null) { - fileInfo.Directory.Create(); + ByteSync.Services.Synchronizations.LocalPathSafety.CreateDirectory(fileInfo.Directory.FullName); } - using (var _ = new FileStream(FinalFile, FileMode.Append)) + using (var _ = ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(FinalFile, append: true)) { // Pour créer au moins un fichier vide } @@ -68,7 +69,8 @@ public async Task MergeAndDecrypt() return; } - await using var outStream = new FileStream(FinalFile, FileMode.Append); + DownloadTarget.CheckAccess(); + await using var outStream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(FinalFile, append: true); var cryptoTransform = Aes.CreateDecryptor(Aes.Key, Aes.IV); await using var cryptoStream = new CryptoStream(outStream, cryptoTransform, CryptoStreamMode.Write); diff --git a/src/ByteSync.Client/Services/Encryptions/SlicerEncrypter.cs b/src/ByteSync.Client/Services/Encryptions/SlicerEncrypter.cs index bb3b10eb2..571be5d4e 100644 --- a/src/ByteSync.Client/Services/Encryptions/SlicerEncrypter.cs +++ b/src/ByteSync.Client/Services/Encryptions/SlicerEncrypter.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Security.Cryptography; using System.Threading; using ByteSync.Business.Communications.Transfers; @@ -13,6 +13,7 @@ public class SlicerEncrypter : ISlicerEncrypter private readonly ICloudSessionConnectionRepository _cloudSessionConnectionRepository; private readonly ILogger _logger; + public Action? ValidateAccess { get; set; } private int _maxSliceLength; public SlicerEncrypter(ICloudSessionConnectionRepository cloudSessionConnectionRepository, @@ -29,7 +30,7 @@ public void Initialize(FileInfo fileToEncrypt, SharedFileDefinition sharedFileDe { SharedFileDefinition = sharedFileDefinition; - InStream = new FileStream(fileToEncrypt.FullName, FileMode.Open, FileAccess.Read); + InStream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(fileToEncrypt.FullName); InReader = new BinaryReader(InStream); EndInitialize(); @@ -85,6 +86,7 @@ public int MaxSliceLength CryptoStream? cryptoStream = null; FileUploaderSlice? fileUploaderSlice = null; + ValidateAccess?.Invoke(); var bytes = InReader.ReadBytes(BufferSize); var readBytes = bytes.Length; var thisSessionReadBytes = readBytes; diff --git a/src/ByteSync.Client/Services/Inventories/DataNodeService.cs b/src/ByteSync.Client/Services/Inventories/DataNodeService.cs index 4d6909271..e40052465 100644 --- a/src/ByteSync.Client/Services/Inventories/DataNodeService.cs +++ b/src/ByteSync.Client/Services/Inventories/DataNodeService.cs @@ -24,6 +24,7 @@ public class DataNodeService : IDataNodeService private readonly IDataSourceRepository _dataSourceRepository; private readonly ILogger _logger; + private readonly ILocalSourceAuthorizationService _authorization; private int _nodeCounter; private readonly SemaphoreSlim _counterSemaphore = new(1, 1); @@ -31,7 +32,7 @@ public DataNodeService(ISessionService sessionService, IConnectionService connec IDataEncrypter dataEncrypter, IInventoryApiClient inventoryApiClient, IDataNodeRepository dataNodeRepository, IDataNodeCodeGenerator codeGenerator, IDataSourceService dataSourceService, - IDataSourceRepository dataSourceRepository, ILogger logger) + IDataSourceRepository dataSourceRepository, ILogger logger, ILocalSourceAuthorizationService authorization) { _sessionService = sessionService; _connectionService = connectionService; @@ -42,6 +43,7 @@ public DataNodeService(ISessionService sessionService, IConnectionService connec _dataSourceService = dataSourceService; _dataSourceRepository = dataSourceRepository; _logger = logger; + _authorization = authorization; // Reset the counter when a session ends or is reset _sessionService.SessionObservable @@ -133,6 +135,7 @@ public async Task TryRemoveDataNode(DataNode dataNode) foreach (var dataSource in associatedDataSources) { + if (dataSource.ClientInstanceId == _connectionService.ClientInstanceId) _authorization.Revoke(dataSource); _dataSourceService.ApplyRemoveDataSourceLocally(dataSource); } } @@ -142,12 +145,16 @@ public async Task TryRemoveDataNode(DataNode dataNode) public void ApplyAddDataNodeLocally(DataNode dataNode) { + var existing = _dataNodeRepository.GetElement(dataNode.Id); + if (existing != null && existing.ClientInstanceId != dataNode.ClientInstanceId) throw new UnauthorizedAccessException("Node id already belongs to another instance"); _dataNodeRepository.AddOrUpdate(dataNode); _codeGenerator.RecomputeCodes(); } public void ApplyRemoveDataNodeLocally(DataNode dataNode) { + var existing = _dataNodeRepository.GetElement(dataNode.Id); + if (existing != null && existing.ClientInstanceId != dataNode.ClientInstanceId) throw new UnauthorizedAccessException("Node owner mismatch"); _dataNodeRepository.Remove(dataNode); _codeGenerator.RecomputeCodes(); } diff --git a/src/ByteSync.Client/Services/Inventories/DataSourceService.cs b/src/ByteSync.Client/Services/Inventories/DataSourceService.cs index 98d460536..2f1b1433a 100644 --- a/src/ByteSync.Client/Services/Inventories/DataSourceService.cs +++ b/src/ByteSync.Client/Services/Inventories/DataSourceService.cs @@ -1,4 +1,4 @@ -using ByteSync.Business.DataNodes; +using ByteSync.Business.DataNodes; using ByteSync.Business.DataSources; using ByteSync.Common.Business.Inventories; using ByteSync.Common.Business.Sessions.Cloud; @@ -14,6 +14,8 @@ namespace ByteSync.Services.Inventories; public class DataSourceService : IDataSourceService { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISessionService _sessionService; private readonly IDataSourceChecker _dataSourceChecker; private readonly IDataEncrypter _dataEncrypter; @@ -25,8 +27,9 @@ public class DataSourceService : IDataSourceService public DataSourceService(ISessionService sessionService, IDataSourceChecker dataSourceChecker, IDataEncrypter dataEncrypter, IConnectionService connectionService, IInventoryApiClient inventoryApiClient, - IDataSourceRepository dataSourceRepository, IDataSourceCodeGenerator codeGenerator, ILogger logger) + IDataSourceRepository dataSourceRepository, IDataSourceCodeGenerator codeGenerator, ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sessionService = sessionService; _dataSourceChecker = dataSourceChecker; _dataEncrypter = dataEncrypter; @@ -68,6 +71,7 @@ public async Task TryAddDataSource(DataSource dataSource) public void ApplyAddDataSourceLocally(DataSource dataSource) { + _authorization.CheckNetworkSource(dataSource, dataSource.ClientInstanceId); _dataSourceRepository.AddOrUpdate(dataSource); _codeGenerator.RecomputeCodesForNode(dataSource.DataNodeId); } @@ -83,9 +87,18 @@ public Task CreateAndTryAddDataSource(string path, FileSystemTypes fileSystemTyp dataSource.DataNodeId = dataNode.Id; dataSource.InitialTimestamp = DateTime.UtcNow; + _authorization.Grant(dataSource); return TryAddDataSource(dataSource); } + public async Task RestoreDataSource(string path, FileSystemTypes type, DataNode node) + { + var source = new DataSource { Id = Guid.NewGuid().ToString(), Path = path, Type = type, + DataNodeId = node.Id, ClientInstanceId = _connectionService.ClientInstanceId!, InitialTimestamp = DateTime.UtcNow }; + _authorization.Grant(source, true); + await TryAddDataSource(source); + } + public async Task TryRemoveDataSource(DataSource dataSource) { var encryptedDataSource = _dataEncrypter.EncryptDataSource(dataSource); @@ -99,6 +112,7 @@ public async Task TryRemoveDataSource(DataSource dataSource) if (isRemoveOK) { + _authorization.Revoke(dataSource); ApplyRemoveDataSourceLocally(dataSource); } diff --git a/src/ByteSync.Client/Services/Inventories/InventoryBuilder.cs b/src/ByteSync.Client/Services/Inventories/InventoryBuilder.cs index 0c3d1664f..9b16061f6 100644 --- a/src/ByteSync.Client/Services/Inventories/InventoryBuilder.cs +++ b/src/ByteSync.Client/Services/Inventories/InventoryBuilder.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; using ByteSync.Business; using ByteSync.Business.Arguments; @@ -104,6 +104,7 @@ public InventoryPart AddInventoryPart(DataSource dataSource) var inventoryPart = AddInventoryPart(dataSource.Path); inventoryPart.Code = dataSource.Code; + inventoryPart.SourceId = dataSource.Id; return inventoryPart; } diff --git a/src/ByteSync.Client/Services/Inventories/InventoryFileAnalyzer.cs b/src/ByteSync.Client/Services/Inventories/InventoryFileAnalyzer.cs index 8a980a973..bd1d1f557 100644 --- a/src/ByteSync.Client/Services/Inventories/InventoryFileAnalyzer.cs +++ b/src/ByteSync.Client/Services/Inventories/InventoryFileAnalyzer.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; using ByteSync.Business; using ByteSync.Business.Arguments; @@ -19,15 +19,17 @@ public class InventoryFileAnalyzer : IInventoryFileAnalyzer private readonly IInventorySaver _saver; private readonly ILogger _logger; + private readonly ILocalSourceAuthorizationService _authorization; public InventoryFileAnalyzer(FingerprintModes fingerprintMode, InventoryProcessData processData, IInventorySaver saver, - ILogger logger) + ILogger logger, ILocalSourceAuthorizationService authorization) { _fingerprintMode = fingerprintMode; _processData = processData; _saver = saver; _logger = logger; + _authorization = authorization; ManualResetSyncEvents = new ManualResetSyncEvents(); SyncRoot = new object(); @@ -148,9 +150,10 @@ private void HandleFilesAnalysis() private void ComputeFingerPrint(Tuple tuple) { + _authorization.ValidatePath(tuple.Item2.FullName); if (tuple.Item1.FingerprintMode == FingerprintModes.Sha256) { - using var basisStream = new FileStream(tuple.Item2.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); + using var basisStream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(tuple.Item2.FullName); var sha256 = CryptographyUtils.ComputeSHA256(basisStream); tuple.Item1.Sha256 = sha256; @@ -159,7 +162,7 @@ private void ComputeFingerPrint(Tuple tuple) { _logger.LogInformation("Analyzing file {FullName}", tuple.Item2.FullName); - using var basisStream = new FileStream(tuple.Item2.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); + using var basisStream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(tuple.Item2.FullName); using var memoryStream = new MemoryStream(); var signatureBuilder = new SignatureBuilder(); signatureBuilder.Build(basisStream, new SignatureWriter(memoryStream)); diff --git a/src/ByteSync.Client/Services/Inventories/InventoryLoader.cs b/src/ByteSync.Client/Services/Inventories/InventoryLoader.cs index dd7016b1a..dc8069f4a 100644 --- a/src/ByteSync.Client/Services/Inventories/InventoryLoader.cs +++ b/src/ByteSync.Client/Services/Inventories/InventoryLoader.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using ByteSync.Common.Controls.Json; using ByteSync.Models.Inventories; @@ -7,13 +7,25 @@ namespace ByteSync.Services.Inventories; public class InventoryLoader : IDisposable { - public InventoryLoader(string fullName) + private readonly string? _expectedOwner; + + public InventoryLoader(string fullName, string? expectedOwner = null) { FullName = fullName; + _expectedOwner = expectedOwner; - ZipArchive = ZipFile.OpenRead(FullName); - - Inventory = Load(); + var stream = ByteSync.Services.Synchronizations.LocalPathSafety.OpenRead(FullName); + try + { + ZipArchive = new ZipArchive(stream, ZipArchiveMode.Read); + Inventory = Load(); + } + catch + { + ZipArchive?.Dispose(); + stream.Dispose(); + throw; + } } public string FullName { get; } @@ -40,6 +52,22 @@ private Inventory Load() throw new InvalidOperationException("Failed to deserialize inventory.json."); } + if (_expectedOwner != null && inventory.Endpoint.ClientInstanceId != _expectedOwner) throw new UnauthorizedAccessException("Inventory sender mismatch"); + foreach (var part in inventory.InventoryParts) + { + part.Inventory = inventory; + if (_expectedOwner != null && string.IsNullOrEmpty(part.SourceId)) throw new UnauthorizedAccessException("Missing inventory source id"); + foreach (var item in part.FileDescriptions.Cast().Concat(part.DirectoryDescriptions)) + { + item.InventoryPart = part; + if (_expectedOwner != null) + { + if (item.RelativePath == null || !item.RelativePath.StartsWith('/')) throw new UnauthorizedAccessException("Invalid inventory path"); + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateRelativePath(item.RelativePath[1..]); + } + } + } + foreach (var inventoryPart in inventory.InventoryParts .Where(ip => !ip.IsIncompleteDueToAccess && (ip.DirectoryDescriptions.Any(d => !d.IsAccessible) diff --git a/src/ByteSync.Client/Services/Inventories/InventorySaver.cs b/src/ByteSync.Client/Services/Inventories/InventorySaver.cs index b39ae802c..6bff03f8f 100644 --- a/src/ByteSync.Client/Services/Inventories/InventorySaver.cs +++ b/src/ByteSync.Client/Services/Inventories/InventorySaver.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using ByteSync.Common.Controls.Json; using ByteSync.Interfaces.Controls.Inventories; @@ -19,12 +19,12 @@ public void Start(string inventoryFullName) if (File.Exists(inventoryFullName)) { Log.Information("Deleting {FileFullName}", inventoryFullName); - File.Delete(inventoryFullName); + ByteSync.Services.Synchronizations.LocalPathSafety.Delete(inventoryFullName); // throw new Exception("file already exists"); } - ZipArchive = ZipFile.Open(inventoryFullName, ZipArchiveMode.Create); + ZipArchive = new ZipArchive(ByteSync.Services.Synchronizations.LocalPathSafety.OpenWrite(inventoryFullName, true), ZipArchiveMode.Create); CountByDirectory.Clear(); } diff --git a/src/ByteSync.Client/Services/Inventories/InventoryService.cs b/src/ByteSync.Client/Services/Inventories/InventoryService.cs index 1e61f34e0..00ffee1ee 100644 --- a/src/ByteSync.Client/Services/Inventories/InventoryService.cs +++ b/src/ByteSync.Client/Services/Inventories/InventoryService.cs @@ -1,4 +1,4 @@ -using System.Reactive.Linq; +using System.Reactive.Linq; using ByteSync.Business; using ByteSync.Business.Communications; using ByteSync.Business.DataNodes; @@ -62,6 +62,11 @@ public async Task OnFileIsFullyDownloaded(LocalSharedFile localSharedFile) { if (localSharedFile.SharedFileDefinition.IsInventory) { + using var loader = new InventoryLoader(localSharedFile.LocalPath, localSharedFile.SharedFileDefinition.ClientInstanceId); + var node = _dataNodeRepository.GetElement(loader.Inventory.NodeId); + if (node == null || node.ClientInstanceId != localSharedFile.SharedFileDefinition.ClientInstanceId || + loader.Inventory.CodeAndId != localSharedFile.SharedFileDefinition.AdditionalName) + throw new UnauthorizedAccessException("Inventory node or id mismatch"); var inventoryFile = new InventoryFile(localSharedFile); _inventoryFileRepository.AddOrUpdate(inventoryFile); diff --git a/src/ByteSync.Client/Services/Inventories/LocalSourceAuthorizationService.cs b/src/ByteSync.Client/Services/Inventories/LocalSourceAuthorizationService.cs new file mode 100644 index 000000000..c9924c0aa --- /dev/null +++ b/src/ByteSync.Client/Services/Inventories/LocalSourceAuthorizationService.cs @@ -0,0 +1,141 @@ +using System.IO; +using ByteSync.Business.Actions.Shared; +using ByteSync.Business.DataSources; +using ByteSync.Common.Business.Inventories; +using ByteSync.Interfaces; +using ByteSync.Interfaces.Controls.Inventories; +using ByteSync.Interfaces.Services.Communications; +using ByteSync.Interfaces.Services.Sessions; +using ByteSync.Services.Synchronizations; + +namespace ByteSync.Services.Inventories; + +public class LocalSourceAuthorizationService(IApplicationSettingsRepository settings, IConnectionService connection, + ISessionService session, ByteSync.Interfaces.Repositories.IDataNodeRepository nodes) : ILocalSourceAuthorizationService +{ + private sealed record GrantData(object? Session, string SessionId, string Id, string NodeId, string InstanceId, string Root, FileSystemTypes Type); + private readonly Dictionary<(string, string), GrantData> _grants = new(); + private readonly object _gate = new(); + + public void Grant(DataSource source, bool restoreOnly = false) + { + if (source.ClientInstanceId != connection.ClientInstanceId || session.SessionId == null || + string.IsNullOrEmpty(source.Id) || string.IsNullOrEmpty(source.DataNodeId)) throw new UnauthorizedAccessException(); + if (source.Type is not (FileSystemTypes.File or FileSystemTypes.Directory)) throw new UnauthorizedAccessException(); + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(source.Path)); + if (!Path.IsPathFullyQualified(source.Path)) throw new UnauthorizedAccessException(); + LocalPathSafety.AssertNoLinks(root); + var identity = ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(settings.GetCurrentApplicationSettings().DecodedRsaPublicKey!); + var permission = new LocalSourcePermission(identity, root, source.Type); + lock (_gate) + { + var permissions = settings.GetCurrentApplicationSettings().LocalSourcePermissions; + if (restoreOnly && !permissions.Contains(permission)) + throw new UnauthorizedAccessException("Select the profile source locally before running it automatically"); + if (!restoreOnly && !permissions.Contains(permission)) + settings.UpdateCurrentApplicationSettings(s => s.LocalSourcePermissions.Add(permission)); + _grants[(session.SessionId, source.Id)] = new GrantData(session.CurrentSession, session.SessionId, source.Id, source.DataNodeId, + source.ClientInstanceId, root, source.Type); + } + } + + public void Revoke(DataSource source) + { + lock (_gate) + { + if (session.SessionId != null) _grants.Remove((session.SessionId, source.Id)); + settings.UpdateCurrentApplicationSettings(s => s.LocalSourcePermissions.RemoveAll(p => + p.Path == Path.TrimEndingDirectorySeparator(Path.GetFullPath(source.Path)) && p.Type == source.Type)); + } + } + + public void CheckNetworkSource(DataSource source, string sender) + { + if (source.ClientInstanceId != sender) throw new UnauthorizedAccessException("Source owner mismatch"); + var node = nodes.GetElement(source.DataNodeId); + if (node == null || node.ClientInstanceId != sender) throw new UnauthorizedAccessException("Source node owner mismatch"); + if (sender != connection.ClientInstanceId) return; + var part = new SharedDataPart { SourceId = source.Id, NodeId = source.DataNodeId, ClientInstanceId = sender, + InventoryPartType = source.Type, SourceRelativePath = "" }; + var expected = Resolve(part); + if (!string.Equals(expected, Path.TrimEndingDirectorySeparator(Path.GetFullPath(source.Path)), LocalPathSafety.Comparison)) + throw new UnauthorizedAccessException("Network data cannot change a local source root"); + } + + public string Resolve(SharedDataPart part) + { + lock (_gate) + { + if (session.SessionId == null || part.SourceId == null || + !_grants.TryGetValue((session.SessionId, part.SourceId), out var grant) || + part.ClientInstanceId != connection.ClientInstanceId || grant.InstanceId != part.ClientInstanceId || + !ReferenceEquals(grant.Session, session.CurrentSession) || grant.NodeId != part.NodeId || grant.Type != part.InventoryPartType) throw new UnauthorizedAccessException("Local source is not authorized"); + LocalPathSafety.ValidateRelativePath(part.SourceRelativePath); + if (grant.Type == FileSystemTypes.File && part.SourceRelativePath != "") throw new UnauthorizedAccessException("File source cannot authorize siblings"); + var resolved = Path.GetFullPath(Path.Combine(grant.Root, part.SourceRelativePath!.Replace('/', Path.DirectorySeparatorChar))); + var boundary = Path.EndsInDirectorySeparator(grant.Root) ? grant.Root : grant.Root + Path.DirectorySeparatorChar; + if (!string.Equals(resolved, grant.Root, LocalPathSafety.Comparison) && + !resolved.StartsWith(boundary, LocalPathSafety.Comparison)) + throw new UnauthorizedAccessException("Path escapes source"); + LocalPathSafety.AssertNoLinks(resolved); + return resolved; + } + } + + public void ValidatePlan(IEnumerable groups) + { + var bindings = new List(); + var ids = new HashSet(StringComparer.Ordinal); + foreach (var group in groups) + { + if (group == null || string.IsNullOrEmpty(group.ActionsGroupId) || !ids.Add(group.ActionsGroupId)) + throw new UnauthorizedAccessException("Invalid or duplicate action id"); + LocalPathSafety.ValidateComponent(group.ActionsGroupId); + if (!Enum.IsDefined(group.Operator) || group.Targets == null || group.PathIdentity == null || + (group.NeedsOperatingOnSourceAndTargets && group.Source == null)) throw new UnauthorizedAccessException("Invalid synchronization plan"); + if (group.PathIdentity.FileSystemType is not (FileSystemTypes.File or FileSystemTypes.Directory) || + (group.IsCreate && !group.IsDirectory) || ((group.IsCopyContent || group.IsCopyDates) && !group.IsFile) || + ((group.IsFullCopy || group.IsCopyDates) && (!group.CreationTimeUtc.HasValue || !group.LastWriteTimeUtc.HasValue)) || + (group.IsCopyContent && group.SynchronizationType is not (ByteSync.Common.Business.Actions.SynchronizationTypes.Full or ByteSync.Common.Business.Actions.SynchronizationTypes.Delta))) + throw new UnauthorizedAccessException("Incomplete synchronization operation"); + foreach (var part in group.Targets.Concat(group.Source == null ? Array.Empty() : new[] { group.Source })) + { + if (part == null || string.IsNullOrEmpty(part.SourceId) || string.IsNullOrEmpty(part.NodeId) || string.IsNullOrEmpty(part.ClientInstanceId)) + throw new UnauthorizedAccessException("Missing action source binding"); + LocalPathSafety.ValidateRelativePath(part.SourceRelativePath); + } + if (group.Source != null && group.Source.ClientInstanceId == connection.ClientInstanceId) bindings.Add(group.Source); + bindings.AddRange(group.Targets.Where(p => p.ClientInstanceId == connection.ClientInstanceId)); + } + foreach (var part in bindings) Resolve(part); + foreach (var part in bindings) part.LocalPathResolver = () => Resolve(part); + } + + public void ValidatePath(string path) + { + lock (_gate) + { + var full = Path.GetFullPath(path); + foreach (var grant in _grants.Values.Where(g => g.SessionId == session.SessionId)) + { + var relative = Path.GetRelativePath(grant.Root, full).Replace(Path.DirectorySeparatorChar, '/'); + if (relative == ".") relative = ""; + try + { + var resolved = Resolve(new SharedDataPart { SourceId = grant.Id, NodeId = grant.NodeId, ClientInstanceId = grant.InstanceId, + InventoryPartType = grant.Type, SourceRelativePath = relative }); + if (string.Equals(resolved, full, StringComparison.Ordinal)) return; + } + catch (UnauthorizedAccessException) { } + } + throw new UnauthorizedAccessException("Path has no current local authorization"); + } + } + + public void ValidateDestination(SharedActionsGroup group, string destination) + { + if (!group.Targets.Where(p => p.ClientInstanceId == connection.ClientInstanceId) + .Any(p => string.Equals(Resolve(p), destination, LocalPathSafety.Comparison))) + throw new UnauthorizedAccessException("Destination is not part of the authorized action"); + } +} diff --git a/src/ByteSync.Client/Services/Profiles/SessionProfileLocalDataManager.cs b/src/ByteSync.Client/Services/Profiles/SessionProfileLocalDataManager.cs index 4aba07a6b..a5da97f6d 100644 --- a/src/ByteSync.Client/Services/Profiles/SessionProfileLocalDataManager.cs +++ b/src/ByteSync.Client/Services/Profiles/SessionProfileLocalDataManager.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using System.Threading.Tasks; using ByteSync.Business.Profiles; @@ -27,6 +27,7 @@ public SessionProfileLocalDataManager(ILocalApplicationDataManager localApplicat public string GetProfileZipPath(string profileId) { + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateComponent(profileId); var profilesDirectory = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Profiles", profileId); Directory.CreateDirectory(profilesDirectory); @@ -39,6 +40,7 @@ public string GetProfileZipPath(SharedFileDefinition sharedFileDefinition) { if (sharedFileDefinition.IsProfileDetails) { + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateComponent(sharedFileDefinition.AdditionalName); var profilesDirectory = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Profiles", sharedFileDefinition.AdditionalName); Directory.CreateDirectory(profilesDirectory); @@ -55,6 +57,7 @@ public string GetProfileZipPath(SharedFileDefinition sharedFileDefinition) public DirectoryInfo GetProfileDirectory(AbstractSessionProfile sessionProfile) { + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateComponent(sessionProfile.ProfileId); var profileDirectory = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Profiles", sessionProfile.ProfileId); return new DirectoryInfo(profileDirectory); @@ -62,6 +65,7 @@ public DirectoryInfo GetProfileDirectory(AbstractSessionProfile sessionProfile) public DirectoryInfo GetProfileDirectory(AbstrastSessionProfileDetails abstrastSessionProfileDetails) { + ByteSync.Services.Synchronizations.LocalPathSafety.ValidateComponent(abstrastSessionProfileDetails.ProfileId); var profileDirectory = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Profiles", abstrastSessionProfileDetails.ProfileId); return new DirectoryInfo(profileDirectory); diff --git a/src/ByteSync.Client/Services/Profiles/SessionProfileManager.cs b/src/ByteSync.Client/Services/Profiles/SessionProfileManager.cs index a8e521b96..0867866cb 100644 --- a/src/ByteSync.Client/Services/Profiles/SessionProfileManager.cs +++ b/src/ByteSync.Client/Services/Profiles/SessionProfileManager.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.IO.Compression; using System.Threading.Tasks; using ByteSync.Assets.Resources; @@ -367,7 +367,8 @@ private CloudSessionProfileDetails BuildCloudSessionProfileDetails(CloudSessionP cloudSessionProfileMember.IpAddress = sessionMemberInfo.IpAddress; cloudSessionProfileMember.ProfileClientId = data.Slots - .Single(t => t.ClientId.Equals(sessionMemberInfo.Endpoint.ClientId)).ProfileClientId; + .Single(t => t.ClientId.Equals(sessionMemberInfo.Endpoint.ClientId) && + t.OriginalClientInstanceId == sessionMemberInfo.ClientInstanceId).ProfileClientId; cloudSessionProfileMember.ProfileClientPassword = $"CSPCP_{Guid.NewGuid()}"; cloudSessionProfileMember.DataSources = allDataSources .Where(ds => ds.BelongsTo(sessionMemberInfo)) diff --git a/src/ByteSync.Client/Services/Sessions/CloudSessionLocalDataManager.cs b/src/ByteSync.Client/Services/Sessions/CloudSessionLocalDataManager.cs index fae1f43b5..74c60579b 100644 --- a/src/ByteSync.Client/Services/Sessions/CloudSessionLocalDataManager.cs +++ b/src/ByteSync.Client/Services/Sessions/CloudSessionLocalDataManager.cs @@ -1,4 +1,5 @@ -using System.IO; +using System.IO; +using ByteSync.Services.Synchronizations; using ByteSync.Business; using ByteSync.Business.Actions.Shared; using ByteSync.Common.Business.SharedFiles; @@ -33,11 +34,12 @@ public CloudSessionLocalDataManager(ILocalApplicationDataManager localApplicatio internal string GetSessionLocalPath() { var cloudSession = _sessionService.CurrentSession!; + LocalPathSafety.ValidateComponent(cloudSession.SessionId); var sessionLocalPath = IOUtils.Combine(_localApplicationDataManager.ApplicationDataPath, "Sessions", $"{cloudSession.SessionId}_{cloudSession.Created:yyyyMMddTHHmmss}"); - Directory.CreateDirectory(sessionLocalPath); + LocalPathSafety.CreateDirectory(sessionLocalPath); return sessionLocalPath; } @@ -56,13 +58,14 @@ private string GetMachineFullPath(string clientInstanceId) var sessionMember = _sessionMemberRepository.GetElement(clientInstanceId); machinePath = sessionMember!.MachineName; } - machinePath += "_" + clientInstanceId; + LocalPathSafety.ValidateComponent(clientInstanceId); + machinePath = clientInstanceId; var machineFullPath = IOUtils.Combine(sessionLocalPath, machinePath); if (!Directory.Exists(machineFullPath)) { - Directory.CreateDirectory(machineFullPath); + LocalPathSafety.CreateDirectory(machineFullPath); } return machineFullPath; @@ -87,6 +90,7 @@ public string GetInventoryPath(SharedFileDefinition sharedFileDefinition) public string GetInventoryPath(string clientInstanceId, string inventoryCodeAndId, LocalInventoryModes localInventoryMode) { + LocalPathSafety.ValidateComponent(inventoryCodeAndId); var machineFullPath = GetMachineFullPath(clientInstanceId); string fileName; @@ -106,13 +110,15 @@ public string GetInventoryPath(string clientInstanceId, string inventoryCodeAndI public string GetTempDeltaFullName(SharedDataPart source, SharedDataPart target) { + if (source.SignatureGuid != null) LocalPathSafety.ValidateComponent(source.SignatureGuid); + if (target.SignatureGuid != null) LocalPathSafety.ValidateComponent(target.SignatureGuid); var sessionLocalPath = GetSessionLocalPath(); var tempFullPath = IOUtils.Combine(sessionLocalPath, "Temp"); if (!Directory.Exists(tempFullPath)) { - Directory.CreateDirectory(tempFullPath); + LocalPathSafety.CreateDirectory(tempFullPath); } var cpt = 0; @@ -144,13 +150,14 @@ public string GetSynchronizationTempZipPath(SharedFileDefinition sharedFileDefin { if (sharedFileDefinition.IsSynchronization) { + LocalPathSafety.ValidateComponent(sharedFileDefinition.Id); var sessionLocalPath = GetSessionLocalPath(); var tempFullPath = IOUtils.Combine(sessionLocalPath, "Temp"); if (!Directory.Exists(tempFullPath)) { - Directory.CreateDirectory(tempFullPath); + LocalPathSafety.CreateDirectory(tempFullPath); } var fileName = $"{sharedFileDefinition.Id}_temp.zip"; diff --git a/src/ByteSync.Client/Services/Sessions/Connecting/AfterJoinSessionService.cs b/src/ByteSync.Client/Services/Sessions/Connecting/AfterJoinSessionService.cs index c1c8d80e4..11e279523 100644 --- a/src/ByteSync.Client/Services/Sessions/Connecting/AfterJoinSessionService.cs +++ b/src/ByteSync.Client/Services/Sessions/Connecting/AfterJoinSessionService.cs @@ -1,4 +1,4 @@ -using System.Text; +using System.Text; using ByteSync.Business.Arguments; using ByteSync.Business.Sessions.Connecting; using ByteSync.Common.Business.Inventories; @@ -141,6 +141,8 @@ private async Task FillDataNodes(AfterJoinSessionRequest request, List _logger; public DeltaManager(ICloudSessionLocalDataManager cloudSessionLocalDataManager, ITemporaryFileManagerFactory temporaryFileManagerFactory, - ILogger logger) + ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _cloudSessionLocalDataManager = cloudSessionLocalDataManager; _temporaryFileManagerFactory = temporaryFileManagerFactory; _logger = logger; @@ -37,8 +41,8 @@ public async Task BuildDelta(SharedActionsGroup sharedActionsGroup, Shar var deltaBuilder = new DeltaBuilder(); await using var targetMemoryStream = targetInventoryLoader.GetSignature(sharedDataPart.SignatureGuid!); - await using var newFileStream = new FileStream(sourceFullName, FileMode.Open, FileAccess.Read, FileShare.Read); - await using var deltaStream = new FileStream(deltaFullName, FileMode.Create, FileAccess.Write, FileShare.Read); + await using var newFileStream = LocalPathSafety.OpenRead(sharedActionsGroup.GetSourceFullName()); + await using var deltaStream = LocalPathSafety.OpenWrite(deltaFullName, true); await deltaBuilder.BuildDeltaAsync(newFileStream, new SignatureReader(targetMemoryStream, deltaBuilder.ProgressReport), @@ -49,12 +53,13 @@ await deltaBuilder.BuildDeltaAsync(newFileStream, public async Task ApplyDelta(string destinationFullName, string deltaFullName) { - await using var deltaStream = new FileStream(deltaFullName, FileMode.Open, FileAccess.Read, FileShare.Read); + await using var deltaStream = LocalPathSafety.OpenRead(deltaFullName); await ApplyDelta(destinationFullName, deltaStream); } public async Task ApplyDelta(string destinationFullName, Stream deltaStream) { + _authorization.ValidatePath(destinationFullName); var deltaApplier = new DeltaApplier { SkipHashCheck = false @@ -69,11 +74,12 @@ public async Task ApplyDelta(string destinationFullName, Stream deltaStream) { // This block is necessary, otherwise the disposals do not occur and the validate temporary file crashes { - await using var basisStream = new FileStream(destinationFullName, FileMode.Open, FileAccess.Read, FileShare.Read); - await using var newFileStream = new FileStream(destinationTemporaryPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); + await using var basisStream = LocalPathSafety.OpenRead(destinationFullName); + await using var newFileStream = LocalPathSafety.OpenWrite(destinationTemporaryPath, true, readable: true); await deltaApplier.ApplyAsync(basisStream, new BinaryDeltaReader(deltaStream, null), newFileStream); } + _authorization.ValidatePath(destinationFullName); temporaryFileManager.ValidateTemporaryFile(); } catch (Exception ex) diff --git a/src/ByteSync.Client/Services/Synchronizations/FileDatesSetter.cs b/src/ByteSync.Client/Services/Synchronizations/FileDatesSetter.cs index 6150a6eb7..10a8997d1 100644 --- a/src/ByteSync.Client/Services/Synchronizations/FileDatesSetter.cs +++ b/src/ByteSync.Client/Services/Synchronizations/FileDatesSetter.cs @@ -1,3 +1,4 @@ +using ByteSync.Interfaces.Controls.Inventories; using System.IO; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Communications.Downloading; @@ -8,10 +9,13 @@ namespace ByteSync.Services.Synchronizations; public class FileDatesSetter : IFileDatesSetter { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ILogger _logger; - public FileDatesSetter(ILogger logger) + public FileDatesSetter(ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _logger = logger; } @@ -19,21 +23,20 @@ public Task SetDates(SharedFileDefinition sharedFileDefinition, string finalDest { return Task.Run(() => { + _authorization.ValidatePath(finalDestination); if (downloadTargetDates != null) { _logger.LogInformation("{sharedFileDefinitionId}: Setting CreationTime and LastWriteTime on {FinalDestination}", sharedFileDefinition.Id, finalDestination); - File.SetCreationTimeUtc(finalDestination, downloadTargetDates.CreationTimeUtc); - File.SetLastWriteTimeUtc(finalDestination, downloadTargetDates.LastWriteTimeUtc); + LocalPathSafety.SetDates(finalDestination, downloadTargetDates.CreationTimeUtc, downloadTargetDates.LastWriteTimeUtc); } else { _logger.LogInformation("{sharedFileDefinitionId}: Setting CreationTime and LastWriteTime on {FinalDestination} to now", sharedFileDefinition.Id, finalDestination); - File.SetCreationTimeUtc(finalDestination, DateTime.UtcNow); - File.SetLastWriteTimeUtc(finalDestination, DateTime.UtcNow); + LocalPathSafety.SetDates(finalDestination, DateTime.UtcNow, DateTime.UtcNow); } }); } @@ -42,21 +45,20 @@ public Task SetDates(SharedActionsGroup sharedActionsGroup, string finalDestinat { return Task.Run(() => { + _authorization.ValidatePath(finalDestination); if (downloadTargetDates != null) { _logger.LogInformation("{Type:l}: Setting CreationTime and LastWriteTime on {FinalDestination}", $"Synchronization.{sharedActionsGroup.Operator}", finalDestination); - File.SetCreationTimeUtc(finalDestination, downloadTargetDates.CreationTimeUtc); - File.SetLastWriteTimeUtc(finalDestination, downloadTargetDates.LastWriteTimeUtc); + LocalPathSafety.SetDates(finalDestination, downloadTargetDates.CreationTimeUtc, downloadTargetDates.LastWriteTimeUtc); } else { _logger.LogInformation("{Type:l}: Setting CreationTime and LastWriteTime on {FinalDestination} to now", $"Synchronization.{sharedActionsGroup.Operator}", finalDestination); - File.SetCreationTimeUtc(finalDestination, DateTime.UtcNow); - File.SetLastWriteTimeUtc(finalDestination, DateTime.UtcNow); + LocalPathSafety.SetDates(finalDestination, DateTime.UtcNow, DateTime.UtcNow); } }); } diff --git a/src/ByteSync.Client/Services/Synchronizations/LocalPathSafety.cs b/src/ByteSync.Client/Services/Synchronizations/LocalPathSafety.cs new file mode 100644 index 000000000..6c52d0f4d --- /dev/null +++ b/src/ByteSync.Client/Services/Synchronizations/LocalPathSafety.cs @@ -0,0 +1,368 @@ +using System.Text; +using System.ComponentModel; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +using System.IO; + +namespace ByteSync.Services.Synchronizations; + +public static class LocalPathSafety +{ + public static StringComparison Comparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + public static void ValidateComponent(string? value) + { + ValidateRelativePath(value); + if (string.IsNullOrEmpty(value) || value.Contains('/')) throw new UnauthorizedAccessException("Invalid storage component"); + } + + public static void ValidateRelativePath(string? path) + { + if (path == null || path.Contains('\\') || path.Contains(':') || path.Contains('\0') || path.StartsWith('/') || + Path.IsPathRooted(path)) throw new UnauthorizedAccessException("Invalid relative path"); + if (path == "") return; + foreach (var component in path.Split('/')) + { + if (component is "" or "." or ".." || component.Any(char.IsControl)) throw new UnauthorizedAccessException("Ambiguous relative path"); + if (OperatingSystem.IsWindows()) + { + var basename = component.Split('.')[0]; + if (component.EndsWith(' ') || component.EndsWith('.') || component.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || + new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }.Contains(basename, StringComparer.OrdinalIgnoreCase)) + throw new UnauthorizedAccessException("Ambiguous Windows path"); + } + } + } + + public static void AssertNoLinks(string path) + { + var fullPath = Path.GetFullPath(path); + var root = Path.GetPathRoot(fullPath)!; + if (OperatingSystem.IsWindows() && root.StartsWith(@"\\")) throw new UnauthorizedAccessException("UNC sources are not supported"); + var current = root; + foreach (var component in fullPath[root.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, component); + try + { + var attributes = File.GetAttributes(current); + if ((attributes & FileAttributes.ReparsePoint) != 0) throw new UnauthorizedAccessException("Links and reparse points are not allowed"); + } + catch (FileNotFoundException) { } + catch (DirectoryNotFoundException) { } + } + } + public static IDisposable Acquire(params string[] paths) => AcquireDirectories(1, paths); + + private static IDisposable AcquireDirectories(uint sharing, params string[] paths) + { + var handles = new List(); + try + { + foreach (var path in paths.Distinct()) + { + AssertNoLinks(path); + if (!OperatingSystem.IsWindows()) continue; + var full = Path.GetFullPath(path); + var current = Path.GetPathRoot(full)!; + foreach (var component in full[current.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, component); + if (current == full || !Directory.Exists(current)) break; + var handle = OpenWindows(current, 0x80000000, sharing, 0x02200000); + handles.Add(handle); + } + } + return new DirectoryLease(handles); + } + catch + { + foreach (var handle in handles) handle.Dispose(); + throw; + } + } + + public static FileStream OpenRead(string path) + { + using var lease = Acquire(path); + if (!OperatingSystem.IsWindows()) return OpenUnixRead(path); + var handle = OpenWindows(path, 0x80000000, 1, 0x00200000); + return new FileStream(handle, FileAccess.Read); + } + + private static FileStream OpenUnixRead(string path) + { + var full = Path.GetFullPath(path); + var noFollow = OperatingSystem.IsMacOS() ? 0x100 : 0x20000; + var directory = OperatingSystem.IsMacOS() ? 0x100000 : 0x10000; + var fd = OpenAt(OperatingSystem.IsMacOS() ? -2 : -100, "/", directory | noFollow, 0); + if (fd < 0) throw new IOException("Cannot open root", new Win32Exception(Marshal.GetLastWin32Error())); + var handle = new SafeFileHandle((IntPtr)fd, true); + try + { + var components = full.TrimStart('/').Split('/'); + for (var i = 0; i < components.Length; i++) + { + var next = OpenAt(handle.DangerousGetHandle().ToInt32(), components[i], (OperatingSystem.IsMacOS() ? 4 : 0x800) | noFollow | (i < components.Length - 1 ? directory : 0), 0); + if (next < 0) throw new IOException("Cannot open file without following links", new Win32Exception(Marshal.GetLastWin32Error())); + handle.Dispose(); + handle = new SafeFileHandle((IntPtr)next, true); + } + AssertUnixRegularFile(handle); + return new FileStream(handle, FileAccess.Read); + } + catch { handle.Dispose(); throw; } + } + + + public static FileStream OpenWrite(string path, bool createNew = false, bool append = false, bool readable = false) + { + using var lease = Acquire(path); + SafeFileHandle handle; + if (OperatingSystem.IsWindows()) + handle = OpenWindows(path, readable ? 0xC0000080u : 0x40000080u, 1, 0x00200000, createNew ? 1u : 4u); + else + { + using var parent = OpenUnixParent(path, out var name); + var flags = (readable ? 2 : 1) | (OperatingSystem.IsMacOS() ? 4 : 0x800) | (OperatingSystem.IsMacOS() ? 0x200 : 0x40) | (OperatingSystem.IsMacOS() ? 0x100 : 0x20000); + if (createNew) flags |= OperatingSystem.IsMacOS() ? 0x800 : 0x80; + var fd = OpenAt(parent.DangerousGetHandle().ToInt32(), name, flags, 0x180); + if (fd < 0) throw new IOException("Cannot open destination", new Win32Exception(Marshal.GetLastWin32Error())); + handle = new SafeFileHandle((IntPtr)fd, true); + } + AssertUnixRegularFile(handle); + var stream = new FileStream(handle, readable ? FileAccess.ReadWrite : FileAccess.Write); + if (append) stream.Seek(0, SeekOrigin.End); + else stream.SetLength(0); + return stream; + } + + public static void CreateDirectory(string path) + { + if (!OperatingSystem.IsWindows()) + { + using var directory = OpenUnixDirectory(path, true); + return; + } + var full = Path.GetFullPath(path); + var current = Path.GetPathRoot(full)!; + var handles = new List(); + try + { + foreach (var component in full[current.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, component); + Directory.CreateDirectory(current); + handles.Add(OpenWindows(current, 0x80000000, 1, 0x02200000)); + } + } + finally { foreach (var handle in handles) handle.Dispose(); } + } + + public static void Move(string source, string destination, bool overwrite = false) + { + if (OperatingSystem.IsWindows()) + { + if (!string.Equals(Path.GetDirectoryName(source), Path.GetDirectoryName(destination), StringComparison.Ordinal)) + throw new UnauthorizedAccessException("Replacement must stay in the same directory"); + using var initialLease = Acquire(source, destination); + using var file = OpenWindows(source, 0x80010080, 1, 0x00200000); + using var renameLease = AcquireDirectories(3, source, destination); + using var parent = OpenWindows(Path.GetDirectoryName(destination)!, 0x80000000, 3, 0x02200000); + initialLease.Dispose(); + var name = Encoding.Unicode.GetBytes(Path.GetFileName(destination)); + var handleOffset = IntPtr.Size == 8 ? 8 : 4; + var lengthOffset = handleOffset + IntPtr.Size; + var nameOffset = lengthOffset + 4; + var buffer = Marshal.AllocHGlobal(nameOffset + name.Length); + try + { + for (var i = 0; i < nameOffset; i++) Marshal.WriteByte(buffer, i, 0); + Marshal.WriteByte(buffer, 0, overwrite ? (byte)1 : (byte)0); + Marshal.WriteIntPtr(buffer, handleOffset, parent.DangerousGetHandle()); + Marshal.WriteInt32(buffer, lengthOffset, name.Length); + Marshal.Copy(name, 0, IntPtr.Add(buffer, nameOffset), name.Length); + var status = NtSetInformationFile(file, out _, buffer, (uint)(nameOffset + name.Length), 10); + if (status != 0) throw new IOException("Cannot replace destination", new Win32Exception((int)RtlNtStatusToDosError(status))); + } + finally { Marshal.FreeHGlobal(buffer); } + return; + } + using var sourceParent = OpenUnixParent(source, out var sourceName); + using var targetParent = OpenUnixParent(destination, out var targetName); + var result = OperatingSystem.IsMacOS() + ? RenameAtMac(sourceParent.DangerousGetHandle().ToInt32(), sourceName, targetParent.DangerousGetHandle().ToInt32(), targetName, overwrite ? 0u : 4u) + : RenameAtLinux(sourceParent.DangerousGetHandle().ToInt32(), sourceName, targetParent.DangerousGetHandle().ToInt32(), targetName, overwrite ? 0u : 1u); + if (result != 0) + throw new IOException("Cannot replace destination", new Win32Exception(Marshal.GetLastWin32Error())); + } + + public static void Delete(string path, bool directory = false) + { + using var lease = Acquire(path); + if (OperatingSystem.IsWindows()) + { + if (directory) Directory.Delete(path, false); else File.Delete(path); + return; + } + using var parent = OpenUnixParent(path, out var name); + if (UnlinkAt(parent.DangerousGetHandle().ToInt32(), name, directory ? (OperatingSystem.IsMacOS() ? 0x80 : 0x200) : 0) != 0 && + Marshal.GetLastWin32Error() != 2) throw new IOException("Cannot delete destination", new Win32Exception(Marshal.GetLastWin32Error())); + } + + public static void SetDates(string path, DateTime creation, DateTime write) + { + using var lease = Acquire(path); + if (OperatingSystem.IsWindows()) + { + using var handle = OpenWindows(path, 0x80000100, 1, 0x00200000); + File.SetCreationTimeUtc(handle, creation); + File.SetLastWriteTimeUtc(handle, write); + } + else + { + using var stream = OpenUnixRead(path); + File.SetCreationTimeUtc(stream.SafeFileHandle, creation); + File.SetLastWriteTimeUtc(stream.SafeFileHandle, write); + } + } + + private static SafeFileHandle OpenUnixParent(string path, out string name) + { + var full = Path.GetFullPath(path); + name = Path.GetFileName(full); + if (name.Length == 0) throw new UnauthorizedAccessException("Cannot operate on a filesystem root"); + return OpenUnixDirectory(Path.GetDirectoryName(full)!, false); + } + + private static SafeFileHandle OpenUnixDirectory(string path, bool create) + { + var flags = OperatingSystem.IsMacOS() ? 0x100100 : 0x30000; + var fd = OpenAt(OperatingSystem.IsMacOS() ? -2 : -100, "/", flags, 0); + if (fd < 0) throw new IOException("Cannot open directory root"); + var handle = new SafeFileHandle((IntPtr)fd, true); + try + { + foreach (var component in Path.GetFullPath(path).Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries)) + { + if (create && MkdirAt(handle.DangerousGetHandle().ToInt32(), component, 0x1C0) != 0 && Marshal.GetLastWin32Error() != 17) + throw new IOException("Cannot create directory", new Win32Exception(Marshal.GetLastWin32Error())); + var next = OpenAt(handle.DangerousGetHandle().ToInt32(), component, flags, 0); + if (next < 0) throw new IOException("Cannot access directory without following links", new Win32Exception(Marshal.GetLastWin32Error())); + handle.Dispose(); + handle = new SafeFileHandle((IntPtr)next, true); + } + return handle; + } + catch { handle.Dispose(); throw; } + } + + [DllImport("libc", SetLastError = true, EntryPoint = "mkdirat")] + private static extern int MkdirAt(int directory, string path, uint mode); + [DllImport("libc", SetLastError = true, EntryPoint = "renameat2")] + private static extern int RenameAtLinux(int sourceDirectory, string source, int targetDirectory, string target, uint flags); + [DllImport("libc", SetLastError = true, EntryPoint = "renameatx_np")] + private static extern int RenameAtMac(int sourceDirectory, string source, int targetDirectory, string target, uint flags); + [DllImport("libc", SetLastError = true, EntryPoint = "unlinkat")] + private static extern int UnlinkAt(int directory, string path, int flags); + + private static SafeFileHandle OpenWindows(string path, uint access, uint share, uint flags, uint disposition = 3) + { + var handle = CreateFile(path, access, share, IntPtr.Zero, disposition, flags, IntPtr.Zero); + if (handle.IsInvalid) { handle.Dispose(); throw new IOException("Cannot acquire path access", new Win32Exception(Marshal.GetLastWin32Error())); } + if (!GetFileInformationByHandleEx(handle, 9, out var info, 8) || (info.Attributes & FileAttributes.ReparsePoint) != 0) + { + handle.Dispose(); + throw new UnauthorizedAccessException("Links and reparse points are not allowed"); + } + if ((info.Attributes & FileAttributes.Directory) == 0 && + (!GetFileInformationByHandle(handle, out var fileInfo) || fileInfo.LinkCount != 1)) + { + handle.Dispose(); + throw new UnauthorizedAccessException("Hard-linked files are not allowed"); + } + return handle; + } + + private static void AssertUnixRegularFile(SafeFileHandle handle) + { + if (OperatingSystem.IsWindows()) return; + UnixFileInformation info; + var result = OperatingSystem.IsMacOS() && RuntimeInformation.ProcessArchitecture == Architecture.X64 + ? FStatMac64(handle.DangerousGetHandle().ToInt32(), out info) + : FStat(handle.DangerousGetHandle().ToInt32(), out info); + if (result != 0) + { + handle.Dispose(); + throw new IOException("Cannot inspect opened file"); + } + var mac = OperatingSystem.IsMacOS(); + var arm = RuntimeInformation.ProcessArchitecture == Architecture.Arm64; + if (!mac && RuntimeInformation.ProcessArchitecture is not (Architecture.X64 or Architecture.Arm64)) + { + handle.Dispose(); + throw new PlatformNotSupportedException("Unsupported filesystem ABI"); + } + var links = mac ? info.MacLinks : arm ? info.LinuxArmLinks : info.LinuxX64Links; + var mode = mac ? info.MacMode : arm ? info.LinuxArmMode : info.LinuxX64Mode; + if (links != 1 || (mode & 0xF000) != 0x8000) + { + handle.Dispose(); + throw new UnauthorizedAccessException("Only regular files with one link are allowed"); + } + } + + [StructLayout(LayoutKind.Explicit, Size = 256)] + private struct UnixFileInformation + { + [FieldOffset(16)] public ulong LinuxX64Links; + [FieldOffset(24)] public uint LinuxX64Mode; + [FieldOffset(20)] public uint LinuxArmLinks; + [FieldOffset(16)] public uint LinuxArmMode; + [FieldOffset(6)] public ushort MacLinks; + [FieldOffset(4)] public ushort MacMode; + } + + [StructLayout(LayoutKind.Explicit, Size = 52)] + private struct WindowsFileInformation + { + [FieldOffset(40)] public uint LinkCount; + } + + [DllImport("libc", SetLastError = true, EntryPoint = "fstat")] + private static extern int FStat(int descriptor, out UnixFileInformation information); + [DllImport("libc", SetLastError = true, EntryPoint = "fstat$INODE64")] + private static extern int FStatMac64(int descriptor, out UnixFileInformation information); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetFileInformationByHandle(SafeFileHandle handle, out WindowsFileInformation information); + + [StructLayout(LayoutKind.Sequential)] + private struct IoStatusBlock { public IntPtr Status; public UIntPtr Information; } + + [DllImport("ntdll.dll")] + private static extern int NtSetInformationFile(SafeFileHandle handle, out IoStatusBlock status, IntPtr information, uint length, int kind); + + [DllImport("ntdll.dll")] + private static extern uint RtlNtStatusToDosError(int status); + + private sealed class DirectoryLease(List handles) : IDisposable + { + public void Dispose() { foreach (var handle in handles) handle.Dispose(); } + } + + [StructLayout(LayoutKind.Sequential)] + private struct AttributeTagInfo { public FileAttributes Attributes; public uint Tag; } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateFileW")] + private static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int kind, out AttributeTagInfo info, uint size); + + [DllImport("libc", SetLastError = true, EntryPoint = "openat")] + private static extern int OpenAt(int directory, string path, int flags, uint mode); + +} diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionHandler.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionHandler.cs index ec5385449..a11666237 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionHandler.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionHandler.cs @@ -1,4 +1,5 @@ -using System.IO; +using ByteSync.Interfaces.Controls.Inventories; +using System.IO; using System.Threading; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Communications.Downloading; @@ -16,6 +17,8 @@ namespace ByteSync.Services.Synchronizations; public class SynchronizationActionHandler : ISynchronizationActionHandler { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISessionService _sessionService; private readonly IConnectionService _connectionService; private readonly IDeltaManager _deltaManager; @@ -31,8 +34,9 @@ public SynchronizationActionHandler(ISessionService sessionService, IConnectionS ISynchronizationActionRemoteUploader synchronizationActionRemoteUploader, ISynchronizationService synchronizationService, ISynchronizationApiClient synchronizationApiClient, IFileDatesSetter fileDatesSetter, - ILogger logger) + ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sessionService = sessionService; _connectionService = connectionService; _deltaManager = deltaManager; @@ -51,6 +55,7 @@ public async Task RunSynchronizationAction(SharedActionsGroup sharedActionsGroup try { cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); if (sharedActionsGroup.IsCopyContentOnly || sharedActionsGroup.IsFinallyCopyContentAndDate) { @@ -137,6 +142,7 @@ private async Task RunCopyContentLocal(SharedActionsGroup sharedActionsGroup, Ha foreach (var localTarget in localTargets) { cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); var destinationFullName = sharedActionsGroup.GetFullName(localTarget); @@ -149,7 +155,7 @@ private async Task RunCopyContentLocal(SharedActionsGroup sharedActionsGroup, Ha _logger.LogInformation("{Type:l}: creating directory {directory}", $"Synchronization.{sharedActionsGroup.Operator}", destinationFileInfo.Directory); - destinationFileInfo.Directory.Create(); + LocalPathSafety.CreateDirectory(destinationFileInfo.Directory.FullName); } _logger.LogInformation("{Type:l}: copying from {source} to {destination}", @@ -157,7 +163,16 @@ private async Task RunCopyContentLocal(SharedActionsGroup sharedActionsGroup, Ha // For full copy, the transferred volume equals the file size transferredBytes = new FileInfo(sourceFullName).Length; - File.Copy(sourceFullName, destinationFullName, true); + var temporary = destinationFullName + "." + Guid.NewGuid().ToString("N") + ".bstemp"; + try + { + using (var input = LocalPathSafety.OpenRead(sourceFullName)) + using (var output = LocalPathSafety.OpenWrite(temporary, true)) input.CopyTo(output); + _authorization.ValidateDestination(sharedActionsGroup, destinationFullName); + LocalPathSafety.AssertNoLinks(destinationFullName); + LocalPathSafety.Move(temporary, destinationFullName, true); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } await ApplyDatesFromLocalSource(sharedActionsGroup, destinationFullName); } @@ -255,8 +270,10 @@ private async Task RunCopyDateSynchronizationAction(SharedActionsGroup sharedAct foreach (var localTarget in localTargets) { var destinationPath = sharedActionsGroup.GetFullName(localTarget); + using var access = LocalPathSafety.Acquire(destinationPath); cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); if (File.Exists(destinationPath)) { @@ -282,8 +299,10 @@ private async Task RunDeleteSynchronizationAction(SharedActionsGroup sharedActio foreach (var localTarget in localTargets) { var destinationPath = sharedActionsGroup.GetFullName(localTarget); + using var access = LocalPathSafety.Acquire(destinationPath); cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); if (sharedActionsGroup.IsFile && File.Exists(destinationPath)) { @@ -291,7 +310,7 @@ private async Task RunDeleteSynchronizationAction(SharedActionsGroup sharedActio _logger.LogInformation("{Type:l}: deleting {fileInfo}", $"Synchronization.{sharedActionsGroup.Operator}", fileInfo.FullName); - fileInfo.Delete(); + LocalPathSafety.Delete(fileInfo.FullName); } else if (sharedActionsGroup.IsDirectory && Directory.Exists(destinationPath)) { @@ -300,8 +319,7 @@ private async Task RunDeleteSynchronizationAction(SharedActionsGroup sharedActio _logger.LogInformation("{Type:l}: deleting {fileInfo}", $"Synchronization.{sharedActionsGroup.Operator}", directoryInfo.FullName); - var subFilesCount = directoryInfo.GetFiles("*", SearchOption.AllDirectories).Length; - directoryInfo.Delete(subFilesCount == 0); + LocalPathSafety.Delete(directoryInfo.FullName, true); } else { @@ -321,7 +339,9 @@ private async Task RunCreateSynchronizationAction(SharedActionsGroup sharedActio foreach (var localTarget in localTargets) { var destinationPath = sharedActionsGroup.GetFullName(localTarget); + using var access = LocalPathSafety.Acquire(destinationPath); cancellationToken.ThrowIfCancellationRequested(); + _authorization.ValidatePlan(new[] { sharedActionsGroup }); if (sharedActionsGroup.PathIdentity.FileSystemType == FileSystemTypes.Directory) { @@ -332,7 +352,7 @@ private async Task RunCreateSynchronizationAction(SharedActionsGroup sharedActio _logger.LogInformation("{Type:l}: creating {directoryInfo}", $"Synchronization.{sharedActionsGroup.Operator}", directoryInfo.FullName); - directoryInfo.Create(); + LocalPathSafety.CreateDirectory(directoryInfo.FullName); } else { diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionRemoteUploader.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionRemoteUploader.cs index 3dd87ee28..8edaed068 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionRemoteUploader.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationActionRemoteUploader.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Synchronizations; @@ -122,6 +122,8 @@ public async Task UploadForRemote(SharedActionsGroup sharedActionsGroup) try { + sharedActionsGroup.GetSourceFullName(); + _currentMultiUploadZip.AccessValidators.Add(() => sharedActionsGroup.GetSourceFullName()); _currentMultiUploadZip.AddEntry(fileInfo, sharedActionsGroup.ActionsGroupId); } catch (Exception ex) @@ -146,6 +148,7 @@ public async Task UploadForRemote(SharedActionsGroup sharedActionsGroup) $"Synchronization.{sharedActionsGroup.Operator}", localFullName, deltaFullName != null); var fileUploader = _fileUploaderFactory.Build(uploadFullName, sharedFileDefinition); + fileUploader.ValidateAccess = () => sharedActionsGroup.GetSourceFullName(); var uploadTask = RunUploadTask(sharedActionsGroup, fileUploader, () => DeleteDeltaFile(deltaFullName)); @@ -158,7 +161,7 @@ private void DeleteDeltaFile(string? deltaFullName) if (deltaFullName != null) { _logger.LogInformation("Deleting delta file {delta}", deltaFullName); - File.Delete(deltaFullName); + LocalPathSafety.Delete(deltaFullName); } } @@ -232,6 +235,7 @@ private async Task CloseAndUploadCurrentMultiZip() var currentMultiUploadZip = _currentMultiUploadZip; var fileUploader = _fileUploaderFactory.Build(currentMultiUploadZip.MemoryStream, currentMultiUploadZip.SharedFileDefinition); + fileUploader.ValidateAccess = () => { foreach (var validate in currentMultiUploadZip.AccessValidators) validate(); }; var uploadTask = RunUploadTask(currentMultiUploadZip.ActionGroupsIds, fileUploader, () => currentMultiUploadZip.Dispose()); UploadTasks.Add(uploadTask); diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationDataReceiver.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationDataReceiver.cs index dcc456cbd..c6e04ab97 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationDataReceiver.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationDataReceiver.cs @@ -1,4 +1,5 @@ -using ByteSync.Business.Actions.Shared; +using ByteSync.Interfaces.Controls.Inventories; +using ByteSync.Business.Actions.Shared; using ByteSync.Business.Communications; using ByteSync.Interfaces.Controls.Actions; using ByteSync.Interfaces.Controls.Synchronizations; @@ -10,6 +11,8 @@ namespace ByteSync.Services.Synchronizations; public class SynchronizationDataReceiver : ISynchronizationDataReceiver { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ICloudSessionLocalDataManager _cloudSessionLocalDataManager; private readonly ISharedAtomicActionRepository _sharedAtomicActionRepository; private readonly ISharedActionsGroupRepository _sharedActionsGroupRepository; @@ -19,8 +22,9 @@ public class SynchronizationDataReceiver : ISynchronizationDataReceiver public SynchronizationDataReceiver(ICloudSessionLocalDataManager cloudSessionLocalDataManager, ISharedAtomicActionRepository sharedAtomicActionRepository, ISharedActionsGroupRepository sharedActionsGroupRepository, ISynchronizationService synchronizationService, - ISharedActionsGroupOrganizer sharedActionsGroupOrganizer, ISynchronizationDataLogger synchronizationDataLogger) + ISharedActionsGroupOrganizer sharedActionsGroupOrganizer, ISynchronizationDataLogger synchronizationDataLogger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _cloudSessionLocalDataManager = cloudSessionLocalDataManager; _sharedAtomicActionRepository = sharedAtomicActionRepository; _sharedActionsGroupRepository = sharedActionsGroupRepository; @@ -35,11 +39,15 @@ public async Task OnSynchronizationDataFileDownloaded(LocalSharedFile downloadTa var synchronizationDataSaver = new SynchronizationDataSaver(); var synchronizationData = synchronizationDataSaver.Load(synchronizationDataPath); + if (synchronizationData.SessionId != downloadTargetLocalSharedFile.SharedFileDefinition.SessionId || + synchronizationData.Endpoint.ClientInstanceId != downloadTargetLocalSharedFile.SharedFileDefinition.ClientInstanceId) + throw new UnauthorizedAccessException("Synchronization plan sender mismatch"); await SetSynchronizationStartData(synchronizationData); } private async Task SetSynchronizationStartData(SharedSynchronizationStartData sharedSynchronizationStartData) { + _authorization.ValidatePlan(sharedSynchronizationStartData.SharedActionsGroups); _sharedAtomicActionRepository.SetSharedAtomicActions(sharedSynchronizationStartData.SharedAtomicActions); _sharedActionsGroupRepository.SetSharedActionsGroups(sharedSynchronizationStartData.SharedActionsGroups); diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationService.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationService.cs index a1709a1cf..6740dce7b 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationService.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationService.cs @@ -1,4 +1,5 @@ -using System.Reactive.Linq; +using ByteSync.Interfaces.Controls.Inventories; +using System.Reactive.Linq; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Misc; using ByteSync.Business.Sessions; @@ -16,6 +17,8 @@ namespace ByteSync.Services.Synchronizations; public class SynchronizationService : ISynchronizationService { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISessionService _sessionService; private readonly ISessionMemberService _sessionMemberService; private readonly ISynchronizationApiClient _synchronizationApiClient; @@ -26,8 +29,9 @@ public class SynchronizationService : ISynchronizationService public SynchronizationService(ISessionService sessionService, ISessionMemberService sessionMemberService, ISynchronizationApiClient synchronizationApiClient, ISynchronizationLooperFactory synchronizationLooperFactory, ITimeTrackingCache timeTrackingCache, - ILogger logger) + ILogger logger, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sessionService = sessionService; _sessionMemberService = sessionMemberService; _synchronizationApiClient = synchronizationApiClient; @@ -130,6 +134,7 @@ public async Task OnSynchronizationStarted(Synchronization synchronization) public Task OnSynchronizationDataTransmitted(SharedSynchronizationStartData sharedSynchronizationStartData) { + _authorization.ValidatePlan(sharedSynchronizationStartData.SharedActionsGroups); SynchronizationProcessData.TotalVolumeToProcess = sharedSynchronizationStartData.TotalVolumeToProcess; SynchronizationProcessData.TotalActionsToProcess = sharedSynchronizationStartData.TotalAtomicActionsToProcess; diff --git a/src/ByteSync.Client/Services/Synchronizations/SynchronizationStartFactory.cs b/src/ByteSync.Client/Services/Synchronizations/SynchronizationStartFactory.cs index f2fad6a4a..955bf4cd1 100644 --- a/src/ByteSync.Client/Services/Synchronizations/SynchronizationStartFactory.cs +++ b/src/ByteSync.Client/Services/Synchronizations/SynchronizationStartFactory.cs @@ -1,4 +1,5 @@ -using ByteSync.Business.Actions.Shared; +using ByteSync.Interfaces.Controls.Inventories; +using ByteSync.Business.Actions.Shared; using ByteSync.Interfaces.Controls.Actions; using ByteSync.Interfaces.Controls.Synchronizations; using ByteSync.Interfaces.Repositories; @@ -9,6 +10,8 @@ namespace ByteSync.Services.Synchronizations; public class SynchronizationStartFactory : ISynchronizationStartFactory { + private readonly ILocalSourceAuthorizationService _authorization; + private readonly ISharedAtomicActionComputer _sharedAtomicActionComputer; private readonly ISynchronizationRulesService _synchronizationRulesService; private readonly ISharedActionsGroupComputer _sharedActionsGroupComputer; @@ -20,8 +23,9 @@ public class SynchronizationStartFactory : ISynchronizationStartFactory public SynchronizationStartFactory(ISharedAtomicActionComputer sharedAtomicActionComputer, ISynchronizationRulesService synchronizationRulesService, ISharedActionsGroupComputer sharedActionsGroupComputer, ISessionService sessionService, IConnectionService connectionService, ISharedActionsGroupOrganizer sharedActionsGroupOrganizer, - ISharedActionsGroupRepository sharedActionsGroupRepository) + ISharedActionsGroupRepository sharedActionsGroupRepository, ILocalSourceAuthorizationService authorization) { + _authorization = authorization; _sharedAtomicActionComputer = sharedAtomicActionComputer; _synchronizationRulesService = synchronizationRulesService; _sharedActionsGroupComputer = sharedActionsGroupComputer; @@ -39,6 +43,7 @@ public async Task PrepareSharedData() var sharedActionsGroups = _sharedActionsGroupRepository.Elements.ToList(); + _authorization.ValidatePlan(sharedActionsGroups); await _sharedActionsGroupOrganizer.OrganizeSharedActionGroups(); var looseSynchronizationRules = _synchronizationRulesService.GetLooseSynchronizationRules(); diff --git a/src/ByteSync.Client/Services/Synchronizations/TemporaryFileManager.cs b/src/ByteSync.Client/Services/Synchronizations/TemporaryFileManager.cs index c73f7d294..62d053d85 100644 --- a/src/ByteSync.Client/Services/Synchronizations/TemporaryFileManager.cs +++ b/src/ByteSync.Client/Services/Synchronizations/TemporaryFileManager.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using ByteSync.Interfaces.Controls.Synchronizations; namespace ByteSync.Services.Synchronizations; @@ -10,10 +10,10 @@ public class TemporaryFileManager : ITemporaryFileManager public TemporaryFileManager(string destinationFullName, ILogger logger) { _logger = logger; - + Reset(destinationFullName); } - + private void Reset(string destinationFullName) { DestinationFullName = destinationFullName; @@ -29,13 +29,13 @@ private void Reset(string destinationFullName) } public string DestinationFullName { get; set; } = null!; - + public string? DestinationTemporaryPath { get; set; } - + public string? PreviousFileTemporaryPath { get; set; } - + public bool HasValidationStarted { get; set; } - + public bool PreviousFileExistsBeforeValidation { get; set; } public bool WasPreviousFileMovedToTemp { get; set; } @@ -53,43 +53,34 @@ public string GetDestinationTemporaryPath() private string GetTemporaryPath() { - var cpt = 0; - var temporaryPath = DestinationFullName + $".bstemp_t{cpt}$"; - - while (File.Exists(temporaryPath)) - { - cpt += 1; - temporaryPath = DestinationFullName + $".bstemp_t{cpt}$"; - } - - return temporaryPath; + return DestinationFullName + "." + Guid.NewGuid().ToString("N") + ".bstemp"; } public void ValidateTemporaryFile() { HasValidationStarted = true; - + // Rename the existing file to “.bstemp_t$” if (File.Exists(DestinationFullName)) { PreviousFileExistsBeforeValidation = true; - + PreviousFileTemporaryPath = GetTemporaryPath(); - File.Move(DestinationFullName, PreviousFileTemporaryPath); - + LocalPathSafety.Move(DestinationFullName, PreviousFileTemporaryPath); + WasPreviousFileMovedToTemp = true; } // Rename the merged file to its final name - File.Move(DestinationTemporaryPath!, DestinationFullName); - + LocalPathSafety.Move(DestinationTemporaryPath!, DestinationFullName); + WasNewFileMovedFromTemp = true; if (PreviousFileExistsBeforeValidation) { // The old file is deleted - File.Delete(PreviousFileTemporaryPath!); - + LocalPathSafety.Delete(PreviousFileTemporaryPath!); + WasPreviousFileDeleted = true; } } @@ -98,7 +89,7 @@ public void TryRevertOnError(Exception exception) { try { - _logger.LogWarning("An exception has occurred during validation operations on file {file}: {type} - {message}. Trying to revert operation", + _logger.LogWarning("An exception has occurred during validation operations on file {file}: {type} - {message}. Trying to revert operation", DestinationFullName, exception.GetType().Name, exception.Message); if (!HasValidationStarted) { @@ -106,7 +97,7 @@ public void TryRevertOnError(Exception exception) if (File.Exists(DestinationTemporaryPath)) { _logger.LogWarning("Deleting {file}", DestinationTemporaryPath); - File.Delete(DestinationTemporaryPath); + LocalPathSafety.Delete(DestinationTemporaryPath); } else { @@ -125,7 +116,7 @@ public void TryRevertOnError(Exception exception) _logger.LogWarning("nothing seems to be undone here"); } } - else + else { // We go back from the end to the beginning if (WasPreviousFileDeleted) @@ -140,7 +131,7 @@ public void TryRevertOnError(Exception exception) else if (WasPreviousFileMovedToTemp) { _logger.LogWarning("The previous version of the file may still exist at location {previous}, " + - "while the new version of the file may be found at location {new}", + "while the new version of the file may be found at location {new}", PreviousFileTemporaryPath, DestinationTemporaryPath); } else @@ -152,7 +143,7 @@ public void TryRevertOnError(Exception exception) if (File.Exists(DestinationTemporaryPath)) { _logger.LogWarning("Deleting {file}", DestinationTemporaryPath); - File.Delete(DestinationTemporaryPath); + LocalPathSafety.Delete(DestinationTemporaryPath); } else { @@ -166,4 +157,4 @@ public void TryRevertOnError(Exception exception) _logger.LogError(ex, "A new exception has occurred, while trying to undo the effects on file {file}", DestinationFullName); } } -} \ No newline at end of file +} diff --git a/src/ByteSync.Common/Business/Auth/AuthenticationChallenge.cs b/src/ByteSync.Common/Business/Auth/AuthenticationChallenge.cs new file mode 100644 index 000000000..d9987653b --- /dev/null +++ b/src/ByteSync.Common/Business/Auth/AuthenticationChallenge.cs @@ -0,0 +1,10 @@ +using System; + +namespace ByteSync.Common.Business.Auth; + +public class AuthenticationChallenge +{ + public string Id { get; set; } = ""; + public string Nonce { get; set; } = ""; + public DateTimeOffset ExpiresAt { get; set; } +} diff --git a/src/ByteSync.Common/Business/Auth/AuthenticationProtocol.cs b/src/ByteSync.Common/Business/Auth/AuthenticationProtocol.cs new file mode 100644 index 000000000..49b55727c --- /dev/null +++ b/src/ByteSync.Common/Business/Auth/AuthenticationProtocol.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using ByteSync.Common.Business.Versions; + +namespace ByteSync.Common.Business.Auth; + +public static class AuthenticationProtocol +{ + public const int Epoch = 1; + public const string Audience = "ByteSync.Relay"; + + public static string GetIdentity(byte[] publicKey) + { + using var rsa = RSA.Create(); + rsa.ImportRSAPublicKey(publicKey, out var read); + if (read != publicKey.Length || rsa.KeySize < 2048 || rsa.KeySize > 8192) + throw new CryptographicException("Invalid public key"); + return Convert.ToHexString(SHA256.HashData(rsa.ExportSubjectPublicKeyInfo())); + } + + public static bool IsInstanceOf(string? instanceId, string identity) + { + return identity.Length == 64 && identity.All(c => c is >= '0' and <= '9' or >= 'A' and <= 'F') && + instanceId != null && instanceId.Length == identity.Length + 37 && + instanceId.StartsWith(identity + "_", StringComparison.Ordinal) && + Guid.TryParseExact(instanceId.Substring(identity.Length + 1), "D", out _); + } + + public static byte[] GetMessage(LoginData login, AuthenticationChallenge challenge) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, true); + writer.Write("ByteSync.Login"); + writer.Write(Epoch); + writer.Write(Audience); + writer.Write(ProtocolVersion.CURRENT); + writer.Write(challenge.Id); + writer.Write(challenge.Nonce); + writer.Write(challenge.ExpiresAt.UtcTicks); + writer.Write(login.Identity); + writer.Write(login.ClientInstanceId); + writer.Write(login.Version); + writer.Write((int)(login.OsPlatform ?? 0)); + return stream.ToArray(); + } +} diff --git a/src/ByteSync.Common/Business/Auth/InitialConnectionStatus.cs b/src/ByteSync.Common/Business/Auth/InitialConnectionStatus.cs index 11caffc93..14781e020 100644 --- a/src/ByteSync.Common/Business/Auth/InitialConnectionStatus.cs +++ b/src/ByteSync.Common/Business/Auth/InitialConnectionStatus.cs @@ -7,6 +7,7 @@ public enum InitialConnectionStatus UndefinedClientId = 3, UndefinedClientInstanceId = 4, UnknownOsPlatform = 5, + InvalidProof = 6, ClientAlreadyConnected = 10, UnknownError = 11, -} \ No newline at end of file +} diff --git a/src/ByteSync.Common/Business/Auth/LoginData.cs b/src/ByteSync.Common/Business/Auth/LoginData.cs index 0e8a13205..e8f30adbe 100644 --- a/src/ByteSync.Common/Business/Auth/LoginData.cs +++ b/src/ByteSync.Common/Business/Auth/LoginData.cs @@ -4,6 +4,13 @@ namespace ByteSync.Common.Business.Auth; public class LoginData { + public int AuthenticationEpoch { get; set; } + public int ProtocolVersion { get; set; } + public string Identity { get; set; } = ""; + public byte[] PublicKey { get; set; } = []; + public string ChallengeId { get; set; } = ""; + public byte[] Signature { get; set; } = []; + public string ClientId { get; set; } public string ClientInstanceId { get; set; } @@ -11,4 +18,4 @@ public class LoginData public string Version { get; set; } public OSPlatforms? OsPlatform { get; set; } -} \ No newline at end of file +} diff --git a/src/ByteSync.Common/Business/Profiles/CloudSessionProfileSlot.cs b/src/ByteSync.Common/Business/Profiles/CloudSessionProfileSlot.cs index 03db5b354..74452904d 100644 --- a/src/ByteSync.Common/Business/Profiles/CloudSessionProfileSlot.cs +++ b/src/ByteSync.Common/Business/Profiles/CloudSessionProfileSlot.cs @@ -1,7 +1,8 @@ -namespace ByteSync.Common.Business.Profiles; +namespace ByteSync.Common.Business.Profiles; public class CloudSessionProfileSlot { public string ProfileClientId { get; set; } = null!; public string ClientId { get; set; } = null!; + public string? OriginalClientInstanceId { get; set; } } \ No newline at end of file diff --git a/src/ByteSync.Common/Business/SharedFiles/SharedFileDefinition.cs b/src/ByteSync.Common/Business/SharedFiles/SharedFileDefinition.cs index 2ce67fbbf..b1820f6b6 100644 --- a/src/ByteSync.Common/Business/SharedFiles/SharedFileDefinition.cs +++ b/src/ByteSync.Common/Business/SharedFiles/SharedFileDefinition.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using ByteSync.Common.Business.EndPoints; using ByteSync.Common.Helpers; @@ -16,6 +16,8 @@ public SharedFileDefinition() public string Id { get; set; } + public string? StorageObjectId { get; set; } + public string SessionId { get; set; } public string ClientInstanceId { get; set; } diff --git a/src/ByteSync.Common/Business/Versions/ProtocolVersion.cs b/src/ByteSync.Common/Business/Versions/ProtocolVersion.cs index 3e8f86083..42c577aff 100644 --- a/src/ByteSync.Common/Business/Versions/ProtocolVersion.cs +++ b/src/ByteSync.Common/Business/Versions/ProtocolVersion.cs @@ -5,9 +5,10 @@ public static class ProtocolVersion public const int V1 = 1; public const int V2 = 2; - public const int CURRENT = V2; + public const int V3 = 3; + public const int CURRENT = V3; - public const int MIN_SUPPORTED = V2; + public const int MIN_SUPPORTED = V3; public static bool IsCompatible(int otherVersion) { @@ -18,4 +19,4 @@ public static bool IsCompatible(int otherVersion) return otherVersion == CURRENT; } -} \ No newline at end of file +} diff --git a/src/ByteSync.Functions/Helpers/Middlewares/ErrorHandlingMiddleware.cs b/src/ByteSync.Functions/Helpers/Middlewares/ErrorHandlingMiddleware.cs index 02f99f80a..9a33c4b53 100644 --- a/src/ByteSync.Functions/Helpers/Middlewares/ErrorHandlingMiddleware.cs +++ b/src/ByteSync.Functions/Helpers/Middlewares/ErrorHandlingMiddleware.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using ByteSync.ServerCommon.Exceptions; using Microsoft.ApplicationInsights; using Microsoft.Azure.Functions.Worker; @@ -25,6 +25,18 @@ public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next { await next(context); } + catch (UnauthorizedAccessException) + { + var request = await context.GetHttpRequestDataAsync(); + if (request == null) throw; + PrepareResponse(context, request, HttpStatusCode.Forbidden); + } + catch (System.Security.Cryptography.CryptographicException) + { + var request = await context.GetHttpRequestDataAsync(); + if (request == null) throw; + PrepareResponse(context, request, HttpStatusCode.BadRequest); + } catch (BadRequestException ex) { _telemetryClient.TrackException(ex); diff --git a/src/ByteSync.Functions/Helpers/Middlewares/JwtMiddleware.cs b/src/ByteSync.Functions/Helpers/Middlewares/JwtMiddleware.cs index 247d25744..c488d6eb0 100644 --- a/src/ByteSync.Functions/Helpers/Middlewares/JwtMiddleware.cs +++ b/src/ByteSync.Functions/Helpers/Middlewares/JwtMiddleware.cs @@ -1,4 +1,5 @@ -using System.IdentityModel.Tokens.Jwt; +using System.IdentityModel.Tokens.Jwt; +using ByteSync.Common.Business.Auth; using System.Net; using System.Security.Claims; using System.Text; @@ -28,7 +29,7 @@ public JwtMiddleware(IOptions appSettings, IClientsRepository clien { var loginFunctionEntryPoint = GetEntryPoint(nameof(AuthFunction.Login)); var getAnnouncementsFunctionEntryPoint = GetEntryPoint(nameof(AnnouncementFunction.GetAnnouncements)); - _allowedAnonymousFunctionEntryPoints = [loginFunctionEntryPoint, getAnnouncementsFunctionEntryPoint]; + _allowedAnonymousFunctionEntryPoints = [loginFunctionEntryPoint, getAnnouncementsFunctionEntryPoint, GetEntryPoint(nameof(AuthFunction.Challenge)), GetEntryPoint(nameof(AuthFunction.RefreshTokens)), GetEntryPoint(nameof(ByteSync.Functions.SignalR.SignalREntryFunction.OnConnected)), GetEntryPoint(nameof(ByteSync.Functions.SignalR.SignalREntryFunction.OnDisconnected))]; _secret = appSettings.Value.Secret; _clientsRepository = clientsRepository; @@ -148,7 +149,9 @@ private TokenValidationParameters BuildTokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), - ValidateIssuer = false, + ValidateIssuer = true, + ValidateLifetime = true, + ValidAlgorithms = [SecurityAlgorithms.HmacSha256], ValidIssuer = AuthConstants.ISSUER, ValidateAudience = true, ValidAudience = AuthConstants.AUDIENCE, @@ -172,6 +175,8 @@ private TokenValidationParameters BuildTokenValidationParameters() throw new SecurityTokenExpiredException("Client is null"); } + ByteSync.ServerCommon.Security.ClientAuthentication.ValidateClaims(client, claims); + return client; } diff --git a/src/ByteSync.Functions/Http/AuthFunction.cs b/src/ByteSync.Functions/Http/AuthFunction.cs index 0f8f2af8c..08e9d4650 100644 --- a/src/ByteSync.Functions/Http/AuthFunction.cs +++ b/src/ByteSync.Functions/Http/AuthFunction.cs @@ -1,4 +1,5 @@ using System.Net; +using Microsoft.Extensions.DependencyInjection; using ByteSync.Common.Business.Auth; using ByteSync.Functions.Helpers.Misc; using ByteSync.ServerCommon.Commands.Authentication; @@ -18,9 +19,23 @@ public AuthFunction(IMediator mediator) _mediator = mediator; } + [AllowAnonymous] + [Function("AuthenticationChallenge")] + public async Task Challenge( + [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth/challenge")] HttpRequestData req, + FunctionContext context) + { + var login = await FunctionHelper.DeserializeRequestBody(req); + var service = context.InstanceServices.GetRequiredService(); + var challenge = await service.Create(login); + var response = req.CreateResponse(); + await response.WriteAsJsonAsync(challenge); + return response; + } + [AllowAnonymous] [Function("Login")] - public async Task Login([HttpTrigger(AuthorizationLevel.Anonymous, "post", "get", Route = "auth/login")] HttpRequestData req, + public async Task Login([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth/login")] HttpRequestData req, FunctionContext executionContext) { var loginData = await FunctionHelper.DeserializeRequestBody(req); @@ -42,7 +57,7 @@ public async Task Login([HttpTrigger(AuthorizationLevel.Anonym } [Function("RefreshTokens")] - public async Task RefreshTokens([HttpTrigger(AuthorizationLevel.Anonymous, "post", "get", Route = "auth/refreshTokens")] HttpRequestData req, + public async Task RefreshTokens([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "auth/refreshTokens")] HttpRequestData req, FunctionContext executionContext) { var refreshTokensData = await FunctionHelper.DeserializeRequestBody(req); @@ -63,4 +78,4 @@ public async Task RefreshTokens([HttpTrigger(AuthorizationLeve return response; } -} \ No newline at end of file +} diff --git a/src/ByteSync.Functions/Http/CloudSessionFunction.cs b/src/ByteSync.Functions/Http/CloudSessionFunction.cs index 2b92eb058..0e15c1af2 100644 --- a/src/ByteSync.Functions/Http/CloudSessionFunction.cs +++ b/src/ByteSync.Functions/Http/CloudSessionFunction.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using ByteSync.Common.Business.Sessions; using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.Functions.Helpers.Misc; @@ -35,6 +35,19 @@ public async Task Create([HttpTrigger(AuthorizationLevel.Anony return response; } + [Function("BeginJoinSessionFunction")] + public async Task BeginJoin( + [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "session/{sessionId}/beginJoin")] HttpRequestData req, + FunctionContext context, string sessionId) + { + var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.SessionId != sessionId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Session route mismatch"); + var result = await _mediator.Send(new BeginJoinSessionRequest(FunctionHelper.GetClientFromContext(context), parameters)); + var response = req.CreateResponse(); + await response.WriteAsJsonAsync(result); + return response; + } + [Function("AskPasswordExchangeKeyFunction")] public async Task AskPasswordExchangeKey( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "session/{sessionId}/askPasswordExchangeKey")] HttpRequestData req, @@ -42,6 +55,7 @@ public async Task AskPasswordExchangeKey( { var client = FunctionHelper.GetClientFromContext(executionContext); var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.SessionId != sessionId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Session route mismatch"); var result = await _mediator.Send(new AskPasswordExchangeKeyRequest(client, parameters), executionContext.CancellationToken); var response = req.CreateResponse(); await response.WriteAsJsonAsync(result); @@ -54,7 +68,8 @@ public async Task ValidateJoinCloudSession( FunctionContext executionContext, string sessionId) { var parameters = await FunctionHelper.DeserializeRequestBody(req); - await _mediator.Send(new ValidateJoinCloudSessionRequest(parameters)); + if (parameters.SessionId != sessionId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Session route mismatch"); + await _mediator.Send(new ValidateJoinCloudSessionRequest(parameters, FunctionHelper.GetClientFromContext(executionContext))); var response = req.CreateResponse(HttpStatusCode.OK); return response; } @@ -67,6 +82,7 @@ public async Task FinalizeJoinCloudSession( var client = FunctionHelper.GetClientFromContext(executionContext); var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.SessionId != sessionId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Session route mismatch"); var request = new FinalizeJoinCloudSessionRequest(parameters, client); var result = await _mediator.Send(request); @@ -84,6 +100,7 @@ public async Task AskJoinCloudSession( { var client = FunctionHelper.GetClientFromContext(executionContext); var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.SessionId != sessionId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Session route mismatch"); var result = await _mediator.Send(new AskJoinCloudSessionRequest(client, parameters)); var response = req.CreateResponse(); await response.WriteAsJsonAsync(result); @@ -97,6 +114,7 @@ public async Task GiveCloudSessionPasswordExchangeKey( { var client = FunctionHelper.GetClientFromContext(executionContext); var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.SessionId != sessionId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Session route mismatch"); await _mediator.Send(new GiveCloudSessionPasswordExchangeKeyRequest(client, parameters)); var response = req.CreateResponse(HttpStatusCode.OK); return response; diff --git a/src/ByteSync.Functions/Http/CloudSessionProfileFunction.cs b/src/ByteSync.Functions/Http/CloudSessionProfileFunction.cs index f29b4124a..e9a7307b5 100644 --- a/src/ByteSync.Functions/Http/CloudSessionProfileFunction.cs +++ b/src/ByteSync.Functions/Http/CloudSessionProfileFunction.cs @@ -43,6 +43,7 @@ public async Task GetCloudSessionProfileData( { var client = FunctionHelper.GetClientFromContext(executionContext); var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.CloudSessionProfileId != cloudSessionProfileId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Profile route mismatch"); var result = await _cloudSessionProfileService.GetCloudSessionProfileData(parameters, client); @@ -59,6 +60,7 @@ public async Task GetProfileDetailsPassword([HttpTrigger( { var client = FunctionHelper.GetClientFromContext(executionContext); var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.CloudSessionProfileId != cloudSessionProfileId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Profile route mismatch"); var result = await _cloudSessionProfileService.GetProfileDetailsPassword(parameters, client); @@ -75,6 +77,7 @@ public async Task DeleteCloudSessionProfile([HttpTrigger( { var client = FunctionHelper.GetClientFromContext(executionContext); var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.CloudSessionProfileId != cloudSessionProfileId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Profile route mismatch"); var result = await _cloudSessionProfileService.DeleteCloudSessionProfile(parameters, client); diff --git a/src/ByteSync.Functions/Http/InventoryFunction.cs b/src/ByteSync.Functions/Http/InventoryFunction.cs index bff05380d..ee114fb7d 100644 --- a/src/ByteSync.Functions/Http/InventoryFunction.cs +++ b/src/ByteSync.Functions/Http/InventoryFunction.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using ByteSync.Common.Business.Inventories; @@ -88,7 +88,7 @@ public async Task GetDataSources( string clientInstanceId, string dataNodeId) { - var request = new GetDataSourcesRequest(sessionId, clientInstanceId, dataNodeId); + var request = new GetDataSourcesRequest(sessionId, clientInstanceId, dataNodeId, FunctionHelper.GetClientFromContext(executionContext)); var result = await _mediator.Send(request); var response = req.CreateResponse(); @@ -145,7 +145,7 @@ public async Task GetDataNodes( string sessionId, string clientInstanceId) { - var request = new GetDataNodesRequest(sessionId, clientInstanceId); + var request = new GetDataNodesRequest(sessionId, clientInstanceId, FunctionHelper.GetClientFromContext(executionContext)); var result = await _mediator.Send(request); var response = req.CreateResponse(); diff --git a/src/ByteSync.Functions/Http/LobbyFunction.cs b/src/ByteSync.Functions/Http/LobbyFunction.cs index a8024a338..dec53ec12 100644 --- a/src/ByteSync.Functions/Http/LobbyFunction.cs +++ b/src/ByteSync.Functions/Http/LobbyFunction.cs @@ -31,6 +31,7 @@ public async Task JoinLobby( var client = FunctionHelper.GetClientFromContext(executionContext); var parameters = await FunctionHelper.DeserializeRequestBody(req); + if (parameters.CloudSessionProfileId != cloudSessionProfileId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Profile route mismatch"); var request = new TryJoinLobbyRequest(parameters, client); var result = await _mediator.Send(request); @@ -50,6 +51,7 @@ public async Task SendLobbyCloudSessionCredentials( var client = FunctionHelper.GetClientFromContext(executionContext); var lobbyCloudSessionCredentials = await FunctionHelper.DeserializeRequestBody(req); + if (lobbyCloudSessionCredentials.LobbyId != lobbyId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Lobby route mismatch"); await _lobbyService.SendLobbyCloudSessionCredentials(lobbyCloudSessionCredentials, client); var response = req.CreateResponse(); @@ -86,6 +88,7 @@ public async Task SendLobbyCheckInfos( var client = FunctionHelper.GetClientFromContext(executionContext); var lobbyCheckInfo = await FunctionHelper.DeserializeRequestBody(req); + if (lobbyCheckInfo.LobbyId != lobbyId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Lobby route mismatch"); await _lobbyService.SendLobbyCheckInfos(lobbyCheckInfo, client); var response = req.CreateResponse(); diff --git a/src/ByteSync.Functions/Http/SessionMemberFunction.cs b/src/ByteSync.Functions/Http/SessionMemberFunction.cs index 1c739c7c4..351c7e585 100644 --- a/src/ByteSync.Functions/Http/SessionMemberFunction.cs +++ b/src/ByteSync.Functions/Http/SessionMemberFunction.cs @@ -22,7 +22,7 @@ public async Task GetMembersInstanceIds( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "session/{sessionId}/members/InstanceIds")] HttpRequestData req, FunctionContext executionContext, string sessionId) { - var result = await _mediator.Send(new GetMembersInstanceIdsRequest(sessionId)); + var result = await _mediator.Send(new GetMembersInstanceIdsRequest(sessionId, FunctionHelper.GetClientFromContext(executionContext))); var response = req.CreateResponse(); await response.WriteAsJsonAsync(result); return response; @@ -33,7 +33,7 @@ public async Task GetMembers( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "session/{sessionId}/members")] HttpRequestData req, FunctionContext executionContext, string sessionId) { - var result = await _mediator.Send(new GetMembersRequest(sessionId)); + var result = await _mediator.Send(new GetMembersRequest(sessionId, FunctionHelper.GetClientFromContext(executionContext))); var response = req.CreateResponse(); await response.WriteAsJsonAsync(result); return response; @@ -49,6 +49,7 @@ public async Task SetGeneralStatus( var client = FunctionHelper.GetClientFromContext(executionContext); var generalStatusParameters = await FunctionHelper.DeserializeRequestBody(req); + if (generalStatusParameters.SessionId != sessionId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Session route mismatch"); var request = new SetGeneralStatusRequest(client, generalStatusParameters); var result = await _mediator.Send(request); diff --git a/src/ByteSync.Functions/Http/SynchronizationFunction.cs b/src/ByteSync.Functions/Http/SynchronizationFunction.cs index 13be32c2f..ef11caa97 100644 --- a/src/ByteSync.Functions/Http/SynchronizationFunction.cs +++ b/src/ByteSync.Functions/Http/SynchronizationFunction.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using ByteSync.Common.Business.Synchronizations; using ByteSync.Functions.Helpers.Misc; using ByteSync.ServerCommon.Commands.Synchronizations; @@ -27,6 +27,7 @@ public async Task StartSynchronization( var client = FunctionHelper.GetClientFromContext(executionContext); var synchronizationStartRequest = await FunctionHelper.DeserializeRequestBody(req); + if (synchronizationStartRequest.SessionId != sessionId) throw new ByteSync.ServerCommon.Exceptions.BadRequestException("Session route mismatch"); var request = new StartSynchronizationRequest(sessionId, client, synchronizationStartRequest.ActionsGroupDefinitions); await _mediator.Send(request); diff --git a/src/ByteSync.Functions/Program.cs b/src/ByteSync.Functions/Program.cs index 11165d844..94fa14abf 100644 --- a/src/ByteSync.Functions/Program.cs +++ b/src/ByteSync.Functions/Program.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Text.Json; using Autofac; using Autofac.Extensions.DependencyInjection; @@ -105,7 +105,11 @@ services.AddClaimAuthorization(); services.AddJwtAuthentication(appSettings!.Secret); - services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly(), typeof(AddDataSourceRequest).Assembly)); + services.AddMediatR(cfg => + { + cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly(), typeof(AddDataSourceRequest).Assembly); + cfg.AddOpenBehavior(typeof(ByteSync.ServerCommon.Security.SessionAuthorizationBehavior<,>)); + }); }) .Build(); diff --git a/src/ByteSync.Functions/SignalR/SignalREntryFunction.cs b/src/ByteSync.Functions/SignalR/SignalREntryFunction.cs index d953a1c17..961540545 100644 --- a/src/ByteSync.Functions/SignalR/SignalREntryFunction.cs +++ b/src/ByteSync.Functions/SignalR/SignalREntryFunction.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; using Azure.Core.Serialization; using ByteSync.Common.Interfaces.Hub; using ByteSync.Functions.Helpers.Misc; @@ -36,11 +36,11 @@ public async Task Negotiate([HttpTrigger(AuthorizationLevel.An var client = FunctionHelper.GetClientFromContext(executionContext); - var negotiateResponse = await _hubContext.NegotiateAsync(new() { UserId = client.ClientInstanceId }); + var negotiateResponse = await _hubContext.NegotiateAsync(new() { UserId = $"{ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch}:{client.ClientInstanceId}" }); if (negotiateResponse == null || string.IsNullOrEmpty(negotiateResponse.Url) || string.IsNullOrEmpty(negotiateResponse.AccessToken)) { - _logger.LogWarning("Negotiate response is null or invalid {@negotiateResponse}", negotiateResponse); + _logger.LogWarning("Negotiate response is null or invalid"); return req.CreateResponse(System.Net.HttpStatusCode.InternalServerError); } @@ -69,9 +69,10 @@ public async Task OnConnected([SignalRTrigger(HUB_NAME, "connections", "connecte { try { - await _clientsService.OnClientConnected(invocationContext.UserId, invocationContext.ConnectionId); + var prefix = $"{ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch}:"; + if (!invocationContext.UserId.StartsWith(prefix, StringComparison.Ordinal)) return; + await _clientsService.OnClientConnected(invocationContext.UserId[prefix.Length..], invocationContext.ConnectionId); - invocationContext.Headers.TryGetValue("Authorization", out var auth); _logger.LogInformation("{InvocationContextConnectionId} has connected", invocationContext.ConnectionId); } catch (Exception ex) diff --git a/src/ByteSync.ServerCommon/Business/Auth/AuthConstants.cs b/src/ByteSync.ServerCommon/Business/Auth/AuthConstants.cs index f15f5ed67..058b508b3 100644 --- a/src/ByteSync.ServerCommon/Business/Auth/AuthConstants.cs +++ b/src/ByteSync.ServerCommon/Business/Auth/AuthConstants.cs @@ -11,7 +11,9 @@ public static class AuthConstants public const string CLAIM_CLIENT_ID = "clientId"; public const string CLAIM_CLIENT_INSTANCE_ID = "clientInstanceId"; public const string CLAIM_VERSION = "version"; + public const string CLAIM_IDENTITY = "identity"; + public const string CLAIM_AUTHENTICATION_EPOCH = "authenticationEpoch"; public const string CLAIM_OS_PLATFORM = "osPlatform"; public const string FUNCTION_CONTEXT_CLIENT = "Client"; -} \ No newline at end of file +} diff --git a/src/ByteSync.ServerCommon/Business/Auth/Client.cs b/src/ByteSync.ServerCommon/Business/Auth/Client.cs index 0c98c7afd..92ae27448 100644 --- a/src/ByteSync.ServerCommon/Business/Auth/Client.cs +++ b/src/ByteSync.ServerCommon/Business/Auth/Client.cs @@ -11,6 +11,9 @@ public enum ClientStatuses public class Client { + public string? Identity { get; set; } + public int AuthenticationEpoch { get; set; } + public Client() { @@ -113,4 +116,4 @@ public void SetDisconnected() Status = ClientStatuses.Disconnected; DisconnectedOn = DateTimeOffset.UtcNow; } -} \ No newline at end of file +} diff --git a/src/ByteSync.ServerCommon/Business/Auth/RefreshToken.cs b/src/ByteSync.ServerCommon/Business/Auth/RefreshToken.cs index 96a713fae..2b2ce7d26 100644 --- a/src/ByteSync.ServerCommon/Business/Auth/RefreshToken.cs +++ b/src/ByteSync.ServerCommon/Business/Auth/RefreshToken.cs @@ -2,6 +2,8 @@ public class RefreshToken : ICloneable { + public int AuthenticationEpoch { get; set; } + public RefreshToken() { @@ -68,4 +70,4 @@ public void Revoke(RefreshToken newRefreshToken, string ipAddress) RevokedByIp = ipAddress; ReplacedByToken = newRefreshToken.Token; } -} \ No newline at end of file +} diff --git a/src/ByteSync.ServerCommon/Business/Sessions/CloudSessionData.cs b/src/ByteSync.ServerCommon/Business/Sessions/CloudSessionData.cs index 808229e8e..41df61c41 100644 --- a/src/ByteSync.ServerCommon/Business/Sessions/CloudSessionData.cs +++ b/src/ByteSync.ServerCommon/Business/Sessions/CloudSessionData.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.EndPoints; +using ByteSync.Common.Business.EndPoints; using ByteSync.Common.Business.Sessions; using ByteSync.Common.Business.Sessions.Cloud; using ByteSync.ServerCommon.Business.Auth; @@ -7,6 +7,8 @@ namespace ByteSync.ServerCommon.Business.Sessions; public class CloudSessionData { + public int AuthenticationEpoch { get; set; } + public CloudSessionData() { SessionMembers = new List(); @@ -21,6 +23,7 @@ public CloudSessionData(string? lobbyId, EncryptedSessionSettings sessionSetting SessionSettings = sessionSettings; CreatorInstanceId = creator.ClientInstanceId; + AuthenticationEpoch = creator.AuthenticationEpoch; } public string SessionId { get; set; } = null!; diff --git a/src/ByteSync.ServerCommon/Business/Sessions/SessionMemberData.cs b/src/ByteSync.ServerCommon/Business/Sessions/SessionMemberData.cs index cc095db34..ed56c195b 100644 --- a/src/ByteSync.ServerCommon/Business/Sessions/SessionMemberData.cs +++ b/src/ByteSync.ServerCommon/Business/Sessions/SessionMemberData.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.EndPoints; +using ByteSync.Common.Business.EndPoints; using ByteSync.Common.Business.Sessions; using ByteSync.ServerCommon.Business.Auth; @@ -17,6 +17,7 @@ public SessionMemberData(Client client, PublicKeyInfo publicKeyInfo, string? pro CloudSessionData cloudSessionData, EncryptedSessionMemberPrivateData? encryptedSessionMemberPrivateData = null) : this(client.ClientInstanceId, client.ClientId, publicKeyInfo, profileClientId, cloudSessionData, encryptedSessionMemberPrivateData) { + Identity = client.Identity; } public SessionMemberData(string clientInstanceId, string clientId, PublicKeyInfo publicKeyInfo, string? profileClientId, @@ -38,6 +39,8 @@ public SessionMemberData(string clientInstanceId, string clientId, PublicKeyInfo public string ClientInstanceId { get; set; } = null!; public string ClientId { get; set; } = null!; + public string? Identity { get; set; } + public DateTimeOffset JoinExpiresAt { get; set; } public PublicKeyInfo PublicKeyInfo { get; set; } = null!; @@ -88,8 +91,9 @@ public override int GetHashCode() return ClientInstanceId.GetHashCode(); } - public bool IsAuthCheckedFor(string joinerInstanceId) + public bool IsAuthCheckedFor(string joinerInstanceId, string? joinerIdentity = null) { - return AuthCheckClientInstanceIds.Contains(joinerInstanceId) || joinerInstanceId.StartsWith(ClientId); + return AuthCheckClientInstanceIds.Contains(joinerInstanceId) || + (Identity != null && Identity == joinerIdentity && ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf(joinerInstanceId, Identity)); } } \ No newline at end of file diff --git a/src/ByteSync.ServerCommon/Commands/Authentication/AuthenticateCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Authentication/AuthenticateCommandHandler.cs index aeb2f1f63..5cb94024f 100644 --- a/src/ByteSync.ServerCommon/Commands/Authentication/AuthenticateCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Authentication/AuthenticateCommandHandler.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Auth; using ByteSync.Common.Business.Misc; using ByteSync.Common.Business.Serials; using ByteSync.Common.Helpers; @@ -7,6 +7,7 @@ using ByteSync.ServerCommon.Interfaces.Factories; using ByteSync.ServerCommon.Interfaces.Repositories; using ByteSync.ServerCommon.Interfaces.Services.Clients; +using ByteSync.ServerCommon.Interfaces.Services; using MediatR; namespace ByteSync.ServerCommon.Commands.Authentication; @@ -17,13 +18,15 @@ public class AuthenticateCommandHandler : IRequestHandler Handle(AuthenticateRequest request, CancellationToken cancellationToken) @@ -55,17 +58,26 @@ public async Task Handle(AuthenticateRequest requ return authenticationResponse; } + if (!await _challenges.VerifyAndConsume(request.LoginData)) + return new InitialAuthenticationResponse(InitialConnectionStatus.InvalidProof); + JwtTokens? tokens = null; var result = await _clientsRepository.AddOrUpdate(request.LoginData.ClientInstanceId, client => { if (client == null) { - client = new Client(request.LoginData.ClientId, request.LoginData.ClientInstanceId, + client = new Client(request.LoginData.Identity, request.LoginData.ClientInstanceId, request.LoginData.Version, request.LoginData.OsPlatform!.Value, request.IpAddress); + client.Identity = request.LoginData.Identity; + client.AuthenticationEpoch = AuthenticationProtocol.Epoch; } else { + if (client.Identity != request.LoginData.Identity || client.AuthenticationEpoch != AuthenticationProtocol.Epoch) + return null; client.IpAddress = request.IpAddress; + client.Version = request.LoginData.Version; + client.OsPlatform = request.LoginData.OsPlatform.Value; } tokens = _tokensFactory.BuildTokens(client); @@ -74,6 +86,9 @@ public async Task Handle(AuthenticateRequest requ return client; }); + if (!result.IsSaved || tokens == null) + return new InitialAuthenticationResponse(InitialConnectionStatus.InvalidProof); + BindSerialResponse bindSerialResponse = await BindSerial(result.Element!); var endPoint = _byteSyncEndpointFactory.BuildByteSyncEndpoint(result.Element!, bindSerialResponse.ProductSerialDescription); @@ -112,4 +127,4 @@ public ProductSerialDescription BuildProductSerialDescription(ProductSerial prod return productSerialDescription; } -} \ No newline at end of file +} diff --git a/src/ByteSync.ServerCommon/Commands/Authentication/RefreshTokensCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Authentication/RefreshTokensCommandHandler.cs index 24cabe76c..4d3ad26cd 100644 --- a/src/ByteSync.ServerCommon/Commands/Authentication/RefreshTokensCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Authentication/RefreshTokensCommandHandler.cs @@ -30,7 +30,10 @@ public async Task Handle(RefreshTokensRequest req, Cancel var result = await _clientsRepository.AddOrUpdate(req.RefreshTokensData.ClientInstanceId, client => { - if (client == null || client.RefreshToken == null || !Equals(client.RefreshToken.Token, req.RefreshTokensData.Token)) + if (client == null || client.AuthenticationEpoch != AuthenticationProtocol.Epoch || + !AuthenticationProtocol.IsInstanceOf(client.ClientInstanceId, client.Identity ?? "") || + client.RefreshToken == null || client.RefreshToken.AuthenticationEpoch != AuthenticationProtocol.Epoch || + !client.RefreshToken.IsActive || !Equals(client.RefreshToken.Token, req.RefreshTokensData.Token)) { authenticationResponse = new RefreshTokensResponse(RefreshTokensStatus.RefreshTokenNotFound); return null; diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/AskJoinCloudSessionRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/AskJoinCloudSessionRequest.cs index 17bf113e0..10dce430f 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/AskJoinCloudSessionRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/AskJoinCloudSessionRequest.cs @@ -1,11 +1,14 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class AskJoinCloudSessionRequest : IRequest +public class AskJoinCloudSessionRequest : IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public AskJoinCloudSessionRequest(Client client, AskJoinCloudSessionParameters parameters) { Client = client; diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/AskPasswordExchangeKeyRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/AskPasswordExchangeKeyRequest.cs index f0c190f97..e60affcdb 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/AskPasswordExchangeKeyRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/AskPasswordExchangeKeyRequest.cs @@ -1,11 +1,14 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class AskPasswordExchangeKeyRequest : IRequest +public class AskPasswordExchangeKeyRequest : IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public AskPasswordExchangeKeyRequest(Client client, AskCloudSessionPasswordExchangeKeyParameters parameters) { Client = client; diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/BeginJoinSessionCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/BeginJoinSessionCommandHandler.cs new file mode 100644 index 000000000..29bbd288f --- /dev/null +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/BeginJoinSessionCommandHandler.cs @@ -0,0 +1,18 @@ +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Services; +using MediatR; + +namespace ByteSync.ServerCommon.Commands.CloudSessions; + +public class BeginJoinSessionCommandHandler(ICloudSessionsRepository sessions, ICloudSessionsService service) + : IRequestHandler> +{ + public async Task> Handle(BeginJoinSessionRequest request, CancellationToken cancellationToken) + { + var session = await sessions.Get(request.SessionId) ?? throw new UnauthorizedAccessException(); + if (session.IsSessionActivated || session.IsSessionRemoved || session.SessionMembers.Count is 0 or >= 5) throw new UnauthorizedAccessException(); + await service.PreJoinCloudSession(request.Client, request.Parameters.PublicKeyInfo, request.Parameters.ProfileClientId, + request.SessionId, session.SessionMembers[0].ClientInstanceId); + return session.SessionMembers.Select(m => m.ClientInstanceId).ToList(); + } +} diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/BeginJoinSessionRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/BeginJoinSessionRequest.cs new file mode 100644 index 000000000..3284d6484 --- /dev/null +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/BeginJoinSessionRequest.cs @@ -0,0 +1,11 @@ +using ByteSync.Common.Business.Sessions.Cloud.Connections; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Security; +using MediatR; + +namespace ByteSync.ServerCommon.Commands.CloudSessions; + +public record BeginJoinSessionRequest(Client Client, AskCloudSessionPasswordExchangeKeyParameters Parameters) : IRequest>, ISessionRequest +{ + public string SessionId => Parameters.SessionId; +} diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/FinalizeJoinCloudSessionCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/FinalizeJoinCloudSessionCommandHandler.cs index a5a54fd23..c8d09df59 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/FinalizeJoinCloudSessionCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/FinalizeJoinCloudSessionCommandHandler.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Sessions.Cloud.Connections; +using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.Common.Helpers; using ByteSync.ServerCommon.Business.Sessions; using ByteSync.ServerCommon.Helpers; @@ -36,10 +36,12 @@ public async Task Handle(FinalizeJoinCloudSessionRequ { var parameters = request.FinalizeJoinCloudSessionParameters; var client = request.Client; + if (parameters.JoinerInstanceId != client.ClientInstanceId) throw new UnauthorizedAccessException(); FinalizeJoinSessionStatuses? finalizeJoinSessionStatus = null; SessionMemberData? joiner = null; + await using var sessionLock = await _redisInfrastructureService.AcquireLockAsync(ByteSync.ServerCommon.Entities.EntityType.Session, parameters.SessionId); var transaction = _redisInfrastructureService.OpenTransaction(); var updateResult = await _cloudSessionsRepository.Update(parameters.SessionId, innerCloudSessionData => @@ -53,10 +55,10 @@ public async Task Handle(FinalizeJoinCloudSessionRequ finalizeJoinSessionStatus = FinalizeJoinSessionStatuses.SessionAlreadyActivated; } else if (innerCloudSessionData.SessionMembers - .Count(sm => !sm.IsAuthCheckedFor(parameters.JoinerInstanceId)) > 0) + .Count(sm => !sm.IsAuthCheckedFor(parameters.JoinerInstanceId, client.Identity)) > 0) { var nonAuthCheckedMembers = innerCloudSessionData.SessionMembers - .Where(sm => !sm.IsAuthCheckedFor(parameters.JoinerInstanceId)) + .Where(sm => !sm.IsAuthCheckedFor(parameters.JoinerInstanceId, client.Identity)) .Select(sm => sm.ClientInstanceId) .ToList().JoinToString(","); @@ -72,7 +74,10 @@ public async Task Handle(FinalizeJoinCloudSessionRequ .FirstOrDefault(m => Equals(m.ClientInstanceId, parameters.JoinerInstanceId) && Equals(m.ValidatorInstanceId, parameters.ValidatorInstanceId) && - Equals(m.FinalizationPassword, parameters.FinalizationPassword)); + Equals(m.FinalizationPassword, parameters.FinalizationPassword) && + !string.IsNullOrEmpty(m.FinalizationPassword) && m.Identity == client.Identity && + m.JoinExpiresAt > DateTimeOffset.UtcNow && + innerCloudSessionData.FindMember(parameters.ValidatorInstanceId) != null); if (joiner == null) { @@ -82,6 +87,7 @@ public async Task Handle(FinalizeJoinCloudSessionRequ if (joiner != null && finalizeJoinSessionStatus == null) { + joiner.FinalizationPassword = ""; joiner.EncryptedPrivateData = parameters.EncryptedSessionMemberPrivateData; innerCloudSessionData.SessionMembers.Remove(joiner); @@ -96,7 +102,7 @@ public async Task Handle(FinalizeJoinCloudSessionRequ { return false; } - }, transaction); + }, transaction, sessionLock); if (updateResult.IsWaitingForTransaction) { @@ -104,7 +110,7 @@ public async Task Handle(FinalizeJoinCloudSessionRequ await _clientsGroupsService.AddSessionSubscription(client, parameters.SessionId, transaction); - await transaction.ExecuteAsync(); + if (!await transaction.ExecuteAsync()) throw new InvalidOperationException("Join transaction was not committed"); await _invokeClientsService.SessionGroup(parameters.SessionId).MemberJoinedSession(sessionMemberInfo).ConfigureAwait(false); await _clientsGroupsService.AddToSessionGroup(client, parameters.SessionId).ConfigureAwait(false); diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/FinalizeJoinCloudSessionRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/FinalizeJoinCloudSessionRequest.cs index 2284d214a..223a24a49 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/FinalizeJoinCloudSessionRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/FinalizeJoinCloudSessionRequest.cs @@ -1,11 +1,14 @@ -using ByteSync.Common.Business.Sessions.Cloud.Connections; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class FinalizeJoinCloudSessionRequest : IRequest +public class FinalizeJoinCloudSessionRequest : IRequest, ISessionRequest { + public string SessionId => FinalizeJoinCloudSessionParameters.SessionId; + public FinalizeJoinCloudSessionRequest(FinalizeJoinCloudSessionParameters finalizeJoinCloudSessionParameters, Client client) { FinalizeJoinCloudSessionParameters = finalizeJoinCloudSessionParameters; diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/GiveCloudSessionPasswordExchangeKeyRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/GiveCloudSessionPasswordExchangeKeyRequest.cs index 4d5fb6fb0..692cec6f3 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/GiveCloudSessionPasswordExchangeKeyRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/GiveCloudSessionPasswordExchangeKeyRequest.cs @@ -1,11 +1,14 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class GiveCloudSessionPasswordExchangeKeyRequest : IRequest +public class GiveCloudSessionPasswordExchangeKeyRequest : IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public GiveCloudSessionPasswordExchangeKeyRequest(Client client, GiveCloudSessionPasswordExchangeKeyParameters parameters) { Client = client; diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/InformPasswordIsWrongRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/InformPasswordIsWrongRequest.cs index 87af36fef..0992075e2 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/InformPasswordIsWrongRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/InformPasswordIsWrongRequest.cs @@ -1,9 +1,10 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class InformPasswordIsWrongRequest : IRequest +public class InformPasswordIsWrongRequest : IRequest, ISessionRequest { public InformPasswordIsWrongRequest(Client client, string sessionId, string clientInstanceId) { diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/QuitSessionRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/QuitSessionRequest.cs index 37474dc2c..11a13deb7 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/QuitSessionRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/QuitSessionRequest.cs @@ -1,9 +1,10 @@ -using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Security; +using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class QuitSessionRequest : IRequest +public class QuitSessionRequest : IRequest, ISessionRequest { public QuitSessionRequest(string sessionId, Client client) { diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/ResetSessionRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/ResetSessionRequest.cs index 4c0bc9073..b831a08ea 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/ResetSessionRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/ResetSessionRequest.cs @@ -1,9 +1,10 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class ResetSessionRequest : IRequest +public class ResetSessionRequest : IRequest, ISessionRequest { public ResetSessionRequest(string sessionId, Client client) { diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/UpdateSessionSettingsRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/UpdateSessionSettingsRequest.cs index 9f79d1bc0..f5335cf27 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/UpdateSessionSettingsRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/UpdateSessionSettingsRequest.cs @@ -1,10 +1,11 @@ -using ByteSync.Common.Business.Sessions; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Sessions; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class UpdateSessionSettingsRequest : IRequest +public class UpdateSessionSettingsRequest : IRequest, ISessionRequest { public UpdateSessionSettingsRequest(string sessionId, Client client, EncryptedSessionSettings settings) { diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/ValidateJoinCloudSessionCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/ValidateJoinCloudSessionCommandHandler.cs index eb7ac1bc2..adc197394 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/ValidateJoinCloudSessionCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/ValidateJoinCloudSessionCommandHandler.cs @@ -14,7 +14,7 @@ public ValidateJoinCloudSessionCommandHandler(ICloudSessionsService cloudSession public async Task Handle(ValidateJoinCloudSessionRequest request, CancellationToken cancellationToken) { - await _cloudSessionsService.ValidateJoinCloudSession(request.Parameters); + await _cloudSessionsService.ValidateJoinCloudSession(request.Parameters, request.Client); return Unit.Value; } } \ No newline at end of file diff --git a/src/ByteSync.ServerCommon/Commands/CloudSessions/ValidateJoinCloudSessionRequest.cs b/src/ByteSync.ServerCommon/Commands/CloudSessions/ValidateJoinCloudSessionRequest.cs index ce616355f..feed91a31 100644 --- a/src/ByteSync.ServerCommon/Commands/CloudSessions/ValidateJoinCloudSessionRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/CloudSessions/ValidateJoinCloudSessionRequest.cs @@ -1,12 +1,19 @@ +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions.Cloud.Connections; using MediatR; namespace ByteSync.ServerCommon.Commands.CloudSessions; -public class ValidateJoinCloudSessionRequest : IRequest +public class ValidateJoinCloudSessionRequest : IRequest, ISessionRequest { - public ValidateJoinCloudSessionRequest(ValidateJoinCloudSessionParameters parameters) + public string SessionId => Parameters.SessionId; + + public Client? Client { get; } + + public ValidateJoinCloudSessionRequest(ValidateJoinCloudSessionParameters parameters, Client? client = null) { + Client = client; Parameters = parameters; } diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertDownloadIsFinishedRequest.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertDownloadIsFinishedRequest.cs index 384e35461..07f766c34 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertDownloadIsFinishedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertDownloadIsFinishedRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.FileTransfers; -public class AssertDownloadIsFinishedRequest : IRequest +public class AssertDownloadIsFinishedRequest : IRequest, IFileTransferRequest { public AssertDownloadIsFinishedRequest(string sessionId, Client client, TransferParameters transferParameters) { diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertFilePartIsDownloadedRequest.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertFilePartIsDownloadedRequest.cs index 771472dec..114cd1177 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertFilePartIsDownloadedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertFilePartIsDownloadedRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.FileTransfers; -public class AssertFilePartIsDownloadedRequest : IRequest +public class AssertFilePartIsDownloadedRequest : IRequest, IFileTransferRequest { public AssertFilePartIsDownloadedRequest(string sessionId, Client client, TransferParameters transferParameters) { diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertFilePartIsUploadedRequest.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertFilePartIsUploadedRequest.cs index a7f54b64f..875ce7b4b 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertFilePartIsUploadedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertFilePartIsUploadedRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.FileTransfers; -public class AssertFilePartIsUploadedRequest : IRequest +public class AssertFilePartIsUploadedRequest : IRequest, IFileTransferRequest { public AssertFilePartIsUploadedRequest(string sessionId, Client client, TransferParameters transferParameters) { diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertUploadIsFinishedRequest.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertUploadIsFinishedRequest.cs index 7112b46da..98b350922 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertUploadIsFinishedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/AssertUploadIsFinishedRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.FileTransfers; -public class AssertUploadIsFinishedRequest : IRequest +public class AssertUploadIsFinishedRequest : IRequest, IFileTransferRequest { public AssertUploadIsFinishedRequest(string sessionId, Client client, TransferParameters transferParameters) { diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileStorageLocationCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileStorageLocationCommandHandler.cs index 3c7333366..9516e4150 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileStorageLocationCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileStorageLocationCommandHandler.cs @@ -31,7 +31,7 @@ public async Task Handle(GetDownloadFileStorageLocationRequ request.TransferParameters ); - var responseObject = new FileStorageLocation(url, _storageProvider); + var responseObject = new FileStorageLocation(url, request.TransferParameters.StorageProvider); _logger.LogDebug("Download file storage location generated for session {SessionId}, file {FileId}", request.SessionId, request.TransferParameters.SharedFileDefinition.Id); diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileStorageLocationRequest.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileStorageLocationRequest.cs index 769f1da51..6483f5132 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileStorageLocationRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileStorageLocationRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.FileTransfers; -public class GetDownloadFileStorageLocationRequest : IRequest +public class GetDownloadFileStorageLocationRequest : IRequest, IFileTransferRequest { public GetDownloadFileStorageLocationRequest(string sessionId, Client client, TransferParameters transferParameters) { diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileUrlRequest.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileUrlRequest.cs index e2b1da672..a3612b225 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileUrlRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetDownloadFileUrlRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.FileTransfers; -public class GetDownloadFileUrlRequest : IRequest +public class GetDownloadFileUrlRequest : IRequest, IFileTransferRequest { public GetDownloadFileUrlRequest(string sessionId, Client client, TransferParameters transferParameters) { diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileStorageLocationCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileStorageLocationCommandHandler.cs index bd00a3f15..187fe2642 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileStorageLocationCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileStorageLocationCommandHandler.cs @@ -31,7 +31,7 @@ public async Task Handle(GetUploadFileStorageLocationReques request.TransferParameters ); - var responseObject = new FileStorageLocation(url, _storageProvider); + var responseObject = new FileStorageLocation(url, request.TransferParameters.StorageProvider); _logger.LogDebug("Upload file storage location generated for session {SessionId}, file {FileId}", request.SessionId, request.TransferParameters.SharedFileDefinition.Id); diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileStorageLocationRequest.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileStorageLocationRequest.cs index 062dd6878..097e8b643 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileStorageLocationRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileStorageLocationRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.FileTransfers; -public class GetUploadFileStorageLocationRequest : IRequest +public class GetUploadFileStorageLocationRequest : IRequest, IFileTransferRequest { public GetUploadFileStorageLocationRequest(string sessionId, Client client, TransferParameters transferParameters) { diff --git a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileUrlRequest.cs b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileUrlRequest.cs index 86f36e352..367d8bbc4 100644 --- a/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileUrlRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/FileTransfers/GetUploadFileUrlRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.FileTransfers; -public class GetUploadFileUrlRequest : IRequest +public class GetUploadFileUrlRequest : IRequest, IFileTransferRequest { public GetUploadFileUrlRequest(string sessionId, Client client, TransferParameters transferParameters) { diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/AddDataNodeCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Inventories/AddDataNodeCommandHandler.cs index a07dc0ab4..8f50556e9 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/AddDataNodeCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/AddDataNodeCommandHandler.cs @@ -46,6 +46,7 @@ public async Task Handle(AddDataNodeRequest request, CancellationToken can { inventoryData ??= new InventoryEntity(sessionId); + if (inventoryData.InventoryMembers.Where(m => m.ClientInstanceId != client.ClientInstanceId).SelectMany(m => m.DataNodes).Any(n => n.Id == encryptedDataNode.Id)) throw new UnauthorizedAccessException("Resource id belongs to another member"); if (!inventoryData.IsInventoryStarted) { var inventoryMember = _inventoryMemberService.GetOrCreateInventoryMember(inventoryData, sessionId, client); diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/AddDataNodeRequest.cs b/src/ByteSync.ServerCommon/Commands/Inventories/AddDataNodeRequest.cs index f8c4dfe78..f79e0c2fd 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/AddDataNodeRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/AddDataNodeRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; using ByteSync.Common.Business.Sessions; using MediatR; namespace ByteSync.ServerCommon.Commands.Inventories; -public class AddDataNodeRequest : IRequest +public class AddDataNodeRequest : IRequest, ISessionRequest { public AddDataNodeRequest(string sessionId, Client client, string clientInstanceId, EncryptedDataNode encryptedDataNode) { diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/AddDataSourceCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Inventories/AddDataSourceCommandHandler.cs index 129ff2ef4..cfcb8744f 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/AddDataSourceCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/AddDataSourceCommandHandler.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Sessions; +using ByteSync.Common.Business.Sessions; using ByteSync.ServerCommon.Interfaces.Repositories; using ByteSync.ServerCommon.Interfaces.Services; using ByteSync.ServerCommon.Interfaces.Services.Clients; @@ -47,6 +47,7 @@ public async Task Handle(AddDataSourceRequest request, CancellationToken c { inventoryData ??= new InventoryEntity(sessionId); + if (inventoryData.InventoryMembers.Where(m => m.ClientInstanceId != client.ClientInstanceId).SelectMany(m => m.DataNodes).SelectMany(n => n.DataSources).Any(s => s.Id == encryptedDataSource.Id)) throw new UnauthorizedAccessException("Resource id belongs to another member"); if (!inventoryData.IsInventoryStarted) { var inventoryMember = _inventoryMemberService.GetOrCreateInventoryMember(inventoryData, sessionId, client); diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/AddDataSourceRequest.cs b/src/ByteSync.ServerCommon/Commands/Inventories/AddDataSourceRequest.cs index 05eebe35a..a72f40965 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/AddDataSourceRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/AddDataSourceRequest.cs @@ -1,10 +1,11 @@ -using ByteSync.Common.Business.Inventories; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Inventories; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Inventories; -public class AddDataSourceRequest : IRequest +public class AddDataSourceRequest : IRequest, ISessionRequest { public AddDataSourceRequest(string sessionId, Client client, string clientInstanceId, string dataNodeId, EncryptedDataSource encryptedDataSource) { diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/GetDataNodesRequest.cs b/src/ByteSync.ServerCommon/Commands/Inventories/GetDataNodesRequest.cs index 77b007769..7cfc76b81 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/GetDataNodesRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/GetDataNodesRequest.cs @@ -1,12 +1,17 @@ -using ByteSync.Common.Business.Sessions; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Sessions; using MediatR; namespace ByteSync.ServerCommon.Commands.Inventories; -public class GetDataNodesRequest : IRequest> +public class GetDataNodesRequest : IRequest>, ISessionRequest { - public GetDataNodesRequest(string sessionId, string clientInstanceId) + public Client? Client { get; } + + public GetDataNodesRequest(string sessionId, string clientInstanceId, Client? client = null) { + Client = client; SessionId = sessionId; ClientInstanceId = clientInstanceId; } diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/GetDataSourcesRequest.cs b/src/ByteSync.ServerCommon/Commands/Inventories/GetDataSourcesRequest.cs index 3b0f14157..29b602eda 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/GetDataSourcesRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/GetDataSourcesRequest.cs @@ -1,12 +1,17 @@ -using ByteSync.Common.Business.Inventories; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Inventories; using MediatR; namespace ByteSync.ServerCommon.Commands.Inventories; -public class GetDataSourcesRequest : IRequest> +public class GetDataSourcesRequest : IRequest>, ISessionRequest { - public GetDataSourcesRequest(string sessionId, string clientInstanceId, string dataNodeId) + public Client? Client { get; } + + public GetDataSourcesRequest(string sessionId, string clientInstanceId, string dataNodeId, Client? client = null) { + Client = client; SessionId = sessionId; ClientInstanceId = clientInstanceId; DataNodeId = dataNodeId; diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/RemoveDataNodeRequest.cs b/src/ByteSync.ServerCommon/Commands/Inventories/RemoveDataNodeRequest.cs index d19de15ae..9f52b5c40 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/RemoveDataNodeRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/RemoveDataNodeRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Inventories; -public class RemoveDataNodeRequest : IRequest +public class RemoveDataNodeRequest : IRequest, ISessionRequest { public RemoveDataNodeRequest(string sessionId, Client client, string clientInstanceId, EncryptedDataNode encryptedDataNode) { diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/RemoveDataSourceRequest.cs b/src/ByteSync.ServerCommon/Commands/Inventories/RemoveDataSourceRequest.cs index aa227c7fb..85adaf2b5 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/RemoveDataSourceRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/RemoveDataSourceRequest.cs @@ -1,10 +1,11 @@ -using ByteSync.Common.Business.Inventories; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Inventories; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Inventories; -public class RemoveDataSourceRequest : IRequest +public class RemoveDataSourceRequest : IRequest, ISessionRequest { public RemoveDataSourceRequest(string sessionId, Client client, string clientInstanceId, string dataNodeId, EncryptedDataSource encryptedDataSource) diff --git a/src/ByteSync.ServerCommon/Commands/Inventories/StartInventoryRequest.cs b/src/ByteSync.ServerCommon/Commands/Inventories/StartInventoryRequest.cs index d6c6cf47e..a166e8490 100644 --- a/src/ByteSync.ServerCommon/Commands/Inventories/StartInventoryRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Inventories/StartInventoryRequest.cs @@ -1,10 +1,11 @@ -using ByteSync.Common.Business.Inventories; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Inventories; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Inventories; -public class StartInventoryRequest : IRequest +public class StartInventoryRequest : IRequest, ISessionRequest { public StartInventoryRequest(string sessionId, Client client) { diff --git a/src/ByteSync.ServerCommon/Commands/Lobbies/QuitLobbyCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Lobbies/QuitLobbyCommandHandler.cs index 1a04dad2c..86082f15c 100644 --- a/src/ByteSync.ServerCommon/Commands/Lobbies/QuitLobbyCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Lobbies/QuitLobbyCommandHandler.cs @@ -1,4 +1,4 @@ -using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Repositories; using ByteSync.ServerCommon.Interfaces.Services; using ByteSync.ServerCommon.Interfaces.Services.Clients; using MediatR; @@ -56,7 +56,7 @@ public async Task Handle(QuitLobbyRequest request, CancellationToken cance await _invokeClientsService.LobbyGroup(lobbyId). MemberQuittedLobby(lobbyId, client.ClientInstanceId).ConfigureAwait(false); - await _clientsGroupsService.RemoveFromLobbyGroup(client, $"Lobby_{lobbyId}").ConfigureAwait(false); + await _clientsGroupsService.RemoveFromLobbyGroup(client, lobbyId).ConfigureAwait(false); } return result.IsSaved || result.IsDeleted; diff --git a/src/ByteSync.ServerCommon/Commands/Lobbies/TryJoinLobbyCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Lobbies/TryJoinLobbyCommandHandler.cs index 761f3232c..058798b13 100644 --- a/src/ByteSync.ServerCommon/Commands/Lobbies/TryJoinLobbyCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Lobbies/TryJoinLobbyCommandHandler.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Lobbies; +using ByteSync.Common.Business.Lobbies; using ByteSync.Common.Business.Lobbies.Connections; using ByteSync.Common.Helpers; using ByteSync.ServerCommon.Entities; @@ -40,6 +40,13 @@ public async Task Handle(TryJoinLobbyRequest request, Cancellat var joinLobbyParameters = request.JoinLobbyParameters; var client = request.Client; + ByteSync.ServerCommon.Security.SessionAuthorizationBehavior.RequireIdentity(client); + if (ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(joinLobbyParameters.PublicKeyInfo.PublicKey) != client.Identity) + throw new UnauthorizedAccessException(); + var authorizedProfile = await _cloudSessionProfileRepository.Get(joinLobbyParameters.CloudSessionProfileId); + if (authorizedProfile == null || authorizedProfile.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || !authorizedProfile.Slots.Any(s => s.ProfileClientId == joinLobbyParameters.ProfileClientId && s.ClientId == client.Identity)) + throw new UnauthorizedAccessException(); + JoinLobbyResult? joinLobbyResult = null; bool? isConnected = null; diff --git a/src/ByteSync.ServerCommon/Commands/SessionMembers/GetMembersInstanceIdsRequest.cs b/src/ByteSync.ServerCommon/Commands/SessionMembers/GetMembersInstanceIdsRequest.cs index 40dd7292b..ab6384200 100644 --- a/src/ByteSync.ServerCommon/Commands/SessionMembers/GetMembersInstanceIdsRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/SessionMembers/GetMembersInstanceIdsRequest.cs @@ -1,11 +1,16 @@ +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Security; using MediatR; namespace ByteSync.ServerCommon.Commands.SessionMembers; -public class GetMembersInstanceIdsRequest : IRequest> +public class GetMembersInstanceIdsRequest : IRequest>, ISessionRequest { - public GetMembersInstanceIdsRequest(string sessionId) + public Client? Client { get; } + + public GetMembersInstanceIdsRequest(string sessionId, Client? client = null) { + Client = client; SessionId = sessionId; } diff --git a/src/ByteSync.ServerCommon/Commands/SessionMembers/GetMembersRequest.cs b/src/ByteSync.ServerCommon/Commands/SessionMembers/GetMembersRequest.cs index 479415801..52c884c20 100644 --- a/src/ByteSync.ServerCommon/Commands/SessionMembers/GetMembersRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/SessionMembers/GetMembersRequest.cs @@ -1,12 +1,17 @@ +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions.Cloud; using MediatR; namespace ByteSync.ServerCommon.Commands.SessionMembers; -public class GetMembersRequest : IRequest> +public class GetMembersRequest : IRequest>, ISessionRequest { - public GetMembersRequest(string sessionId) + public Client? Client { get; } + + public GetMembersRequest(string sessionId, Client? client = null) { + Client = client; SessionId = sessionId; } diff --git a/src/ByteSync.ServerCommon/Commands/SessionMembers/SetGeneralStatusRequest.cs b/src/ByteSync.ServerCommon/Commands/SessionMembers/SetGeneralStatusRequest.cs index 21e086659..57e08cac6 100644 --- a/src/ByteSync.ServerCommon/Commands/SessionMembers/SetGeneralStatusRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/SessionMembers/SetGeneralStatusRequest.cs @@ -1,11 +1,14 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions.Cloud; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.SessionMembers; -public class SetGeneralStatusRequest : IRequest +public class SetGeneralStatusRequest : IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public SetGeneralStatusRequest(Client client, UpdateSessionMemberGeneralStatusParameters parameters) { Client = client; diff --git a/src/ByteSync.ServerCommon/Commands/Synchronizations/DateIsCopiedRequest.cs b/src/ByteSync.ServerCommon/Commands/Synchronizations/DateIsCopiedRequest.cs index 370bdc66e..91e35d801 100644 --- a/src/ByteSync.ServerCommon/Commands/Synchronizations/DateIsCopiedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Synchronizations/DateIsCopiedRequest.cs @@ -1,8 +1,9 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; namespace ByteSync.ServerCommon.Commands.Synchronizations; -public class DateIsCopiedRequest : IActionCompletedRequest +public class DateIsCopiedRequest : IActionCompletedRequest, ISessionRequest { public DateIsCopiedRequest(string sessionId, Client client, List actionsGroupIds, string? nodeId) { diff --git a/src/ByteSync.ServerCommon/Commands/Synchronizations/DirectoryIsCreatedRequest.cs b/src/ByteSync.ServerCommon/Commands/Synchronizations/DirectoryIsCreatedRequest.cs index fdd9b7714..90bb4aad8 100644 --- a/src/ByteSync.ServerCommon/Commands/Synchronizations/DirectoryIsCreatedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Synchronizations/DirectoryIsCreatedRequest.cs @@ -1,8 +1,9 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; namespace ByteSync.ServerCommon.Commands.Synchronizations; -public class DirectoryIsCreatedRequest : IActionCompletedRequest +public class DirectoryIsCreatedRequest : IActionCompletedRequest, ISessionRequest { public DirectoryIsCreatedRequest(string sessionId, Client client, List actionsGroupIds, string? nodeId) { diff --git a/src/ByteSync.ServerCommon/Commands/Synchronizations/FileOrDirectoryIsDeletedRequest.cs b/src/ByteSync.ServerCommon/Commands/Synchronizations/FileOrDirectoryIsDeletedRequest.cs index 75b7a92bf..286f5e31b 100644 --- a/src/ByteSync.ServerCommon/Commands/Synchronizations/FileOrDirectoryIsDeletedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Synchronizations/FileOrDirectoryIsDeletedRequest.cs @@ -1,8 +1,9 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; namespace ByteSync.ServerCommon.Commands.Synchronizations; -public class FileOrDirectoryIsDeletedRequest : IActionCompletedRequest +public class FileOrDirectoryIsDeletedRequest : IActionCompletedRequest, ISessionRequest { public FileOrDirectoryIsDeletedRequest(string sessionId, Client client, List actionsGroupIds, string? nodeId) { diff --git a/src/ByteSync.ServerCommon/Commands/Synchronizations/LocalCopyIsDoneRequest.cs b/src/ByteSync.ServerCommon/Commands/Synchronizations/LocalCopyIsDoneRequest.cs index b4b7fc3da..2df5c1338 100644 --- a/src/ByteSync.ServerCommon/Commands/Synchronizations/LocalCopyIsDoneRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Synchronizations/LocalCopyIsDoneRequest.cs @@ -1,9 +1,10 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Synchronizations; using ByteSync.ServerCommon.Business.Auth; namespace ByteSync.ServerCommon.Commands.Synchronizations; -public class LocalCopyIsDoneRequest : IActionCompletedRequest +public class LocalCopyIsDoneRequest : IActionCompletedRequest, ISessionRequest { public LocalCopyIsDoneRequest(string sessionId, Client client, List actionsGroupIds, string? nodeId) : this(sessionId, client, actionsGroupIds, nodeId, null) diff --git a/src/ByteSync.ServerCommon/Commands/Synchronizations/MemberHasFinishedRequest.cs b/src/ByteSync.ServerCommon/Commands/Synchronizations/MemberHasFinishedRequest.cs index c62e78262..0549a2e21 100644 --- a/src/ByteSync.ServerCommon/Commands/Synchronizations/MemberHasFinishedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Synchronizations/MemberHasFinishedRequest.cs @@ -1,9 +1,10 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Synchronizations; -public class MemberHasFinishedRequest : IRequest +public class MemberHasFinishedRequest : IRequest, ISessionRequest { public MemberHasFinishedRequest(string sessionId, Client client) { diff --git a/src/ByteSync.ServerCommon/Commands/Synchronizations/RequestSynchronizationAbortRequest.cs b/src/ByteSync.ServerCommon/Commands/Synchronizations/RequestSynchronizationAbortRequest.cs index 401f1e227..28a8f1641 100644 --- a/src/ByteSync.ServerCommon/Commands/Synchronizations/RequestSynchronizationAbortRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Synchronizations/RequestSynchronizationAbortRequest.cs @@ -1,9 +1,10 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Synchronizations; -public class RequestSynchronizationAbortRequest : IRequest +public class RequestSynchronizationAbortRequest : IRequest, ISessionRequest { public RequestSynchronizationAbortRequest(string sessionId, Client client) { diff --git a/src/ByteSync.ServerCommon/Commands/Synchronizations/StartSynchronizationRequest.cs b/src/ByteSync.ServerCommon/Commands/Synchronizations/StartSynchronizationRequest.cs index 46b29aeec..2bef0df8d 100644 --- a/src/ByteSync.ServerCommon/Commands/Synchronizations/StartSynchronizationRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Synchronizations/StartSynchronizationRequest.cs @@ -1,10 +1,11 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Actions; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Synchronizations; -public class StartSynchronizationRequest : IRequest +public class StartSynchronizationRequest : IRequest, ISessionRequest { public StartSynchronizationRequest(string sessionId, Client client, List actionsGroupDefinitions) { diff --git a/src/ByteSync.ServerCommon/Commands/Synchronizations/SynchronizationErrorsRequest.cs b/src/ByteSync.ServerCommon/Commands/Synchronizations/SynchronizationErrorsRequest.cs index 537c5376d..48a9e4a06 100644 --- a/src/ByteSync.ServerCommon/Commands/Synchronizations/SynchronizationErrorsRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Synchronizations/SynchronizationErrorsRequest.cs @@ -1,8 +1,9 @@ +using ByteSync.ServerCommon.Security; using ByteSync.ServerCommon.Business.Auth; namespace ByteSync.ServerCommon.Commands.Synchronizations; -public class SynchronizationErrorsRequest : IActionErrorRequest +public class SynchronizationErrorsRequest : IActionErrorRequest, ISessionRequest { public SynchronizationErrorsRequest(string sessionId, Client client, List actionsGroupIds, string? nodeId) { diff --git a/src/ByteSync.ServerCommon/Commands/Trusts/GiveMemberPublicKeyCheckDataRequest.cs b/src/ByteSync.ServerCommon/Commands/Trusts/GiveMemberPublicKeyCheckDataRequest.cs index 248f8a35c..98e145cc1 100644 --- a/src/ByteSync.ServerCommon/Commands/Trusts/GiveMemberPublicKeyCheckDataRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Trusts/GiveMemberPublicKeyCheckDataRequest.cs @@ -1,11 +1,14 @@ -using ByteSync.Common.Business.Trust.Connections; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Trust.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Trusts; -public class GiveMemberPublicKeyCheckDataRequest : IRequest +public class GiveMemberPublicKeyCheckDataRequest : IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public GiveMemberPublicKeyCheckDataRequest(GiveMemberPublicKeyCheckDataParameters parameters, Client client) { Parameters = parameters; diff --git a/src/ByteSync.ServerCommon/Commands/Trusts/InformProtocolVersionIncompatibleRequest.cs b/src/ByteSync.ServerCommon/Commands/Trusts/InformProtocolVersionIncompatibleRequest.cs index 106a83e7b..768085757 100644 --- a/src/ByteSync.ServerCommon/Commands/Trusts/InformProtocolVersionIncompatibleRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Trusts/InformProtocolVersionIncompatibleRequest.cs @@ -1,11 +1,14 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Trusts; -public class InformProtocolVersionIncompatibleRequest : IRequest +public class InformProtocolVersionIncompatibleRequest : IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public InformProtocolVersionIncompatibleRequest(InformProtocolVersionIncompatibleParameters parameters, Client client) { Parameters = parameters; diff --git a/src/ByteSync.ServerCommon/Commands/Trusts/InformPublicKeyValidationIsFinishedRequest.cs b/src/ByteSync.ServerCommon/Commands/Trusts/InformPublicKeyValidationIsFinishedRequest.cs index 7e1c22a08..ccce2c83b 100644 --- a/src/ByteSync.ServerCommon/Commands/Trusts/InformPublicKeyValidationIsFinishedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Trusts/InformPublicKeyValidationIsFinishedRequest.cs @@ -1,11 +1,14 @@ +using ByteSync.ServerCommon.Security; using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Trusts; -public class InformPublicKeyValidationIsFinishedRequest: IRequest +public class InformPublicKeyValidationIsFinishedRequest: IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public InformPublicKeyValidationIsFinishedRequest(PublicKeyValidationParameters parameters, Client client) { Parameters = parameters; diff --git a/src/ByteSync.ServerCommon/Commands/Trusts/RequestTrustPublicKeyRequest.cs b/src/ByteSync.ServerCommon/Commands/Trusts/RequestTrustPublicKeyRequest.cs index a5e85edfb..d0ddbaf6a 100644 --- a/src/ByteSync.ServerCommon/Commands/Trusts/RequestTrustPublicKeyRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Trusts/RequestTrustPublicKeyRequest.cs @@ -1,11 +1,14 @@ -using ByteSync.Common.Business.Sessions.Cloud.Connections; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Trusts; -public class RequestTrustPublicKeyRequest: IRequest +public class RequestTrustPublicKeyRequest: IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public RequestTrustPublicKeyRequest(RequestTrustProcessParameters parameters, Client client) { Parameters = parameters; diff --git a/src/ByteSync.ServerCommon/Commands/Trusts/SendDigitalSignaturesCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Trusts/SendDigitalSignaturesCommandHandler.cs index 36863f8e8..c41e5e649 100644 --- a/src/ByteSync.ServerCommon/Commands/Trusts/SendDigitalSignaturesCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Trusts/SendDigitalSignaturesCommandHandler.cs @@ -1,4 +1,4 @@ -using ByteSync.ServerCommon.Entities; +using ByteSync.ServerCommon.Entities; using ByteSync.ServerCommon.Interfaces.Repositories; using ByteSync.ServerCommon.Interfaces.Services.Clients; using MediatR; @@ -40,7 +40,8 @@ public async Task Handle(SendDigitalSignaturesRequest request, CancellationToken Lobby? lobby = null; if (cloudSession != null) { - if (cloudSession.FindMemberOrPreMember(client.ClientInstanceId) == null) + if (cloudSession.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || cloudSession.IsSessionRemoved || cloudSession.FindMemberOrPreMember(client.ClientInstanceId) == null || + parameters.DigitalSignatureCheckInfos.Any(ds => cloudSession.FindMemberOrPreMember(ds.Recipient) == null)) { _logger.LogInformation("{Endpoint} is neither a member nor a premember of session {session}", client.ClientInstanceId, parameters.DataId); return; @@ -51,7 +52,8 @@ public async Task Handle(SendDigitalSignaturesRequest request, CancellationToken lobby = await _lobbyRepository.Get(parameters.DataId).ConfigureAwait(false); if (lobby != null) { - if (lobby.GetLobbyMemberByClientInstanceId(client.ClientInstanceId) == null) + if (lobby.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || lobby.GetLobbyMemberByClientInstanceId(client.ClientInstanceId) == null || + parameters.DigitalSignatureCheckInfos.Any(ds => lobby.GetLobbyMemberByClientInstanceId(ds.Recipient) == null)) { _logger.LogInformation("{Endpoint} is neither a member of lobby {lobbyId}", client.ClientInstanceId, parameters.DataId); return; diff --git a/src/ByteSync.ServerCommon/Commands/Trusts/SetAuthCheckedRequest.cs b/src/ByteSync.ServerCommon/Commands/Trusts/SetAuthCheckedRequest.cs index 9cc17011f..a4b2ecc59 100644 --- a/src/ByteSync.ServerCommon/Commands/Trusts/SetAuthCheckedRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Trusts/SetAuthCheckedRequest.cs @@ -1,11 +1,14 @@ -using ByteSync.Common.Business.Trust.Connections; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Trust.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Trusts; -public class SetAuthCheckedRequest: IRequest +public class SetAuthCheckedRequest: IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public SetAuthCheckedRequest(SetAuthCheckedParameters parameters, Client client) { Parameters = parameters; diff --git a/src/ByteSync.ServerCommon/Commands/Trusts/StartTrustCheckRequest.cs b/src/ByteSync.ServerCommon/Commands/Trusts/StartTrustCheckRequest.cs index 671682293..a06021cd4 100644 --- a/src/ByteSync.ServerCommon/Commands/Trusts/StartTrustCheckRequest.cs +++ b/src/ByteSync.ServerCommon/Commands/Trusts/StartTrustCheckRequest.cs @@ -1,11 +1,14 @@ -using ByteSync.Common.Business.Sessions.Cloud.Connections; +using ByteSync.ServerCommon.Security; +using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using MediatR; namespace ByteSync.ServerCommon.Commands.Trusts; -public class StartTrustCheckRequest : IRequest +public class StartTrustCheckRequest : IRequest, ISessionRequest { + public string SessionId => Parameters.SessionId; + public StartTrustCheckRequest(TrustCheckParameters parameters, Client client) { Parameters = parameters; diff --git a/src/ByteSync.ServerCommon/Entities/CloudSessionProfileEntity.cs b/src/ByteSync.ServerCommon/Entities/CloudSessionProfileEntity.cs index 7bccabbb0..6917390c3 100644 --- a/src/ByteSync.ServerCommon/Entities/CloudSessionProfileEntity.cs +++ b/src/ByteSync.ServerCommon/Entities/CloudSessionProfileEntity.cs @@ -4,6 +4,8 @@ namespace ByteSync.ServerCommon.Entities; public class CloudSessionProfileEntity { + public int AuthenticationEpoch { get; set; } + public CloudSessionProfileEntity() { CreationDateTime = DateTime.UtcNow; diff --git a/src/ByteSync.ServerCommon/Entities/Lobby.cs b/src/ByteSync.ServerCommon/Entities/Lobby.cs index b9aedb9a6..fe52af832 100644 --- a/src/ByteSync.ServerCommon/Entities/Lobby.cs +++ b/src/ByteSync.ServerCommon/Entities/Lobby.cs @@ -7,6 +7,8 @@ namespace ByteSync.ServerCommon.Entities; public class Lobby { + public int AuthenticationEpoch { get; set; } + public Lobby() { LobbyMemberCells = new List(); diff --git a/src/ByteSync.ServerCommon/Factories/ClientsGroupIdFactory.cs b/src/ByteSync.ServerCommon/Factories/ClientsGroupIdFactory.cs index 41c4218e7..e4eff4137 100644 --- a/src/ByteSync.ServerCommon/Factories/ClientsGroupIdFactory.cs +++ b/src/ByteSync.ServerCommon/Factories/ClientsGroupIdFactory.cs @@ -1,4 +1,4 @@ -using ByteSync.ServerCommon.Interfaces.Factories; +using ByteSync.ServerCommon.Interfaces.Factories; namespace ByteSync.ServerCommon.Factories; @@ -10,16 +10,16 @@ public class ClientsGroupIdFactory : IClientsGroupIdFactory public string GetClientGroupId(string clientInstanceId) { - return CLIENT_PREFIX + clientInstanceId; + return $"Auth{ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch}_" + CLIENT_PREFIX + clientInstanceId; } public string GetSessionGroupId(string sessionId) { - return SESSION_PREFIX + sessionId; + return $"Auth{ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch}_" + SESSION_PREFIX + sessionId; } public string GetLobbyGroupId(string lobbyId) { - return LOBBY_PREFIX + lobbyId; + return $"Auth{ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch}_" + LOBBY_PREFIX + lobbyId; } } \ No newline at end of file diff --git a/src/ByteSync.ServerCommon/Factories/LobbyFactory.cs b/src/ByteSync.ServerCommon/Factories/LobbyFactory.cs index d74215134..a1ba4f388 100644 --- a/src/ByteSync.ServerCommon/Factories/LobbyFactory.cs +++ b/src/ByteSync.ServerCommon/Factories/LobbyFactory.cs @@ -1,4 +1,4 @@ -using ByteSync.ServerCommon.Entities; +using ByteSync.ServerCommon.Entities; using ByteSync.ServerCommon.Interfaces.Factories; namespace ByteSync.ServerCommon.Factories; @@ -8,6 +8,7 @@ public class LobbyFactory : ILobbyFactory public Lobby BuildLobby(CloudSessionProfileEntity cloudSessionProfileData) { Lobby lobby = new Lobby(); + lobby.AuthenticationEpoch = cloudSessionProfileData.AuthenticationEpoch; lobby.LobbyId = $"LobbyID_{Guid.NewGuid()}"; diff --git a/src/ByteSync.ServerCommon/Helpers/JwtHelper.cs b/src/ByteSync.ServerCommon/Helpers/JwtHelper.cs index bf9d9ce63..136905459 100644 --- a/src/ByteSync.ServerCommon/Helpers/JwtHelper.cs +++ b/src/ByteSync.ServerCommon/Helpers/JwtHelper.cs @@ -1,4 +1,4 @@ -using System.Text; +using System.Text; using ByteSync.ServerCommon.Business.Auth; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; @@ -20,6 +20,18 @@ public static void AddJwtAuthentication(this IServiceCollection services, string }) .AddJwtBearer(option => { + option.Events = new JwtBearerEvents + { + OnTokenValidated = async context => + { + var instance = context.Principal?.FindFirst(AuthConstants.CLAIM_CLIENT_INSTANCE_ID)?.Value; + var repository = context.HttpContext.RequestServices.GetRequiredService(); + var client = instance == null ? null : await repository.Get(instance); + if (client == null) { context.Fail("Unknown client"); return; } + try { ByteSync.ServerCommon.Security.ClientAuthentication.ValidateClaims(client, context.Principal!); } + catch (SecurityTokenValidationException) { context.Fail("Authentication epoch or identity mismatch"); } + } + }; option.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, @@ -28,7 +40,8 @@ public static void AddJwtAuthentication(this IServiceCollection services, string ClockSkew = TimeSpan.Zero, - ValidateIssuerSigningKey = false, + ValidateIssuerSigningKey = true, + ValidAlgorithms = [SecurityAlgorithms.HmacSha256], ValidIssuer = AuthConstants.ISSUER, ValidAudience = AuthConstants.AUDIENCE, IssuerSigningKey = new SymmetricSecurityKey(key), @@ -42,6 +55,8 @@ public static void AddClaimAuthorization(this IServiceCollection services) { option.AddPolicy(AuthConstants.CLAIMBASEDAUTH, policy => { + policy.RequireClaim(AuthConstants.CLAIM_AUTHENTICATION_EPOCH, ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch.ToString()); + policy.RequireClaim(AuthConstants.CLAIM_IDENTITY); policy.RequireClaim(AuthConstants.CLAIM_CLIENT_ID); policy.RequireClaim(AuthConstants.CLAIM_CLIENT_INSTANCE_ID); policy.RequireClaim(AuthConstants.CLAIM_VERSION); @@ -49,6 +64,8 @@ public static void AddClaimAuthorization(this IServiceCollection services) option.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() + .RequireClaim(AuthConstants.CLAIM_AUTHENTICATION_EPOCH, ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch.ToString()) + .RequireClaim(AuthConstants.CLAIM_IDENTITY) .Build(); }); } diff --git a/src/ByteSync.ServerCommon/Interfaces/Services/IAuthenticationChallengeService.cs b/src/ByteSync.ServerCommon/Interfaces/Services/IAuthenticationChallengeService.cs new file mode 100644 index 000000000..a5a09acfb --- /dev/null +++ b/src/ByteSync.ServerCommon/Interfaces/Services/IAuthenticationChallengeService.cs @@ -0,0 +1,9 @@ +using ByteSync.Common.Business.Auth; + +namespace ByteSync.ServerCommon.Interfaces.Services; + +public interface IAuthenticationChallengeService +{ + Task Create(LoginData login); + Task VerifyAndConsume(LoginData login); +} diff --git a/src/ByteSync.ServerCommon/Interfaces/Services/ICloudSessionsService.cs b/src/ByteSync.ServerCommon/Interfaces/Services/ICloudSessionsService.cs index 2257dd188..4fa22b48a 100644 --- a/src/ByteSync.ServerCommon/Interfaces/Services/ICloudSessionsService.cs +++ b/src/ByteSync.ServerCommon/Interfaces/Services/ICloudSessionsService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Sessions.Cloud; +using ByteSync.Common.Business.Sessions.Cloud; using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Business.Sessions; @@ -10,12 +10,14 @@ public interface ICloudSessionsService Task BuildCloudSessionResult(CloudSessionData cloudSessionData, SessionMemberData sessionMemberData); Task> GetMembersInstanceIds(string sessionId); + + Task PreJoinCloudSession(Client client, ByteSync.Common.Business.EndPoints.PublicKeyInfo publicKeyInfo, string? profileClientId, string sessionId, string validatorClientInstanceId); Task AskCloudSessionPasswordExchangeKey(Client client, AskCloudSessionPasswordExchangeKeyParameters parameters); Task AskJoinCloudSession(Client client, AskJoinCloudSessionParameters parameters); - Task ValidateJoinCloudSession(ValidateJoinCloudSessionParameters parameters); + Task ValidateJoinCloudSession(ValidateJoinCloudSessionParameters parameters, Client? caller = null); Task> GetSessionMembersInfosAsync(string sessionId); diff --git a/src/ByteSync.ServerCommon/Interfaces/Services/ITransferAuthorizationService.cs b/src/ByteSync.ServerCommon/Interfaces/Services/ITransferAuthorizationService.cs new file mode 100644 index 000000000..187416f74 --- /dev/null +++ b/src/ByteSync.ServerCommon/Interfaces/Services/ITransferAuthorizationService.cs @@ -0,0 +1,9 @@ +using ByteSync.Common.Business.SharedFiles; +using ByteSync.ServerCommon.Business.Auth; + +namespace ByteSync.ServerCommon.Interfaces.Services; + +public interface ITransferAuthorizationService +{ + Task Authorize(string sessionId, Client client, TransferParameters parameters, bool upload, bool create); +} diff --git a/src/ByteSync.ServerCommon/Interfaces/Services/Storage/Factories/ICloudflareR2ClientFactory.cs b/src/ByteSync.ServerCommon/Interfaces/Services/Storage/Factories/ICloudflareR2ClientFactory.cs index ac6e5d948..b23ceba5a 100644 --- a/src/ByteSync.ServerCommon/Interfaces/Services/Storage/Factories/ICloudflareR2ClientFactory.cs +++ b/src/ByteSync.ServerCommon/Interfaces/Services/Storage/Factories/ICloudflareR2ClientFactory.cs @@ -4,5 +4,5 @@ namespace ByteSync.ServerCommon.Interfaces.Services.Storage.Factories; public interface ICloudflareR2ClientFactory { - AmazonS3Client GetClient(); + IAmazonS3 GetClient(); } \ No newline at end of file diff --git a/src/ByteSync.ServerCommon/Security/ClientAuthentication.cs b/src/ByteSync.ServerCommon/Security/ClientAuthentication.cs new file mode 100644 index 000000000..2fe9ec765 --- /dev/null +++ b/src/ByteSync.ServerCommon/Security/ClientAuthentication.cs @@ -0,0 +1,19 @@ +using System.Security.Claims; +using ByteSync.Common.Business.Auth; +using ByteSync.ServerCommon.Business.Auth; +using Microsoft.IdentityModel.Tokens; + +namespace ByteSync.ServerCommon.Security; + +public static class ClientAuthentication +{ + public static void ValidateClaims(Client client, ClaimsPrincipal claims) + { + if (client.AuthenticationEpoch != AuthenticationProtocol.Epoch || + claims.FindFirst(AuthConstants.CLAIM_AUTHENTICATION_EPOCH)?.Value != AuthenticationProtocol.Epoch.ToString() || + claims.FindFirst(AuthConstants.CLAIM_IDENTITY)?.Value != client.Identity || + claims.FindFirst(AuthConstants.CLAIM_CLIENT_INSTANCE_ID)?.Value != client.ClientInstanceId || + !AuthenticationProtocol.IsInstanceOf(client.ClientInstanceId, client.Identity ?? "")) + throw new SecurityTokenValidationException("Authentication epoch or identity mismatch"); + } +} diff --git a/src/ByteSync.ServerCommon/Security/IFileTransferRequest.cs b/src/ByteSync.ServerCommon/Security/IFileTransferRequest.cs new file mode 100644 index 000000000..773d0ef64 --- /dev/null +++ b/src/ByteSync.ServerCommon/Security/IFileTransferRequest.cs @@ -0,0 +1,8 @@ +using ByteSync.Common.Business.SharedFiles; + +namespace ByteSync.ServerCommon.Security; + +public interface IFileTransferRequest : ISessionRequest +{ + TransferParameters TransferParameters { get; } +} diff --git a/src/ByteSync.ServerCommon/Security/ISessionRequest.cs b/src/ByteSync.ServerCommon/Security/ISessionRequest.cs new file mode 100644 index 000000000..64a9c3133 --- /dev/null +++ b/src/ByteSync.ServerCommon/Security/ISessionRequest.cs @@ -0,0 +1,9 @@ +using ByteSync.ServerCommon.Business.Auth; + +namespace ByteSync.ServerCommon.Security; + +public interface ISessionRequest +{ + Client? Client { get; } + string SessionId { get; } +} diff --git a/src/ByteSync.ServerCommon/Security/SessionAuthorizationBehavior.cs b/src/ByteSync.ServerCommon/Security/SessionAuthorizationBehavior.cs new file mode 100644 index 000000000..088ed8009 --- /dev/null +++ b/src/ByteSync.ServerCommon/Security/SessionAuthorizationBehavior.cs @@ -0,0 +1,172 @@ +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.EndPoints; +using ByteSync.Common.Business.Versions; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Business.Sessions; +using ByteSync.ServerCommon.Commands.CloudSessions; +using ByteSync.ServerCommon.Commands.Inventories; +using ByteSync.ServerCommon.Commands.SessionMembers; +using ByteSync.ServerCommon.Commands.Synchronizations; +using ByteSync.ServerCommon.Commands.Trusts; +using ByteSync.ServerCommon.Interfaces.Repositories; +using MediatR; + +namespace ByteSync.ServerCommon.Security; + +public class SessionAuthorizationBehavior(ICloudSessionsRepository sessions, ByteSync.ServerCommon.Interfaces.Services.ITransferAuthorizationService transfers, ITrackingActionRepository actions, IInventoryRepository inventories, ILobbyRepository lobbies) + : IPipelineBehavior where TRequest : notnull +{ + public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) + { + if (request is CreateSessionRequest create) + { + RequireIdentity(create.Client); + RequireKey(create.Client, create.CreateCloudSessionParameters.CreatorPublicKeyInfo); + if (create.CreateCloudSessionParameters.CreatorPublicKeyInfo.ProtocolVersion != ProtocolVersion.CURRENT) Deny(); + await RequireProfileLink(create.Client, create.CreateCloudSessionParameters.LobbyId, create.CreateCloudSessionParameters.CreatorProfileClientId, true); + } + if (request is ISessionRequest operation) + { + RequireIdentity(operation.Client); + var session = await sessions.Get(operation.SessionId); + if (session == null || session.IsSessionRemoved || session.AuthenticationEpoch != AuthenticationProtocol.Epoch || session.ProtocolVersion != ProtocolVersion.CURRENT) + Deny(); + var client = operation.Client!; + var member = session!.FindMember(client.ClientInstanceId); + var attempt = session.PreSessionMembers.SingleOrDefault(m => m.ClientInstanceId == client.ClientInstanceId && + m.JoinExpiresAt > DateTimeOffset.UtcNow && m.Identity == client.Identity); + var joining = request is AskPasswordExchangeKeyRequest or BeginJoinSessionRequest; + var trust = request is StartTrustCheckRequest or RequestTrustPublicKeyRequest or SetAuthCheckedRequest or + GiveMemberPublicKeyCheckDataRequest or InformPublicKeyValidationIsFinishedRequest or InformProtocolVersionIncompatibleRequest; + var pendingAllowed = trust || request is GetMembersInstanceIdsRequest or AskJoinCloudSessionRequest or FinalizeJoinCloudSessionRequest; + if (!joining && member == null && !(pendingAllowed && attempt != null)) Deny(); + if (member != null && member.Identity != client.Identity) Deny(); + if ((joining || pendingAllowed || request is UpdateSessionSettingsRequest or AddDataNodeRequest or RemoveDataNodeRequest or + AddDataSourceRequest or RemoveDataSourceRequest) && session.IsSessionActivated) Deny(); + if (request is StartSynchronizationRequest && !session.IsSessionActivated) Deny(); + if (request is IActionCompletedRequest completed) + await RequireActions(operation.SessionId, client, completed.ActionsGroupIds, completed.NodeId, request is LocalCopyIsDoneRequest); + if (request is SynchronizationErrorsRequest errors) + await RequireActions(operation.SessionId, client, errors.ActionsGroupIds, errors.NodeId, false, true); + if (request is StartSynchronizationRequest start) + { + var inventory = await inventories.Get(operation.SessionId) ?? throw new UnauthorizedAccessException(); + foreach (var definition in start.ActionsGroupDefinitions) + { + if (definition.SourceClientInstanceId != null && session.FindMember(definition.SourceClientInstanceId) == null) Deny(); + foreach (var target in definition.TargetClientInstanceAndNodeIds) + if (session.FindMember(target.ClientInstanceId) == null || !inventory.InventoryMembers + .Any(m => m.ClientInstanceId == target.ClientInstanceId && m.DataNodes.Any(n => n.Id == target.NodeId))) Deny(); + } + } + switch (request) + { + case BeginJoinSessionRequest begin: + RequireKey(client, begin.Parameters.PublicKeyInfo); + if (begin.Parameters.LobbyId != null && begin.Parameters.LobbyId != session.LobbyId) Deny(); + await RequireProfileLink(client, begin.Parameters.LobbyId, begin.Parameters.ProfileClientId); + break; + case AskPasswordExchangeKeyRequest r: + RequireKey(client, r.Parameters.PublicKeyInfo); + if (r.Parameters.LobbyId != null && r.Parameters.LobbyId != session.LobbyId) Deny(); + await RequireProfileLink(client, r.Parameters.LobbyId, r.Parameters.ProfileClientId); + break; + case AskJoinCloudSessionRequest r: + if (r.Parameters.JoinerClientInstanceId != client.ClientInstanceId || attempt?.ValidatorInstanceId != r.Parameters.ValidatorInstanceId) Deny(); + break; + case GiveCloudSessionPasswordExchangeKeyRequest r: + RequireOwner(client, r.Parameters.ValidatorInstanceId); + RequireKey(client, r.Parameters.PublicKeyInfo); + break; + case ValidateJoinCloudSessionRequest r: + if (r.Parameters.ValidatorInstanceId != client.ClientInstanceId || member == null) Deny(); + break; + case FinalizeJoinCloudSessionRequest r: + if (r.FinalizeJoinCloudSessionParameters.JoinerInstanceId != client.ClientInstanceId) Deny(); + break; + case AddDataNodeRequest r: RequireOwner(client, r.ClientInstanceId); break; + case RemoveDataNodeRequest r: RequireOwner(client, r.ClientInstanceId); break; + case AddDataSourceRequest r: RequireOwner(client, r.ClientInstanceId); break; + case RemoveDataSourceRequest r: RequireOwner(client, r.ClientInstanceId); break; + case SetGeneralStatusRequest r: RequireOwner(client, r.Parameters.ClientInstanceId); break; + case StartTrustCheckRequest r: + RequireKey(client, r.Parameters.PublicKeyInfo); + if (r.Parameters.MembersInstanceIdsToCheck.Any(id => session.FindMember(id) == null)) Deny(); + break; + case RequestTrustPublicKeyRequest r: + RequireOwner(client, r.Parameters.JoinerClientInstanceId); + RequireKey(client, new PublicKeyInfo { PublicKey = r.Parameters.JoinerPublicKeyCheckData.IssuerPublicKeyInfo.PublicKey }); + if (session.FindMember(r.Parameters.SessionMemberInstanceId) == null) Deny(); + break; + case GiveMemberPublicKeyCheckDataRequest r: + RequireOwner(client, r.Parameters.PublicKeyCheckData.IssuerClientInstanceId); + RequireKey(client, new PublicKeyInfo { PublicKey = r.Parameters.PublicKeyCheckData.IssuerPublicKeyInfo.PublicKey }); + if (session.FindMemberOrPreMember(r.Parameters.ClientInstanceId) == null) Deny(); + break; + case SetAuthCheckedRequest r: + if (session.FindMemberOrPreMember(r.Parameters.CheckedClientInstanceId) == null) Deny(); + break; + case InformPublicKeyValidationIsFinishedRequest r: + if (session.FindMemberOrPreMember(r.Parameters.OtherPartyClientInstanceId) == null) Deny(); + break; + case InformProtocolVersionIncompatibleRequest r: + RequireOwner(client, r.Parameters.MemberClientInstanceId); + if (session.FindMemberOrPreMember(r.Parameters.JoinerClientInstanceId) == null) Deny(); + break; + } + } + if (request is IFileTransferRequest file) + { + if (request is not (ByteSync.ServerCommon.Commands.FileTransfers.AssertDownloadIsFinishedRequest or ByteSync.ServerCommon.Commands.FileTransfers.AssertUploadIsFinishedRequest) && file.TransferParameters.PartNumber == null) Deny(); + if (request is ByteSync.ServerCommon.Commands.FileTransfers.AssertUploadIsFinishedRequest && file.TransferParameters.TotalParts == null) Deny(); + var upload = request is ByteSync.ServerCommon.Commands.FileTransfers.GetUploadFileUrlRequest or ByteSync.ServerCommon.Commands.FileTransfers.GetUploadFileStorageLocationRequest or ByteSync.ServerCommon.Commands.FileTransfers.AssertFilePartIsUploadedRequest or ByteSync.ServerCommon.Commands.FileTransfers.AssertUploadIsFinishedRequest; + var createTransfer = request is ByteSync.ServerCommon.Commands.FileTransfers.GetUploadFileUrlRequest or ByteSync.ServerCommon.Commands.FileTransfers.GetUploadFileStorageLocationRequest; + await transfers.Authorize(file.SessionId, file.Client!, file.TransferParameters, upload, createTransfer); + } + return await next(); + } + + private async Task RequireProfileLink(Client client, string? lobbyId, string? profileId, bool creator = false) + { + if (lobbyId == null && profileId == null) return; + if (lobbyId == null || profileId == null) Deny(); + var lobby = await lobbies.Get(lobbyId!); + var member = lobby?.GetLobbyMemberByClientInstanceId(client.ClientInstanceId); + if (lobby?.AuthenticationEpoch != AuthenticationProtocol.Epoch || member == null || member.ProfileClientId != profileId || + (creator && lobby.LobbyMemberCells.FirstOrDefault()?.LobbyMember?.ClientInstanceId != client.ClientInstanceId)) Deny(); + } + + private async Task RequireActions(string sessionId, Client client, List ids, string? nodeId, bool requireSource, bool allowSource = false) + { + foreach (var id in ids) + { + var action = await actions.GetOrThrow(sessionId, id); + var isSource = action.SourceClientInstanceId == client.ClientInstanceId; + if (requireSource && !isSource) Deny(); + if (!(allowSource && isSource) && !action.TargetClientInstanceAndNodeIds + .Any(t => t.ClientInstanceId == client.ClientInstanceId && (nodeId == null || t.NodeId == nodeId))) Deny(); + } + } + + public static void RequireIdentity(Client? client) + { + if (client == null || client.AuthenticationEpoch != AuthenticationProtocol.Epoch || string.IsNullOrEmpty(client.Identity) || + !AuthenticationProtocol.IsInstanceOf(client.ClientInstanceId, client.Identity)) Deny(); + } + + private static void RequireOwner(Client client, string instanceId) + { + if (client.ClientInstanceId != instanceId) Deny(); + } + + private static void RequireKey(Client client, PublicKeyInfo key) + { + try + { + if (key == null || key.PublicKey == null || key.PublicKey.Length > 2048 || AuthenticationProtocol.GetIdentity(key.PublicKey) != client.Identity) Deny(); + } + catch (System.Security.Cryptography.CryptographicException) { Deny(); } + } + + private static void Deny() => throw new UnauthorizedAccessException("Operation not authorized"); +} diff --git a/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs b/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs new file mode 100644 index 000000000..d911cc5ac --- /dev/null +++ b/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs @@ -0,0 +1,62 @@ +using System.Security.Cryptography; +using System.Text.Json; +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Versions; +using ByteSync.ServerCommon.Interfaces.Services; +using StackExchange.Redis; + +namespace ByteSync.ServerCommon.Services; + +public class AuthenticationChallengeService(IRedisInfrastructureService redis) : IAuthenticationChallengeService +{ + private sealed record ChallengeRecord(LoginData Login, AuthenticationChallenge Challenge); + + public async Task Create(LoginData login) + { + Validate(login); + var challenge = new AuthenticationChallenge + { + Id = Guid.NewGuid().ToString("N"), + Nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)), + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(2) + }; + var stored = await redis.GetDatabase().StringSetAsync(Key(challenge.Id), + JsonSerializer.Serialize(new ChallengeRecord(login, challenge)), TimeSpan.FromMinutes(2), When.NotExists); + if (!stored) throw new InvalidOperationException("Challenge could not be created"); + return challenge; + } + + public async Task VerifyAndConsume(LoginData login) + { + try + { + Validate(login); + if (!Guid.TryParseExact(login.ChallengeId, "N", out _)) return false; + var value = await redis.GetDatabase().StringGetDeleteAsync(Key(login.ChallengeId)); + if (value.IsNullOrEmpty) return false; + var record = JsonSerializer.Deserialize((string)value!)!; + if (record.Challenge.ExpiresAt <= DateTimeOffset.UtcNow) return false; + var message = AuthenticationProtocol.GetMessage(login, record.Challenge); + if (!message.AsSpan().SequenceEqual(AuthenticationProtocol.GetMessage(record.Login, record.Challenge))) return false; + using var rsa = RSA.Create(); + rsa.ImportRSAPublicKey(login.PublicKey, out _); + return rsa.VerifyData(message, login.Signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss); + } + catch (Exception ex) when (ex is CryptographicException or ArgumentException or JsonException) + { + return false; + } + } + + private static string Key(string id) => $"auth:{AuthenticationProtocol.Epoch}:challenge:{id}"; + + private static void Validate(LoginData login) + { + if (login.PublicKey == null || login.PublicKey.Length > 2048 || login.Signature == null || login.Signature.Length > 1024 || + login.AuthenticationEpoch != AuthenticationProtocol.Epoch || login.ProtocolVersion != ProtocolVersion.CURRENT || + string.IsNullOrEmpty(login.Version) || login.Version.Length > 100 || + AuthenticationProtocol.GetIdentity(login.PublicKey) != login.Identity || + !AuthenticationProtocol.IsInstanceOf(login.ClientInstanceId, login.Identity)) + throw new CryptographicException("Invalid authentication identity"); + } +} diff --git a/src/ByteSync.ServerCommon/Services/Clients/ClientsGroupsHubService.cs b/src/ByteSync.ServerCommon/Services/Clients/ClientsGroupsHubService.cs index d99be0520..0a20e7ebd 100644 --- a/src/ByteSync.ServerCommon/Services/Clients/ClientsGroupsHubService.cs +++ b/src/ByteSync.ServerCommon/Services/Clients/ClientsGroupsHubService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Interfaces.Hub; +using ByteSync.Common.Interfaces.Hub; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Interfaces.Factories; using ByteSync.ServerCommon.Interfaces.Services.Clients; @@ -12,21 +12,28 @@ public class ClientsGroupsHubService : IClientsGroupsHubService private readonly IHubContext, IHubByteSyncPush> _hubContext; private readonly IClientsGroupIdFactory _clientsGroupIdFactory; private readonly ILogger _logger; + private readonly ByteSync.ServerCommon.Interfaces.Repositories.ICloudSessionsRepository _sessions; + private readonly ByteSync.ServerCommon.Interfaces.Repositories.ILobbyRepository _lobbies; public ClientsGroupsHubService(IHubContext, IHubByteSyncPush> hubContext, IClientsGroupIdFactory clientsGroupIdFactory, - ILogger logger) + ILogger logger, ByteSync.ServerCommon.Interfaces.Repositories.ICloudSessionsRepository sessions, + ByteSync.ServerCommon.Interfaces.Repositories.ILobbyRepository lobbies) { _hubContext = hubContext; _clientsGroupIdFactory = clientsGroupIdFactory; _logger = logger; + _sessions = sessions; + _lobbies = lobbies; } public async Task AddToSessionGroup(Client client, string sessionId) { + if (!await IsAuthorizedSubscription(client, _clientsGroupIdFactory.GetSessionGroupId(sessionId))) throw new UnauthorizedAccessException(); await AddToGroup(client, _clientsGroupIdFactory.GetSessionGroupId(sessionId)).ConfigureAwait(false); } public async Task AddToLobbyGroup(Client client, string lobbyId) { + if (!await IsAuthorizedSubscription(client, _clientsGroupIdFactory.GetLobbyGroupId(lobbyId))) throw new UnauthorizedAccessException(); await AddToGroup(client, _clientsGroupIdFactory.GetLobbyGroupId(lobbyId)).ConfigureAwait(false); } @@ -40,7 +47,8 @@ private async Task AddToGroup(Client client, string groupName) return; } - await _hubContext.Groups.AddToGroupAsync(connectionId, groupName).ConfigureAwait(false); + foreach (var id in client.ConnectionIds.Distinct()) + await _hubContext.Groups.AddToGroupAsync(id, groupName).ConfigureAwait(false); } public async Task RemoveFromSessionGroup(Client client, string sessionId) @@ -63,21 +71,41 @@ private async Task RemoveFromGroup(Client client, string groupName) return; } - await _hubContext.Groups.RemoveFromGroupAsync(connectionId, groupName).ConfigureAwait(false); + foreach (var id in client.ConnectionIds.Distinct()) + await _hubContext.Groups.RemoveFromGroupAsync(id, groupName).ConfigureAwait(false); } public async Task AddClientGroup(string connectionId, Client client) { + ByteSync.ServerCommon.Security.SessionAuthorizationBehavior.RequireIdentity(client); await _hubContext.Groups.AddToGroupAsync(connectionId, _clientsGroupIdFactory.GetClientGroupId(client.ClientInstanceId)).ConfigureAwait(false); foreach (var subscribedGroup in client.SubscribedGroups) { + if (!await IsAuthorizedSubscription(client, subscribedGroup)) continue; _logger.LogInformation("Adding client {clientInstanceId} to subscribed group {subscribedGroup}", client.ClientInstanceId, subscribedGroup); await _hubContext.Groups.AddToGroupAsync(connectionId, subscribedGroup).ConfigureAwait(false); } } + private async Task IsAuthorizedSubscription(Client client, string group) + { + ByteSync.ServerCommon.Security.SessionAuthorizationBehavior.RequireIdentity(client); + var prefix = $"Auth{ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch}_"; + if (group.StartsWith(prefix + "Session_", StringComparison.Ordinal)) + { + var session = await _sessions.Get(group[(prefix.Length + "Session_".Length)..]); + return session is { IsSessionRemoved: false } && session.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && session.FindMember(client.ClientInstanceId)?.Identity == client.Identity; + } + if (group.StartsWith(prefix + "Lobby_", StringComparison.Ordinal)) + { + var lobby = await _lobbies.Get(group[(prefix.Length + "Lobby_".Length)..]); + return lobby?.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && lobby.GetLobbyMemberByClientInstanceId(client.ClientInstanceId) != null; + } + return false; + } + public async Task RemoveClientGroup(string connectionId, Client client) { await _hubContext.Groups.RemoveFromGroupAsync(connectionId, _clientsGroupIdFactory.GetClientGroupId(client.ClientInstanceId)).ConfigureAwait(false); diff --git a/src/ByteSync.ServerCommon/Services/Clients/ClientsService.cs b/src/ByteSync.ServerCommon/Services/Clients/ClientsService.cs index a82f90e9d..862f1ef4e 100644 --- a/src/ByteSync.ServerCommon/Services/Clients/ClientsService.cs +++ b/src/ByteSync.ServerCommon/Services/Clients/ClientsService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.EndPoints; +using ByteSync.Common.Business.EndPoints; using ByteSync.Common.Helpers; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Helpers; @@ -32,6 +32,9 @@ public ClientsService(IByteSyncEndpointFactory byteSyncEndpointFactory, { var result = await _clientsRepository.AddOrUpdate(clientInstanceId, client => { + if (client == null || client.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || + !ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf(client.ClientInstanceId, client.Identity ?? "")) + return null; if (client != null) { client.SetConnected(connectionId); diff --git a/src/ByteSync.ServerCommon/Services/Clients/InvokeClientsService.cs b/src/ByteSync.ServerCommon/Services/Clients/InvokeClientsService.cs index 896740c24..29bb69b7c 100644 --- a/src/ByteSync.ServerCommon/Services/Clients/InvokeClientsService.cs +++ b/src/ByteSync.ServerCommon/Services/Clients/InvokeClientsService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Interfaces.Hub; +using ByteSync.Common.Interfaces.Hub; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Business.Sessions; using ByteSync.ServerCommon.Interfaces.Factories; @@ -76,7 +76,7 @@ private IHubByteSyncPush GroupExcept(string groupId, Client client) var connectionId = client.ConnectionIds.LastOrDefault(); if (connectionId != null) { - return _hubContext.Clients.GroupExcept(groupId, client.ConnectionIds.Last()); + return _hubContext.Clients.GroupExcept(groupId, client.ConnectionIds.ToArray()); } else { diff --git a/src/ByteSync.ServerCommon/Services/CloudSessionProfileService.cs b/src/ByteSync.ServerCommon/Services/CloudSessionProfileService.cs index edd9fada0..46c957d47 100644 --- a/src/ByteSync.ServerCommon/Services/CloudSessionProfileService.cs +++ b/src/ByteSync.ServerCommon/Services/CloudSessionProfileService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Lobbies.Connections; +using ByteSync.Common.Business.Lobbies.Connections; using ByteSync.Common.Business.Profiles; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Business.Sessions; @@ -30,11 +30,14 @@ public CloudSessionProfileService(ICloudSessionProfileRepository cloudSessionPro public async Task CreateCloudSessionProfile(string sessionId, Client client) { + Security.SessionAuthorizationBehavior.RequireIdentity(client); var sessionMemberData = await _cloudSessionsRepository.GetSessionMember(sessionId, client.ClientInstanceId); - if (sessionMemberData != null) + if (sessionMemberData != null && sessionMemberData.Identity == client.Identity && + !sessionMemberData.CloudSessionData.IsSessionRemoved && sessionMemberData.CloudSessionData.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch) { CloudSessionProfileEntity cloudSessionProfileEntity = new CloudSessionProfileEntity(); + cloudSessionProfileEntity.AuthenticationEpoch = ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch; cloudSessionProfileEntity.CloudSessionProfileId = $"CSPID_{Guid.NewGuid()}"; CloudSessionProfileData f; @@ -46,7 +49,8 @@ public async Task CreateCloudSessionProfile(str var slot = new CloudSessionProfileSlot { ProfileClientId = profileClientId, - ClientId = sessionMember.ClientId + ClientId = sessionMember.ClientId, + OriginalClientInstanceId = sessionMember.ClientInstanceId }; cloudSessionProfileEntity.Slots.Add(slot); @@ -74,13 +78,15 @@ public async Task CreateCloudSessionProfile(str public async Task GetCloudSessionProfileData(GetCloudSessionProfileDataParameters getCloudSessionProfileDataParameters, Client client) { + Security.SessionAuthorizationBehavior.RequireIdentity(client); var sessionMemberData = await _cloudSessionsRepository.GetSessionMember(getCloudSessionProfileDataParameters.SessionId, client.ClientInstanceId); - if (sessionMemberData != null) + if (sessionMemberData != null && sessionMemberData.Identity == client.Identity && + !sessionMemberData.CloudSessionData.IsSessionRemoved && sessionMemberData.CloudSessionData.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch) { var cloudSessionProfileEntity = await _cloudSessionProfileRepository.Get(getCloudSessionProfileDataParameters.CloudSessionProfileId); - if (cloudSessionProfileEntity != null && cloudSessionProfileEntity.Slots.Any(s => s.ClientId == sessionMemberData.ClientId)) + if (cloudSessionProfileEntity != null && cloudSessionProfileEntity.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && cloudSessionProfileEntity.Slots.Any(s => s.ClientId == sessionMemberData.ClientId)) { var result = BuildCloudSessionProfileCreationData(sessionMemberData, cloudSessionProfileEntity); @@ -93,9 +99,10 @@ public async Task CreateCloudSessionProfile(str public async Task GetProfileDetailsPassword(GetProfileDetailsPasswordParameters parameters, Client client) { + Security.SessionAuthorizationBehavior.RequireIdentity(client); var cloudSessionProfile = await _cloudSessionProfileRepository.Get(parameters.CloudSessionProfileId); - if (cloudSessionProfile != null && cloudSessionProfile.Slots.Any(s => s.ProfileClientId == parameters.ProfileClientId)) + if (cloudSessionProfile != null && cloudSessionProfile.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && cloudSessionProfile.Slots.Any(s => s.ProfileClientId == parameters.ProfileClientId && s.ClientId == client.Identity)) { _logger.LogInformation("GetProfileDetailsPassword: result OK for Client:{ClientInstanceId} with CloudSessionProfileId:{CloudSessionProfileId}", client.ClientInstanceId, parameters.CloudSessionProfileId); @@ -111,6 +118,9 @@ public async Task CreateCloudSessionProfile(str public async Task DeleteCloudSessionProfile(DeleteCloudSessionProfileParameters parameters, Client byteSyncEndpoint) { + Security.SessionAuthorizationBehavior.RequireIdentity(byteSyncEndpoint); + var profile = await _cloudSessionProfileRepository.Get(parameters.CloudSessionProfileId); + if (profile == null || profile.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || !profile.Slots.Any(s => s.ClientId == byteSyncEndpoint.Identity)) throw new UnauthorizedAccessException(); await _cloudSessionProfileRepository.Delete(parameters.CloudSessionProfileId); return true; @@ -125,7 +135,8 @@ private CloudSessionProfileData BuildCloudSessionProfileCreationData(SessionMemb cloudSessionProfileCreationData.ProfileDetailsPassword = cloudSessionProfileEntity.ProfileDetailsPassword; cloudSessionProfileCreationData.CreationDateTime = cloudSessionProfileEntity.CreationDateTime; cloudSessionProfileCreationData.RequesterProfileClientId = - cloudSessionProfileEntity.Slots.Single(s => s.ClientId == sessionMemberData.ClientId).ProfileClientId; + cloudSessionProfileEntity.Slots.Single(s => s.ClientId == sessionMemberData.ClientId && + (s.OriginalClientInstanceId == sessionMemberData.ClientInstanceId || s.ProfileClientId == sessionMemberData.ProfileClientId)).ProfileClientId; return cloudSessionProfileCreationData; } diff --git a/src/ByteSync.ServerCommon/Services/CloudSessionsService.cs b/src/ByteSync.ServerCommon/Services/CloudSessionsService.cs index b9fd25ff4..09c76cad2 100644 --- a/src/ByteSync.ServerCommon/Services/CloudSessionsService.cs +++ b/src/ByteSync.ServerCommon/Services/CloudSessionsService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.EndPoints; +using ByteSync.Common.Business.EndPoints; using ByteSync.Common.Business.Sessions.Cloud; using ByteSync.Common.Business.Sessions.Cloud.Connections; using ByteSync.Common.Helpers; @@ -56,8 +56,16 @@ public async Task PreJoinCloudSession(Client client, PublicKeyInfo publicKeyInfo var updateResult = await _cloudSessionsRepository.Update(sessionId, cloudSessionData => { SessionMemberData joiner = new SessionMemberData(client, publicKeyInfo, profileClientId, cloudSessionData); + if (cloudSessionData.IsSessionActivated || cloudSessionData.IsSessionRemoved || cloudSessionData.SessionMembers.Count >= 5 || + cloudSessionData.FindMember(validatorClientInstanceId) == null) throw new UnauthorizedAccessException(); + if (ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(publicKeyInfo.PublicKey) != client.Identity) + throw new UnauthorizedAccessException(); joiner.ValidatorInstanceId = validatorClientInstanceId; + joiner.JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5); + var existing = cloudSessionData.PreSessionMembers.SingleOrDefault(m => m.ClientInstanceId == client.ClientInstanceId && + m.Identity == client.Identity && m.JoinExpiresAt > DateTimeOffset.UtcNow && m.ValidatorInstanceId == validatorClientInstanceId); + if (existing != null) return false; cloudSessionData.PreSessionMembers.Remove(joiner); cloudSessionData.PreSessionMembers.RemoveAll(m => m.ClientInstanceId.Equals(joiner.ClientInstanceId)); @@ -149,19 +157,23 @@ private async Task CheckCanJoinLimit(Client currentClient, List { - if (cloudSessionData is { IsSessionActivated: false, IsSessionRemoved: false }) + if (cloudSessionData is { IsSessionActivated: false, IsSessionRemoved: false } && + cloudSessionData.FindMember(caller.ClientInstanceId)?.Identity == caller.Identity) { joiner = cloudSessionData .PreSessionMembers .FirstOrDefault(m => Equals(m.ClientInstanceId, parameters.JoinerClientInstanceId) && - Equals(m.ValidatorInstanceId, parameters.ValidatorInstanceId)); + Equals(m.ValidatorInstanceId, parameters.ValidatorInstanceId) && + m.JoinExpiresAt > DateTimeOffset.UtcNow && string.IsNullOrEmpty(m.FinalizationPassword)); if (joiner != null) { @@ -171,7 +183,7 @@ public async Task ValidateJoinCloudSession(ValidateJoinCloudSessionParameters pa parameters.FinalizationPassword = finaliationPassword; } - return true; + return joiner != null; } else { @@ -296,7 +308,7 @@ public async Task InformPasswordIsWrong(Client client, string sessionId, string public async Task GiveCloudSessionPasswordExchangeKey(Client client, GiveCloudSessionPasswordExchangeKeyParameters parameters) { var preSessionMemberData = await _cloudSessionsRepository.GetSessionPreMember(parameters.SessionId, parameters.JoinerInstanceId); - if (preSessionMemberData == null) + if (preSessionMemberData == null || preSessionMemberData.JoinExpiresAt <= DateTimeOffset.UtcNow) { _logger.LogWarning("GiveCloudSessionPasswordExchangeKey: PreSessionMember not found for {session}", parameters.SessionId); return; diff --git a/src/ByteSync.ServerCommon/Services/LobbyService.cs b/src/ByteSync.ServerCommon/Services/LobbyService.cs index 70085a1c9..16bcdd09f 100644 --- a/src/ByteSync.ServerCommon/Services/LobbyService.cs +++ b/src/ByteSync.ServerCommon/Services/LobbyService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Lobbies; +using ByteSync.Common.Business.Lobbies; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Entities; using ByteSync.ServerCommon.Interfaces.Repositories; @@ -27,6 +27,7 @@ public LobbyService(ILobbyRepository lobbyRepository, IInvokeClientsService invo var result = await _lobbyRepository.Update(lobbyId, lobby => { + if (lobby.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch) throw new UnauthorizedAccessException(); lobbyMember = lobby.ConnectedLobbyMembers.SingleOrDefault(m => m.ClientInstanceId.Equals(client.ClientInstanceId)); if (lobbyMember != null) @@ -58,13 +59,13 @@ public async Task SendLobbyCloudSessionCredentials(LobbyCloudSessionCredentials { var lobby = await _lobbyRepository.Get(lobbyCloudSessionCredentials.LobbyId); - if (lobby != null) + if (lobby?.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch) { var firstCell = lobby.LobbyMemberCells.FirstOrDefault(); if (firstCell is { LobbyMember: not null } && firstCell.LobbyMember.ClientInstanceId .Equals(client.ClientInstanceId)) { - _logger.LogInformation("SendLobbyCloudSessionCredentials: {@credentials} sent to {@recipient}", - lobbyCloudSessionCredentials, lobbyCloudSessionCredentials.Recipient); + if (lobby.GetLobbyMemberByClientInstanceId(lobbyCloudSessionCredentials.Recipient) == null) throw new UnauthorizedAccessException(); + _logger.LogInformation("Lobby credentials sent to {Recipient}", lobbyCloudSessionCredentials.Recipient); await _invokeClientsService.Client(lobbyCloudSessionCredentials.Recipient) .LobbyCloudSessionCredentialsSent(lobbyCloudSessionCredentials).ConfigureAwait(false); @@ -76,7 +77,7 @@ public async Task SendLobbyCheckInfos(LobbyCheckInfo lobbyCheckInfo, Client clie { var lobby = await _lobbyRepository.Get(lobbyCheckInfo.LobbyId); - if (lobby != null && lobby.LobbyMemberCells.Any(c => c.LobbyMember != null && c.LobbyMember.ClientInstanceId == client.ClientInstanceId)) + if (lobby?.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && lobby.LobbyMemberCells.Any(c => c.LobbyMember != null && c.LobbyMember.ClientInstanceId == client.ClientInstanceId)) { await _invokeClientsService.LobbyGroup(lobbyCheckInfo.LobbyId) .LobbyCheckInfosSent(lobbyCheckInfo.LobbyId, lobbyCheckInfo).ConfigureAwait(false); diff --git a/src/ByteSync.ServerCommon/Services/SharedFilesService.cs b/src/ByteSync.ServerCommon/Services/SharedFilesService.cs index 4587a369f..93d1e4b1d 100644 --- a/src/ByteSync.ServerCommon/Services/SharedFilesService.cs +++ b/src/ByteSync.ServerCommon/Services/SharedFilesService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.SharedFiles; +using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Business.Sessions; using ByteSync.ServerCommon.Business.Settings; @@ -68,7 +68,6 @@ public async Task AssertFilePartIsDownloaded(Client downloadedBy, TransferParame var sharedFileDefinition = transferParameters.SharedFileDefinition; var partNumber = transferParameters.PartNumber!.Value; bool shouldDeletePart = false; - bool unregister = false; await _sharedFilesRepository.AddOrUpdate(sharedFileDefinition, sharedFileData => { @@ -83,10 +82,6 @@ await _sharedFilesRepository.AddOrUpdate(sharedFileDefinition, sharedFileData => shouldDeletePart = isPartFullyDownloaded && !_appSettings.RetainFilesAfterTransfer; - if (sharedFileData.IsFullyDownloaded) - { - unregister = true; - } return sharedFileData; }); @@ -95,18 +90,6 @@ await _sharedFilesRepository.AddOrUpdate(sharedFileDefinition, sharedFileData => { await DeleteDownloadedPart(transferParameters, sharedFileDefinition, partNumber); } - - if (unregister) - { - try - { - await _sharedFilesRepository.Forget(sharedFileDefinition); - } - catch (Exception ex) - { - _logger.LogError(ex, "Can not unregister SharedFileDefinition:{Id}", sharedFileDefinition.Id); - } - } } private async Task DeleteDownloadedPart(TransferParameters transferParameters, diff --git a/src/ByteSync.ServerCommon/Services/Storage/AzureBlobStorageService.cs b/src/ByteSync.ServerCommon/Services/Storage/AzureBlobStorageService.cs index 568baf0e8..778a3d76e 100644 --- a/src/ByteSync.ServerCommon/Services/Storage/AzureBlobStorageService.cs +++ b/src/ByteSync.ServerCommon/Services/Storage/AzureBlobStorageService.cs @@ -1,4 +1,4 @@ -using Azure.Storage; +using Azure.Storage; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Azure.Storage.Sas; @@ -39,16 +39,8 @@ private async Task ComputeUrl(SharedFileDefinition sharedFileDefinition, BlobClient blobClient = container.GetBlobClient(finalFileName); - double minutes; - if (permission == BlobSasPermissions.Write) - { - minutes = 60; - } - else - { - minutes = 20; - } - + const double minutes = 5; + BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = blobClient.BlobContainerName, @@ -73,8 +65,7 @@ private async Task ComputeUrl(SharedFileDefinition sharedFileDefinition, private string GetServerFileName(SharedFileDefinition sharedFileDefinition, int partNumber) { - return sharedFileDefinition.SessionId + "_" + sharedFileDefinition.ClientInstanceId + "_" + - sharedFileDefinition.GetFileName(partNumber); + return $"{Guid.ParseExact(sharedFileDefinition.StorageObjectId!, "N"):N}/part-{partNumber}"; } public async Task DeleteObject(SharedFileDefinition sharedFileDefinition, int partNumber) diff --git a/src/ByteSync.ServerCommon/Services/Storage/CloudflareR2Service.cs b/src/ByteSync.ServerCommon/Services/Storage/CloudflareR2Service.cs index e6d0c63bf..e11af2099 100644 --- a/src/ByteSync.ServerCommon/Services/Storage/CloudflareR2Service.cs +++ b/src/ByteSync.ServerCommon/Services/Storage/CloudflareR2Service.cs @@ -34,7 +34,7 @@ public async Task GetUploadFileUrl(SharedFileDefinition sharedFileDefini BucketName = _cloudflareR2Settings.BucketName, Key = key, Verb = HttpVerb.PUT, - Expires = DateTime.UtcNow.AddMinutes(60) + Expires = DateTime.UtcNow.AddMinutes(5) }; var preSignedUrl = await s3Client.GetPreSignedURLAsync(request); @@ -51,7 +51,7 @@ public async Task GetDownloadFileUrl(SharedFileDefinition sharedFileDefi BucketName = _cloudflareR2Settings.BucketName, Key = key, Verb = HttpVerb.GET, - Expires = DateTime.UtcNow.AddMinutes(20) + Expires = DateTime.UtcNow.AddMinutes(5) }; return await s3Client.GetPreSignedURLAsync(request); @@ -77,8 +77,7 @@ public async Task DeleteObject(SharedFileDefinition sharedFileDefinition, int pa private string GetServerFileName(SharedFileDefinition sharedFileDefinition, int partNumber) { - var fileName = sharedFileDefinition.GetFileName(partNumber); - var serverFileName = sharedFileDefinition.SessionId + "_" + sharedFileDefinition.ClientInstanceId + "_" + fileName; + var serverFileName = $"{Guid.ParseExact(sharedFileDefinition.StorageObjectId!, "N"):N}/part-{partNumber}"; return serverFileName; } diff --git a/src/ByteSync.ServerCommon/Services/Storage/Factories/CloudflareR2ClientFactory.cs b/src/ByteSync.ServerCommon/Services/Storage/Factories/CloudflareR2ClientFactory.cs index 2113d8776..3c392e654 100644 --- a/src/ByteSync.ServerCommon/Services/Storage/Factories/CloudflareR2ClientFactory.cs +++ b/src/ByteSync.ServerCommon/Services/Storage/Factories/CloudflareR2ClientFactory.cs @@ -15,7 +15,7 @@ public CloudflareR2ClientFactory(IOptions settings) _settings = settings.Value; } - public AmazonS3Client GetClient() + public IAmazonS3 GetClient() { if (_client == null) { diff --git a/src/ByteSync.ServerCommon/Services/TokensFactory.cs b/src/ByteSync.ServerCommon/Services/TokensFactory.cs index 37de22a54..2c9b2adcb 100644 --- a/src/ByteSync.ServerCommon/Services/TokensFactory.cs +++ b/src/ByteSync.ServerCommon/Services/TokensFactory.cs @@ -2,6 +2,7 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text; +using ByteSync.Common.Business.Auth; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Business.Settings; using ByteSync.ServerCommon.Interfaces.Factories; @@ -21,6 +22,9 @@ public TokensFactory(IOptions appSettings) public JwtTokens BuildTokens(Client client) { + if (client.AuthenticationEpoch != AuthenticationProtocol.Epoch || + !AuthenticationProtocol.IsInstanceOf(client.ClientInstanceId, client.Identity ?? "")) + throw new UnauthorizedAccessException("Verified identity required"); var jwtToken = GenerateJwtToken(client); var refreshToken = GenerateRefreshToken(client); @@ -41,6 +45,8 @@ private string GenerateJwtToken(Client client) new(AuthConstants.CLAIM_CLIENT_INSTANCE_ID, client.ClientInstanceId), new(AuthConstants.CLAIM_CLIENT_ID, client.ClientId), new(AuthConstants.CLAIM_VERSION, client.Version), + new(AuthConstants.CLAIM_IDENTITY, client.Identity!), + new(AuthConstants.CLAIM_AUTHENTICATION_EPOCH, AuthenticationProtocol.Epoch.ToString()), new(AuthConstants.CLAIM_OS_PLATFORM, client.OsPlatform.ToString()), }; @@ -73,10 +79,11 @@ private RefreshToken GenerateRefreshToken(Client client) return new RefreshToken { Token = token, + AuthenticationEpoch = AuthenticationProtocol.Epoch, Expires = DateTime.UtcNow.AddSeconds(_appSettings.JwtDurationInSeconds * 2), Created = DateTimeOffset.UtcNow, CreatedByIp = client.IpAddress }; } } -} \ No newline at end of file +} diff --git a/src/ByteSync.ServerCommon/Services/TransferAuthorizationService.cs b/src/ByteSync.ServerCommon/Services/TransferAuthorizationService.cs new file mode 100644 index 000000000..cf2fe615d --- /dev/null +++ b/src/ByteSync.ServerCommon/Services/TransferAuthorizationService.cs @@ -0,0 +1,76 @@ +using ByteSync.Common.Business.Auth; +using System.Text.Json; +using ByteSync.Common.Business.SharedFiles; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Business.Sessions; +using ByteSync.ServerCommon.Business.Settings; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Services; +using Microsoft.Extensions.Options; + +namespace ByteSync.ServerCommon.Services; + +public class TransferAuthorizationService(ICloudSessionsRepository sessions, ISharedFilesRepository files, + ITrackingActionRepository actions, IOptions settings) : ITransferAuthorizationService +{ + public async Task Authorize(string sessionId, Client client, TransferParameters parameters, bool upload, bool create) + { + Security.SessionAuthorizationBehavior.RequireIdentity(client); + var session = await sessions.Get(sessionId); + var supplied = parameters.SharedFileDefinition; + if (session == null || session.IsSessionRemoved || session.AuthenticationEpoch != AuthenticationProtocol.Epoch || session.FindMember(client.ClientInstanceId)?.Identity != client.Identity || + supplied == null || supplied.SessionId != sessionId || parameters.SessionId != sessionId || + string.IsNullOrWhiteSpace(supplied.Id) || supplied.Id.Length > 100 || !Enum.IsDefined(supplied.SharedFileType) || + parameters.PartNumber is <= 0 or > 1000000 || parameters.TotalParts is <= 0 or > 1000000 || parameters.PartSizeInBytes is < 0) + throw new UnauthorizedAccessException("Invalid transfer"); + if ((supplied.IsInventory || supplied.IsSynchronization || supplied.IsSynchronizationStartData) && !session.IsSessionActivated) + throw new UnauthorizedAccessException("Session is not activated for file transfers"); + if (upload && supplied.ClientInstanceId != client.ClientInstanceId) throw new UnauthorizedAccessException(); + var recipients = session.SessionMembers.Where(m => m.ClientInstanceId != supplied.ClientInstanceId) + .Select(m => m.ClientInstanceId).ToHashSet(); + if (supplied.IsSynchronization) + { + if (supplied.ActionsGroupIds == null || supplied.ActionsGroupIds.Count == 0 || supplied.ActionsGroupIds.Count > 10000) + throw new UnauthorizedAccessException(); + HashSet? targets = null; + foreach (var id in supplied.ActionsGroupIds) + { + var action = await actions.GetOrThrow(sessionId, id); + if (action.SourceClientInstanceId != supplied.ClientInstanceId) throw new UnauthorizedAccessException(); + var actionTargets = action.TargetClientInstanceAndNodeIds.Select(t => t.ClientInstanceId).ToHashSet(); + if (targets == null) targets = actionTargets; + else targets.IntersectWith(actionTargets); + } + recipients.IntersectWith(targets!); + } + if (create) + { + await files.AddOrUpdate(supplied, existing => + { + if (existing != null) { CheckDefinition(existing.SharedFileDefinition, supplied); return existing; } + var definition = JsonSerializer.Deserialize(JsonSerializer.Serialize(supplied))!; + definition.StorageObjectId = Guid.NewGuid().ToString("N"); + return new SharedFileData(definition, recipients, settings.Value.DefaultStorageProvider); + }); + } + var record = await files.Get(supplied.Id) ?? throw new UnauthorizedAccessException("Unregistered transfer"); + CheckDefinition(record.SharedFileDefinition, supplied); + if (!upload && (!record.Recipients.Contains(client.ClientInstanceId) || + (parameters.PartNumber.HasValue && !record.UploadedPartsNumbers.Contains(parameters.PartNumber.Value)))) + throw new UnauthorizedAccessException("Transfer recipient or part mismatch"); + if (record.TotalParts.HasValue && (parameters.PartNumber > record.TotalParts || + (parameters.TotalParts.HasValue && parameters.TotalParts != record.TotalParts))) throw new UnauthorizedAccessException(); + if (parameters.TotalParts.HasValue && record.UploadedPartsNumbers.Any(p => p > parameters.TotalParts.Value)) + throw new UnauthorizedAccessException("Total parts is inconsistent with uploaded parts"); + parameters.SharedFileDefinition = record.SharedFileDefinition; + parameters.StorageProvider = record.StorageProvider; + } + + private static void CheckDefinition(SharedFileDefinition stored, SharedFileDefinition supplied) + { + if (!stored.Equals(supplied) || stored.AdditionalName != supplied.AdditionalName || stored.IsMultiFileZip != supplied.IsMultiFileZip || + !(stored.IV ?? []).SequenceEqual(supplied.IV ?? []) || + !(stored.ActionsGroupIds ?? []).SequenceEqual(supplied.ActionsGroupIds ?? [])) + throw new UnauthorizedAccessException("Transfer definition mismatch"); + } +} diff --git a/src/ByteSync.ServerCommon/Services/TransferLocationService.cs b/src/ByteSync.ServerCommon/Services/TransferLocationService.cs index eb48e3e72..7e933b83f 100644 --- a/src/ByteSync.ServerCommon/Services/TransferLocationService.cs +++ b/src/ByteSync.ServerCommon/Services/TransferLocationService.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.SharedFiles; +using ByteSync.Common.Business.SharedFiles; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Business.Sessions; using ByteSync.ServerCommon.Business.Settings; @@ -18,17 +18,19 @@ public class TransferLocationService : ITransferLocationService private readonly ICloudflareR2Service _cloudflareR2Service; private readonly ILogger _logger; private readonly StorageProvider _storageProvider; + private readonly ITransferAuthorizationService _authorization; public TransferLocationService(ICloudSessionsRepository cloudSessionsRepository, IAzureBlobStorageService azureBlobStorageService, ICloudflareR2Service cloudflareR2Service, IOptions appSettings, - ILogger logger) + ILogger logger, ITransferAuthorizationService authorization) { _cloudSessionsRepository = cloudSessionsRepository; _azureBlobStorageService = azureBlobStorageService; _cloudflareR2Service = cloudflareR2Service; _storageProvider = appSettings.Value.DefaultStorageProvider; _logger = logger; + _authorization = authorization; } public async Task GetUploadFileUrl(string sessionId, Client client, TransferParameters transferParameters) @@ -38,6 +40,7 @@ public async Task GetUploadFileUrl(string sessionId, Client client, Tran throw new ArgumentOutOfRangeException(nameof(transferParameters.PartNumber), "Part number must be greater than 0"); } + await _authorization.Authorize(sessionId, client, transferParameters, true, true); var sessionMemberData = await _cloudSessionsRepository.GetSessionMember(sessionId, client); var sharedFileDefinition = transferParameters.SharedFileDefinition; var partNumber = transferParameters.PartNumber.Value; @@ -46,7 +49,7 @@ public async Task GetUploadFileUrl(string sessionId, Client client, Tran if (canGetUrl) { - string uploadUrl = _storageProvider switch + string uploadUrl = transferParameters.StorageProvider switch { StorageProvider.AzureBlobStorage => await _azureBlobStorageService.GetUploadFileUrl(sharedFileDefinition, partNumber), StorageProvider.CloudflareR2 => await _cloudflareR2Service.GetUploadFileUrl(sharedFileDefinition, partNumber), @@ -71,6 +74,7 @@ public async Task GetDownloadFileUrl(string sessionId, Client client, Tr throw new ArgumentOutOfRangeException(nameof(transferParameters.PartNumber), "Part number must be greater than 0"); } + await _authorization.Authorize(sessionId, client, transferParameters, false, false); var sessionMemberData = await _cloudSessionsRepository.GetSessionMember(sessionId, client); var sharedFileDefinition = transferParameters.SharedFileDefinition; var partNumber = transferParameters.PartNumber.Value; @@ -79,7 +83,7 @@ public async Task GetDownloadFileUrl(string sessionId, Client client, Tr if (canGetUrl) { - string downloadUrl = _storageProvider switch + string downloadUrl = transferParameters.StorageProvider switch { StorageProvider.AzureBlobStorage => await _azureBlobStorageService.GetDownloadFileUrl(sharedFileDefinition, partNumber), StorageProvider.CloudflareR2 => await _cloudflareR2Service.GetDownloadFileUrl(sharedFileDefinition, partNumber), @@ -98,7 +102,7 @@ public bool IsSharedFileDefinitionAllowed(SessionMemberData? sessionMemberData, { bool canGetUrl = false; - if (sessionMemberData != null && sharedFileDefinition != null) + if (sessionMemberData != null && sharedFileDefinition != null && sharedFileDefinition.SessionId == sessionMemberData.CloudSessionData.SessionId) { canGetUrl = sessionMemberData.CloudSessionData.SessionMembers.Any(smd => Equals(smd.ClientInstanceId, sharedFileDefinition.ClientInstanceId)); diff --git a/tests/ByteSync.Client.IntegrationTests/Services/Applications/EnvironmentService_Tests.cs b/tests/ByteSync.Client.IntegrationTests/Services/Applications/EnvironmentService_Tests.cs index 4c38c76f0..ca0fff1d6 100644 --- a/tests/ByteSync.Client.IntegrationTests/Services/Applications/EnvironmentService_Tests.cs +++ b/tests/ByteSync.Client.IntegrationTests/Services/Applications/EnvironmentService_Tests.cs @@ -141,7 +141,7 @@ public void SetClientId_sets_ids_and_instance_contains_guid() { var service = new EnvironmentService(new MsixPfnParser()); - var clientId = "client-123"; + var clientId = new string('A', 64); service.SetClientId(clientId); service.ClientId.Should().Be(clientId); diff --git a/tests/ByteSync.Client.IntegrationTests/Services/Inventories/FullInventoryRunner_IntegrationTests.cs b/tests/ByteSync.Client.IntegrationTests/Services/Inventories/FullInventoryRunner_IntegrationTests.cs index 2af6a269b..bea815ded 100644 --- a/tests/ByteSync.Client.IntegrationTests/Services/Inventories/FullInventoryRunner_IntegrationTests.cs +++ b/tests/ByteSync.Client.IntegrationTests/Services/Inventories/FullInventoryRunner_IntegrationTests.cs @@ -241,7 +241,7 @@ private IInventoryBuilder CreateInventoryBuilder(DataNode dataNode, IEnumerable< var inventoryFileAnalyzerLogger = new Mock>().Object; var saver = new InventorySaver(); - var analyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, processData, saver, inventoryFileAnalyzerLogger); + var analyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, processData, saver, inventoryFileAnalyzerLogger, Moq.Mock.Of()); var inventoryBuilder = new InventoryBuilder( sessionMember, diff --git a/tests/ByteSync.Client.IntegrationTests/Services/Inventories/InventoryBuilderAccessHandling_IntegrationTests.cs b/tests/ByteSync.Client.IntegrationTests/Services/Inventories/InventoryBuilderAccessHandling_IntegrationTests.cs index ac3075a34..dc3a6001c 100644 --- a/tests/ByteSync.Client.IntegrationTests/Services/Inventories/InventoryBuilderAccessHandling_IntegrationTests.cs +++ b/tests/ByteSync.Client.IntegrationTests/Services/Inventories/InventoryBuilderAccessHandling_IntegrationTests.cs @@ -91,7 +91,7 @@ public async Task InaccessibleDirectory_MarkedAsInaccessibleAndSkipped_Windows() var inventorySaver = new InventorySaver(); var inventoryFileAnalyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, _inventoryProcessData, inventorySaver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryIndexer = new InventoryIndexer(); @@ -187,7 +187,7 @@ public async Task InaccessibleDirectory_MarkedAsInaccessibleAndSkipped_Posix() var inventorySaver = new InventorySaver(); var inventoryFileAnalyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, _inventoryProcessData, inventorySaver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryIndexer = new InventoryIndexer(); @@ -293,7 +293,7 @@ public async Task InaccessibleFile_MarkedAsInaccessibleButDirectoryAccessible_Wi var inventorySaver = new InventorySaver(); var inventoryFileAnalyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, _inventoryProcessData, inventorySaver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryIndexer = new InventoryIndexer(); @@ -385,7 +385,7 @@ public async Task InaccessibleFile_MarkedAsInaccessibleButDirectoryAccessible_Po var inventorySaver = new InventorySaver(); var inventoryFileAnalyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, _inventoryProcessData, inventorySaver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryIndexer = new InventoryIndexer(); @@ -495,7 +495,7 @@ public async Task InaccessibleFiles_NotCountedInIdentifiedVolume() var inventorySaver = new InventorySaver(); var inventoryFileAnalyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, _inventoryProcessData, inventorySaver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryIndexer = new InventoryIndexer(); @@ -609,7 +609,7 @@ public async Task InventoryContinues_AfterEncountering_InaccessibleItems() var inventorySaver = new InventorySaver(); var inventoryFileAnalyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, _inventoryProcessData, inventorySaver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryIndexer = new InventoryIndexer(); @@ -714,7 +714,7 @@ public async Task InaccessibleFile_AsInventoryPartOfTypeFile_Windows() var inventorySaver = new InventorySaver(); var inventoryFileAnalyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, _inventoryProcessData, inventorySaver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryIndexer = new InventoryIndexer(); @@ -794,7 +794,7 @@ public async Task InaccessibleFile_AsInventoryPartOfTypeFile_Posix() var inventorySaver = new InventorySaver(); var inventoryFileAnalyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, _inventoryProcessData, inventorySaver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryIndexer = new InventoryIndexer(); diff --git a/tests/ByteSync.Client.IntegrationTests/Services/Inventories/TestInventoryBuilder.cs b/tests/ByteSync.Client.IntegrationTests/Services/Inventories/TestInventoryBuilder.cs index 908976552..2113932be 100644 --- a/tests/ByteSync.Client.IntegrationTests/Services/Inventories/TestInventoryBuilder.cs +++ b/tests/ByteSync.Client.IntegrationTests/Services/Inventories/TestInventoryBuilder.cs @@ -921,7 +921,7 @@ private InventoryBuilder BuildInventoryBuilder(SessionSettings? sessionSettings var saver = new InventorySaver(); var analyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, inventoryProcessData, saver, - inventoryFileAnalyzerLoggerMock.Object); + inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); return new InventoryBuilder(sessionMemberInfo, dataNode, sessionSettings, inventoryProcessData, osPlatform, FingerprintModes.Rsync, inventoryBuilderloggerMock.Object, diff --git a/tests/ByteSync.Client.IntegrationTests/Services/Synchronizations/TestSynchronizationActionHandler.cs b/tests/ByteSync.Client.IntegrationTests/Services/Synchronizations/TestSynchronizationActionHandler.cs index a1f4cc829..ae9c232ec 100644 --- a/tests/ByteSync.Client.IntegrationTests/Services/Synchronizations/TestSynchronizationActionHandler.cs +++ b/tests/ByteSync.Client.IntegrationTests/Services/Synchronizations/TestSynchronizationActionHandler.cs @@ -1,5 +1,9 @@ -using Autofac; +using Autofac; using ByteSync.Business.Actions.Shared; +using ByteSync.Business.Configurations; +using ByteSync.Business.DataSources; +using ByteSync.Interfaces.Controls.Inventories; +using ByteSync.Services.Inventories; using ByteSync.Business.Inventories; using ByteSync.Business.Synchronizations; using ByteSync.Client.IntegrationTests.TestHelpers; @@ -30,11 +34,14 @@ namespace ByteSync.Client.IntegrationTests.Services.Synchronizations; public class TestSynchronizationActionHandler : IntegrationTest { private ByteSyncEndpoint _currentEndPoint; + private LocalSourceAuthorizationService _authorization; + private ApplicationSettings _settings; private SynchronizationActionHandler _synchronizationActionHandler; [SetUp] public void SetUp() { + RegisterType(); RegisterType(); RegisterType(); RegisterType(); @@ -60,9 +67,31 @@ public void SetUp() mockLocalApplicationDataManager.Setup(m => m.ApplicationDataPath).Returns(IOUtils.Combine(testDirectory.FullName, "ApplicationDataPath")); + _settings = new ApplicationSettings { InstallationId = "integration-test" }; + _settings.SetEncryptionPassword("local-test-password"); + _settings.InitializeRsa(); + var settings = Container.Resolve>(); + settings.Setup(s => s.GetCurrentApplicationSettings()).Returns(_settings); + settings.Setup(s => s.UpdateCurrentApplicationSettings(It.IsAny>(), It.IsAny())) + .Returns((Action update, bool save) => { update(_settings); return _settings; }); + _authorization = Container.Resolve(); _synchronizationActionHandler = Container.Resolve(); } + [TearDown] + public void DisposeSecuritySettings() => _settings?.PrivateRsa.Dispose(); + + private Task RunWithLocalPermissions(SharedActionsGroup group, CancellationToken cancellationToken = default) + { + foreach (var part in group.Targets.Concat(group.Source == null ? Array.Empty() : new[] { group.Source }) + .Where(p => p.ClientInstanceId == _currentEndPoint.ClientInstanceId)) + { + _authorization.Grant(new DataSource { Id = part.SourceId!, DataNodeId = part.NodeId!, + ClientInstanceId = part.ClientInstanceId, Path = part.RootPath, Type = part.InventoryPartType }); + } + return _synchronizationActionHandler.RunSynchronizationAction(group, cancellationToken); + } + [Test] public async Task Test_FailUnknownOperator() { @@ -71,8 +100,8 @@ public async Task Test_FailUnknownOperator() ActionsGroupId = "ACI_Test", }; - await FluentActions.Awaiting(() => _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup)) - .Should().ThrowAsync(); + await FluentActions.Awaiting(() => RunWithLocalPermissions(sharedActionsGroup)) + .Should().ThrowAsync(); } [Test] @@ -122,7 +151,7 @@ public async Task Test_SynchronizeContentOnly_Full_LocalTarget(bool isLocalSessi PathIdentity = new PathIdentity(FileSystemTypes.File, "/fileToCopy1.txt", "fileToCopy1.txt", "/fileToCopy1.txt") }; - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); fileA.Refresh(); fileB.Refresh(); @@ -210,7 +239,7 @@ public async Task Test_SynchronizeContentOnly_Delta_LocalTarget(bool isLocalSess PathIdentity = new PathIdentity(FileSystemTypes.File, "/fileToCopy1.txt", "fileToCopy1.txt", "/fileToCopy1.txt") }; - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); fileA.Refresh(); fileB.Refresh(); @@ -258,7 +287,7 @@ public async Task Test_SynchronizeDate_LocalTarget(bool isLocalSession) LastWriteTimeUtc = originalDateA }; - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); fileA.Refresh(); fileB.Refresh(); @@ -310,7 +339,7 @@ public async Task Test_SynchronizeContentAndDate_Full_LocalTarget(bool isLocalSe LastWriteTimeUtc = originalDateA }; - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); fileA.Refresh(); fileB.Refresh(); @@ -347,7 +376,7 @@ public async Task Test_Create_Directory_LocalTarget() PathIdentity = new PathIdentity(FileSystemTypes.Directory, "/NewDirectory", "NewDirectory", "/NewDirectory") }; - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); targetDirectory.Refresh(); targetDirectory.Exists.Should().BeTrue(); @@ -376,7 +405,7 @@ public async Task Test_Create_Directory_AlreadyExists_LocalTarget() }; // Should not throw exception even if directory already exists - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); existingDirectory.Refresh(); existingDirectory.Exists.Should().BeTrue(); @@ -404,7 +433,7 @@ public async Task Test_Delete_File_LocalTarget() PathIdentity = new PathIdentity(FileSystemTypes.File, "/fileToDelete.txt", "fileToDelete.txt", "/fileToDelete.txt") }; - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); fileToDelete.Refresh(); fileToDelete.Exists.Should().BeFalse(); @@ -432,7 +461,7 @@ public async Task Test_Delete_Directory_LocalTarget() PathIdentity = new PathIdentity(FileSystemTypes.Directory, "/DirectoryToDelete", "DirectoryToDelete", "/DirectoryToDelete") }; - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); directoryToDelete.Refresh(); directoryToDelete.Exists.Should().BeFalse(); @@ -461,7 +490,7 @@ public async Task Test_Delete_NonExistentFile_LocalTarget_ShouldNotThrow() }; // Should not throw exception for non-existent files - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); } [Test] @@ -479,15 +508,17 @@ public async Task Test_SynchronizeDate_FileNotExists_ShouldLogWarning() var sharedActionsGroup = new SharedActionsGroup { ActionsGroupId = "ACI_SyncDateNonExistent", + CreationTimeUtc = DateTime.UtcNow, + LastWriteTimeUtc = DateTime.UtcNow, Operator = ActionOperatorTypes.CopyDatesOnly, Targets = [target], - Source = null, + Source = target, SynchronizationType = SynchronizationTypes.Full, PathIdentity = new PathIdentity(FileSystemTypes.File, "/nonExistent.txt", "nonExistent.txt", "/nonExistent.txt") }; // Should not throw but should handle the missing file gracefully - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); } [Test] @@ -510,8 +541,8 @@ public async Task Test_Create_InvalidFileSystemType_ShouldThrowException() }; // Should throw exception because Create operation should only work for directories - await FluentActions.Awaiting(() => _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup)) - .Should().ThrowAsync(); + await FluentActions.Awaiting(() => RunWithLocalPermissions(sharedActionsGroup)) + .Should().ThrowAsync(); } [Test] @@ -541,7 +572,7 @@ public async Task Test_Delete_Directory_WithFiles_ShouldThrowIOException() }; // Should throw IOException when trying to delete non-empty directory with recursive=false - await FluentActions.Awaiting(() => _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup)) + await FluentActions.Awaiting(() => RunWithLocalPermissions(sharedActionsGroup)) .Should().ThrowAsync(); // Directory should still exist because the delete operation failed @@ -566,7 +597,7 @@ public async Task Test_RunSynchronizationAction_CancelledImmediately_ShouldThrow }; await FluentActions.Awaiting(() => - _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup, cancellationTokenSource.Token)) + RunWithLocalPermissions(sharedActionsGroup, cancellationTokenSource.Token)) .Should().ThrowAsync(); } @@ -597,7 +628,7 @@ public async Task Test_SynchronizeContentOnly_RemoteTarget_ShouldCallUploader() }; // This should call the remote uploader (mocked in integration tests) - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); // Verify that no local files were affected fileA.Refresh(); @@ -637,7 +668,7 @@ public async Task Test_SynchronizeContentOnly_MixedLocalAndRemoteTargets() PathIdentity = new PathIdentity(FileSystemTypes.File, "/fileToSync.txt", "fileToSync.txt", "/fileToSync.txt") }; - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup); + await RunWithLocalPermissions(sharedActionsGroup); // Verify local target was synchronized fileB.Refresh(); @@ -690,7 +721,7 @@ public async Task Test_RunSynchronizationAction_MultipleTargets_CancelledDuringP try { - await _synchronizationActionHandler.RunSynchronizationAction(sharedActionsGroup, cancellationTokenSource.Token); + await RunWithLocalPermissions(sharedActionsGroup, cancellationTokenSource.Token); } catch (OperationCanceledException) { diff --git a/tests/ByteSync.Client.IntegrationTests/TestHelpers/ComparisonResultPreparer.cs b/tests/ByteSync.Client.IntegrationTests/TestHelpers/ComparisonResultPreparer.cs index 034310f1f..ed270c0fb 100644 --- a/tests/ByteSync.Client.IntegrationTests/TestHelpers/ComparisonResultPreparer.cs +++ b/tests/ByteSync.Client.IntegrationTests/TestHelpers/ComparisonResultPreparer.cs @@ -1,4 +1,4 @@ -using ByteSync.Business; +using ByteSync.Business; using ByteSync.Business.DataNodes; using ByteSync.Business.Inventories; using ByteSync.Business.SessionMembers; @@ -99,7 +99,7 @@ private async Task DoBuildAndCompare() var processData = new InventoryProcessData(); var saver = new InventorySaver(); - var analyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, processData, saver, InventoryFileAnalyzerLoggerMock.Object); + var analyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, processData, saver, InventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryBuilder = new InventoryBuilder(sessionMemberInfo, dataNode, SessionSettings, processData, OSPlatforms.Windows, FingerprintModes.Rsync, inventoryBuilderloggerMock.Object, analyzer, diff --git a/tests/ByteSync.Client.IntegrationTests/TestHelpers/SharedDataPartTestFactory.cs b/tests/ByteSync.Client.IntegrationTests/TestHelpers/SharedDataPartTestFactory.cs index 0d8bf3b49..b926db975 100644 --- a/tests/ByteSync.Client.IntegrationTests/TestHelpers/SharedDataPartTestFactory.cs +++ b/tests/ByteSync.Client.IntegrationTests/TestHelpers/SharedDataPartTestFactory.cs @@ -7,6 +7,7 @@ namespace ByteSync.Client.IntegrationTests.TestHelpers; public static class SharedDataPartTestFactory { + private static string? Normalize(string? path) => path == null ? null : "/" + string.Join("/", path.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries)); public static SharedDataPart Create( string name, Inventory inventory, @@ -20,10 +21,11 @@ public static SharedDataPart Create( { var inventoryPart = new InventoryPart(inventory, rootPath, inventoryPartType) { + SourceId = inventory.InventoryParts.FirstOrDefault(p => p.RootPath == rootPath)?.SourceId ?? Guid.NewGuid().ToString(), Code = inventory.Code + "1" }; - var part = new SharedDataPart(name, inventory, inventoryPart, relativePath, signatureGuid, signatureHash, hasAnalysisError); + var part = new SharedDataPart(name, inventory, inventoryPart, Normalize(relativePath), signatureGuid, signatureHash, hasAnalysisError); part.ClientInstanceId = overrideClientInstanceId; return part; } @@ -40,10 +42,11 @@ public static SharedDataPart Create( { var inventoryPart = new InventoryPart(inventory, rootPath, inventoryPartType) { + SourceId = inventory.InventoryParts.FirstOrDefault(p => p.RootPath == rootPath)?.SourceId ?? Guid.NewGuid().ToString(), Code = inventory.Code + "1" }; - return new SharedDataPart(name, inventory, inventoryPart, relativePath, signatureGuid, signatureHash, hasAnalysisError); + return new SharedDataPart(name, inventory, inventoryPart, Normalize(relativePath), signatureGuid, signatureHash, hasAnalysisError); } public static SharedDataPart Create( @@ -73,10 +76,11 @@ public static SharedDataPart Create( var inventoryPart = new InventoryPart(inventory, rootPath, inventoryPartType) { + SourceId = Guid.NewGuid().ToString(), Code = inventoryCode + "1" }; - return new SharedDataPart(name, inventory, inventoryPart, relativePath, signatureGuid, signatureHash, hasAnalysisError); + return new SharedDataPart(name, inventory, inventoryPart, Normalize(relativePath), signatureGuid, signatureHash, hasAnalysisError); } } diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/PushReceivers/DataNodePushReceiverTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/PushReceivers/DataNodePushReceiverTests.cs index 0c6529351..8a99e917d 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Communications/PushReceivers/DataNodePushReceiverTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/PushReceivers/DataNodePushReceiverTests.cs @@ -45,7 +45,7 @@ public void DataNodeAdded_ShouldRefreshCodes() { var encrypted = new EncryptedDataNode(); var dto = new DataNodeDTO("SID", "CID", encrypted); - var node = new DataNode(); + var node = new DataNode { ClientInstanceId = "CID" }; _dataEncrypterMock.Setup(e => e.DecryptDataNode(encrypted)).Returns(node); _addedSubject.OnNext(dto); @@ -59,7 +59,7 @@ public void DataNodeRemoved_ShouldRefreshCodes() { var encrypted = new EncryptedDataNode(); var dto = new DataNodeDTO("SID", "CID", encrypted); - var node = new DataNode(); + var node = new DataNode { ClientInstanceId = "CID" }; _dataEncrypterMock.Setup(e => e.DecryptDataNode(encrypted)).Returns(node); _removedSubject.OnNext(dto); diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/PushReceivers/DataSourcePushReceiverTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/PushReceivers/DataSourcePushReceiverTests.cs index 4d4d5a004..6d3763b60 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Communications/PushReceivers/DataSourcePushReceiverTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/PushReceivers/DataSourcePushReceiverTests.cs @@ -38,7 +38,7 @@ public void SetUp() _hubPushHandlerMock.SetupGet(h => h.DataSourceRemoved).Returns(_removedSubject); _ = new DataSourcePushReceiver(_sessionServiceMock.Object, _dataEncrypterMock.Object, - _hubPushHandlerMock.Object, _dataSourceServiceMock.Object); + _hubPushHandlerMock.Object, _dataSourceServiceMock.Object, Moq.Mock.Of()); } [Test] diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/Transfers/Downloading/DownloadTargetBuilderTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/Transfers/Downloading/DownloadTargetBuilderTests.cs index e741daf36..817606daf 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Communications/Transfers/Downloading/DownloadTargetBuilderTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/Transfers/Downloading/DownloadTargetBuilderTests.cs @@ -49,7 +49,7 @@ public void Setup() _sharedActionsGroupRepository.Object, _connectionService.Object, _temporaryFileManagerFactory.Object, - _sessionService.Object); + _sessionService.Object, Moq.Mock.Of()); } [TearDown] diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizerTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizerTests.cs index 56cf47a1a..04f3aa47f 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizerTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/Transfers/Downloading/SynchronizationDownloadFinalizerTests.cs @@ -59,6 +59,7 @@ public async Task FinalizeSynchronization_MonoFile_Delta_AppliesDeltaForEachDest var downloadTarget = new DownloadTarget(shared, null, ["temp.delta"]) { + ValidateAccess = () => { }, FinalDestinationsPerActionsGroupId = new Dictionary> { ["ag1"] = [GetTempFilePath(), GetTempFilePath()] @@ -95,6 +96,7 @@ public async Task FinalizeSynchronization_MonoFile_NonDelta_SetsDatesForAllFinal var downloadTarget = new DownloadTarget(shared, null, []) { + ValidateAccess = () => { }, FinalDestinationsPerActionsGroupId = new Dictionary> { ["ag1"] = [GetTempFilePath(), GetTempFilePath(), GetTempFilePath()] @@ -139,6 +141,7 @@ public async Task FinalizeSynchronization_MultiFileZip_Delta_ExtractsStreamsAndA var downloadTarget = new DownloadTarget(shared, null, [zipPath]) { + ValidateAccess = () => { }, FinalDestinationsPerActionsGroupId = finalMap, IsMultiFileZip = true }; @@ -210,6 +213,7 @@ public async Task FinalizeSynchronization_MultiFileZip_NonDelta_ExtractsEachEntr var downloadTarget = new DownloadTarget(shared, null, [zipPath]) { + ValidateAccess = () => { }, FinalDestinationsPerActionsGroupId = finalMap, IsMultiFileZip = true }; @@ -261,6 +265,7 @@ public async Task FinalizeSynchronization_MultiFileZip_NonDelta_WhenExtractThrow var downloadTarget = new DownloadTarget(shared, null, [zipPath]) { + ValidateAccess = () => { }, FinalDestinationsPerActionsGroupId = finalMap, IsMultiFileZip = true }; diff --git a/tests/ByteSync.Client.UnitTests/Services/Comparisons/IdentityBuilderTests.cs b/tests/ByteSync.Client.UnitTests/Services/Comparisons/IdentityBuilderTests.cs index 8b09d0a26..46d7ec740 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Comparisons/IdentityBuilderTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Comparisons/IdentityBuilderTests.cs @@ -1,4 +1,4 @@ -using ByteSync.Business; +using ByteSync.Business; using ByteSync.Business.DataNodes; using ByteSync.Business.DataSources; using ByteSync.Business.Inventories; @@ -184,7 +184,7 @@ private static InventoryBuilder GetInventoryBuilder(FileSystemInfo dataSourceRoo var processData = new InventoryProcessData(); var saver = new InventorySaver(); - var analyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, processData, saver, inventoryFileAnalyzerLoggerMock.Object); + var analyzer = new InventoryFileAnalyzer(FingerprintModes.Rsync, processData, saver, inventoryFileAnalyzerLoggerMock.Object, Moq.Mock.Of()); var inventoryBuilder = new InventoryBuilder(sessionMemberInfo, dataNode, SessionSettingsHelper.BuildDefaultSessionSettings(DataTypes.FilesDirectories, MatchingModes.Tree), processData, OSPlatforms.Windows, FingerprintModes.Rsync, loggerMock.Object, diff --git a/tests/ByteSync.Client.UnitTests/Services/Inventories/DataNodeServiceTests.cs b/tests/ByteSync.Client.UnitTests/Services/Inventories/DataNodeServiceTests.cs index 1a3557c1b..7feb283ac 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Inventories/DataNodeServiceTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Inventories/DataNodeServiceTests.cs @@ -62,7 +62,7 @@ public void Setup() _codeGeneratorMock.Object, _dataSourceServiceMock.Object, _dataSourceRepositoryMock.Object, - _loggerMock.Object); + _loggerMock.Object, Moq.Mock.Of()); } [TearDown] diff --git a/tests/ByteSync.Client.UnitTests/Services/Inventories/DataSourceServiceTests.cs b/tests/ByteSync.Client.UnitTests/Services/Inventories/DataSourceServiceTests.cs index 378d2ca22..3e51d0494 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Inventories/DataSourceServiceTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Inventories/DataSourceServiceTests.cs @@ -50,7 +50,7 @@ public void Setup() _inventoryApiClientMock.Object, _dataSourceRepositoryMock.Object, _codeGeneratorMock.Object, - _loggerMock.Object); + _loggerMock.Object, Moq.Mock.Of()); } [Test] diff --git a/tests/ByteSync.Client.UnitTests/Services/Security/LocalSourceAuthorizationSecurityTests.cs b/tests/ByteSync.Client.UnitTests/Services/Security/LocalSourceAuthorizationSecurityTests.cs new file mode 100644 index 000000000..c5b21e647 --- /dev/null +++ b/tests/ByteSync.Client.UnitTests/Services/Security/LocalSourceAuthorizationSecurityTests.cs @@ -0,0 +1,486 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Xml.Serialization; +using ByteSync.Business.Actions.Shared; +using ByteSync.Business.Configurations; +using ByteSync.Business.DataSources; +using ByteSync.Business.Inventories; +using ByteSync.Common.Business.Actions; +using ByteSync.Common.Business.Inventories; +using ByteSync.Interfaces; +using ByteSync.Interfaces.Services.Communications; +using ByteSync.Interfaces.Services.Sessions; +using ByteSync.Services.Inventories; +using ByteSync.Services.Synchronizations; +using FluentAssertions; +using Moq; +using NUnit.Framework; + +namespace ByteSync.Client.UnitTests.Services.Security; + +public class LocalSourceAuthorizationSecurityTests +{ + private string _directory = null!; + private ApplicationSettings _settings = null!; + private LocalSourceAuthorizationService _service = null!; + private DataSource _source = null!; + private const string Instance = "local-instance"; + + [SetUp] + public void SetUp() + { + _directory = Path.Combine(Path.GetTempPath(), "ByteSyncSecurityTests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_directory); + _settings = new ApplicationSettings(); + _settings.SetEncryptionPassword("local-test-only-password"); + _settings.InstallationId = "test"; + _settings.InitializeRsa(); + var settings = new Mock(); + settings.Setup(s => s.GetCurrentApplicationSettings()).Returns(_settings); + settings.Setup(s => s.UpdateCurrentApplicationSettings(It.IsAny>(), It.IsAny())) + .Returns((Action update, bool save) => { update(_settings); return _settings; }); + var connection = new Mock(); + connection.SetupGet(c => c.ClientInstanceId).Returns(Instance); + var session = new Mock(); + session.SetupGet(s => s.SessionId).Returns("session"); + var nodes = new Mock(); + nodes.Setup(n => n.GetElement("node")).Returns(new ByteSync.Business.DataNodes.DataNode { Id = "node", ClientInstanceId = Instance }); + _service = new LocalSourceAuthorizationService(settings.Object, connection.Object, session.Object, nodes.Object); + _source = new DataSource { Id = "source", DataNodeId = "node", ClientInstanceId = Instance, Path = _directory, Type = FileSystemTypes.Directory }; + _service.Grant(_source); + } + + [TearDown] + public void TearDown() + { + _settings.PrivateRsa.Dispose(); + if (Directory.Exists(_directory)) Directory.Delete(_directory, true); + } + + private SharedDataPart Part(string relative = "file.txt") => new() + { + SourceId = _source.Id, NodeId = _source.DataNodeId, ClientInstanceId = Instance, + InventoryPartType = _source.Type, RootPath = "untrusted-root-from-peer", SourceRelativePath = relative, + RelativePath = "/" + relative + }; + + private static SharedActionsGroup Group(SharedDataPart part) => new() + { + ActionsGroupId = Guid.NewGuid().ToString(), Operator = ActionOperatorTypes.Delete, + PathIdentity = new PathIdentity(FileSystemTypes.File, "file", "file", "file"), Targets = new HashSet { part } + }; + + [TestCase("../outside")] + [TestCase("a/../../outside")] + [TestCase("/etc/passwd")] + [TestCase("C:/Windows/file")] + [TestCase("C:relative")] + [TestCase(@"\\server\share\file")] + [TestCase(@"a\..\outside")] + [TestCase("a//file")] + [TestCase("./file")] + [TestCase("a/./file")] + public void PeerRelativePaths_CannotEscapeOrUseAmbiguousForms(string relative) + { + var act = () => _service.Resolve(Part(relative)); + + act.Should().Throw(); + } + + [Test] + public void PeerRoot_IsIgnoredAndOnlyLocalGrantResolvesPaths() + { + var part = Part("sub/file.txt"); + var expected = Path.Combine(_directory, "sub", "file.txt"); + + _service.Resolve(part).Should().Be(expected); + _service.ValidatePlan(new[] { Group(part) }); + part.LocalPathResolver!().Should().Be(expected); + } + + [TestCase("owner")] + [TestCase("node")] + [TestCase("source")] + [TestCase("type")] + public void PeerBinding_MustMatchTheLocalGrant(string field) + { + var part = Part(); + switch (field) + { + case "owner": part.ClientInstanceId = "remote"; break; + case "node": part.NodeId = "other-node"; break; + case "source": part.SourceId = "other-source"; break; + case "type": part.InventoryPartType = FileSystemTypes.File; break; + } + + var act = () => _service.Resolve(part); + + act.Should().Throw(); + } + + [Test] + public void FileGrant_AuthorizesOnlyTheSelectedFile() + { + _service.Revoke(_source); + _source.Path = Path.Combine(_directory, "only.txt"); + _source.Type = FileSystemTypes.File; + File.WriteAllText(_source.Path, "authorized"); + _service.Grant(_source); + + _service.Resolve(Part("")).Should().Be(_source.Path); + var sibling = () => _service.Resolve(Part("sibling.txt")); + var siblingAccess = () => _service.ValidatePath(Path.Combine(_directory, "sibling.txt")); + + sibling.Should().Throw(); + siblingAccess.Should().Throw(); + } + + [Test] + public void NetworkSources_CannotClaimLocalOwnershipOrChangeTheRoot() + { + var remote = new DataSource { Id = "remote", ClientInstanceId = Instance, DataNodeId = "node", Path = _directory, Type = FileSystemTypes.Directory }; + var spoof = () => _service.CheckNetworkSource(remote, "remote-instance"); + spoof.Should().Throw(); + var echo = new DataSource { Id = _source.Id, ClientInstanceId = Instance, DataNodeId = "node", Path = _directory + "-sibling", Type = FileSystemTypes.Directory }; + var changeRoot = () => _service.CheckNetworkSource(echo, Instance); + changeRoot.Should().Throw(); + _service.CheckNetworkSource(_source, Instance); + } + + [Test] + public void RevokedGrant_InvalidatesPreviouslyPreparedActions() + { + var part = Part(); + var group = Group(part); + _service.ValidatePlan(new[] { group }); + _service.Revoke(_source); + + var act = () => group.GetFullName(part); + + act.Should().Throw(); + } + + [Test] + public void Plan_WithValidThenInvalidAction_BindsNothingAndMutatesNothing() + { + var sentinel = Path.Combine(_directory, "file.txt"); + File.WriteAllText(sentinel, "unchanged"); + var valid = Part(); + var groups = new[] { Group(valid), Group(Part("../outside")) }; + + var act = () => _service.ValidatePlan(groups); + + act.Should().Throw(); + valid.LocalPathResolver.Should().BeNull(); + File.ReadAllText(sentinel).Should().Be("unchanged"); + } + + [Test] + public void ProfileRestore_RequiresAnExistingIndependentLocalPermission() + { + var another = new DataSource { Id = "restored", ClientInstanceId = Instance, DataNodeId = "node", Path = _directory, Type = FileSystemTypes.Directory }; + _service.Grant(another, true); + another.Path = _directory + "-untrusted"; + + var restore = () => _service.Grant(another, true); + + restore.Should().Throw(); + _settings.LocalSourcePermissions.Should().HaveCount(1); + } + + [Test] + public void LocalPermissions_SurviveXmlWithoutChangingTheRsaKeys() + { + var serializer = new XmlSerializer(typeof(ApplicationSettings)); + using var writer = new StringWriter(); + serializer.Serialize(writer, _settings); + using var reader = new StringReader(writer.ToString()); + var restored = (ApplicationSettings)serializer.Deserialize(reader)!; + restored.SetEncryptionPassword("local-test-only-password"); + + restored.LocalSourcePermissions.Should().BeEquivalentTo(_settings.LocalSourcePermissions); + restored.DecodedRsaPublicKey.Should().Equal(_settings.DecodedRsaPublicKey!); + restored.PrivateRsa.Dispose(); + } + + [Test] + public void LinkInsertedAfterPreparation_IsRejectedBeforeAccess() + { + var sub = Path.Combine(_directory, "sub"); + var outside = Path.Combine(_directory, "outside"); + Directory.CreateDirectory(sub); + Directory.CreateDirectory(outside); + var part = Part("sub/file.txt"); + _service.ValidatePlan(new[] { Group(part) }); + Directory.Delete(sub); + try { Directory.CreateSymbolicLink(sub, outside); } + catch (UnauthorizedAccessException) { Assert.Ignore("Creating symbolic links requires Windows Developer Mode or a symlink privilege"); } + try + { + var act = () => part.LocalPathResolver!(); + act.Should().Throw(); + } + finally { Directory.Delete(sub); } + } + + [Test] + public void NativeFileOperations_PreserveLegitimateCopyReplaceAndMetadata() + { + var source = Path.Combine(_directory, "source.txt"); + var target = Path.Combine(_directory, "nested", "target.txt"); + File.WriteAllText(source, "contents"); + LocalPathSafety.CreateDirectory(Path.GetDirectoryName(target)!); + using (var input = LocalPathSafety.OpenRead(source)) + using (var output = LocalPathSafety.OpenWrite(target, true)) input.CopyTo(output); + var date = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + LocalPathSafety.SetDates(target, date, date); + + File.ReadAllText(target).Should().Be("contents"); + File.GetLastWriteTimeUtc(target).Should().Be(date); + LocalPathSafety.Delete(target); + File.Exists(target).Should().BeFalse(); + } + + [Test] + public void WindowsDirectoryLease_PreventsParentSubstitutionDuringAccess() + { + if (!OperatingSystem.IsWindows()) Assert.Ignore("Windows sharing semantics test"); + var sub = Path.Combine(_directory, "sub"); + Directory.CreateDirectory(sub); + using var lease = LocalPathSafety.Acquire(Path.Combine(sub, "file.txt")); + + var swap = () => Directory.Move(sub, sub + "-moved"); + + swap.Should().Throw(); + } + [TestCase(ActionOperatorTypes.CopyContentOnly)] + [TestCase(ActionOperatorTypes.Copy)] + [TestCase(ActionOperatorTypes.CopyDatesOnly)] + [TestCase(ActionOperatorTypes.Create)] + [TestCase(ActionOperatorTypes.Delete)] + public async System.Threading.Tasks.Task EveryFileOperation_RejectsAnUnauthorizedTargetBeforeMutation(ActionOperatorTypes operation) + { + var part = Part("../outside.txt"); + var group = Group(part); + group.Operator = operation; + group.Source = Part("source.txt"); + group.SynchronizationType = SynchronizationTypes.Full; + group.CreationTimeUtc = group.LastWriteTimeUtc = DateTime.UtcNow; + if (operation == ActionOperatorTypes.Create) group.PathIdentity = new PathIdentity(FileSystemTypes.Directory, "dir", "dir", "dir"); + var handler = Handler(); + + var act = () => handler.RunSynchronizationAction(group); + + await act.Should().ThrowAsync(); + Directory.GetFiles(_directory).Should().BeEmpty(); + } + + private SynchronizationActionHandler Handler() + { + var connection = new Mock(); + connection.SetupGet(c => c.CurrentEndPoint).Returns(new ByteSync.Common.Business.EndPoints.ByteSyncEndpoint { ClientInstanceId = Instance }); + return new SynchronizationActionHandler(Mock.Of(), connection.Object, + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + Mock.Of(), + new FileDatesSetter(Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, _service), + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, _service); + } + + [TestCase(false)] + [TestCase(true)] + public async System.Threading.Tasks.Task LegitimateFullCopy_UsesLocalRootsDespitePeerRootValues(bool automatedProfileRestore) + { + var source = Path.Combine(_directory, "source.txt"); + var target = Path.Combine(_directory, "target.txt"); + File.WriteAllText(source, "legitimate synchronization"); + var group = Group(Part("target.txt")); + group.Operator = ActionOperatorTypes.CopyContentOnly; + group.Source = Part("source.txt"); + group.SynchronizationType = SynchronizationTypes.Full; + + if (automatedProfileRestore) + { + var restoredSource = new DataSource { Id = "restored-source", DataNodeId = _source.DataNodeId, + ClientInstanceId = Instance, Path = _directory, Type = _source.Type }; + _service.Grant(restoredSource, true); + group.Source.SourceId = restoredSource.Id; + foreach (var part in group.Targets) part.SourceId = restoredSource.Id; + } + + await Handler().RunSynchronizationAction(group); + + File.ReadAllText(target).Should().Be("legitimate synchronization"); + Directory.GetFiles(_directory, "*.bstemp").Should().BeEmpty(); + } + + [Test] + public async System.Threading.Tasks.Task LegitimateDifferentialApply_UsesAuthorizedBasisAndReplacement() + { + var target = Path.Combine(_directory, "basis.txt"); + var newer = Path.Combine(_directory, "new.txt"); + File.WriteAllText(target, new string('a', 16384)); + File.WriteAllText(newer, new string('a', 8192) + new string('b', 8192)); + using var signature = new MemoryStream(); + using (var basis = File.OpenRead(target)) new FastRsync.Signature.SignatureBuilder().Build(basis, new FastRsync.Signature.SignatureWriter(signature)); + signature.Position = 0; + using var delta = new MemoryStream(); + using (var input = File.OpenRead(newer)) + { + var builder = new FastRsync.Delta.DeltaBuilder(); + await builder.BuildDeltaAsync(input, new FastRsync.Signature.SignatureReader(signature, builder.ProgressReport), + new FastRsync.Core.AggregateCopyOperationsDecorator(new FastRsync.Delta.BinaryDeltaWriter(delta))); + } + delta.Position = 0; + var factory = new Mock(); + factory.Setup(f => f.Create(target)).Returns(() => new TemporaryFileManager(target, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance)); + var manager = new DeltaManager(Mock.Of(), factory.Object, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, _service); + + await manager.ApplyDelta(target, delta); + + File.ReadAllBytes(target).Should().Equal(File.ReadAllBytes(newer)); + } + + [Test] + public void HardLinkedFiles_CannotBeReadOrTruncated() + { + if (!OperatingSystem.IsWindows()) Assert.Ignore("Windows hard-link API test"); + var original = Path.Combine(_directory, "original.txt"); + var linked = Path.Combine(_directory, "linked.txt"); + File.WriteAllText(original, "unchanged"); + CreateHardLink(linked, original, IntPtr.Zero).Should().BeTrue(); + + var read = () => LocalPathSafety.OpenRead(linked).Dispose(); + var write = () => LocalPathSafety.OpenWrite(linked).Dispose(); + + read.Should().Throw(); + write.Should().Throw(); + File.ReadAllText(original).Should().Be("unchanged"); + } + + [System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, EntryPoint = "CreateHardLinkW")] + [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] + private static extern bool CreateHardLink(string name, string existing, IntPtr security); + + [TestCase("CON")] + [TestCase("NUL.txt")] + [TestCase("name.")] + [TestCase("name ")] + [TestCase("file:stream")] + public void WindowsAmbiguousPaths_AreRejected(string path) + { + if (!OperatingSystem.IsWindows()) Assert.Ignore("Windows path syntax"); + var act = () => _service.Resolve(Part(path)); + act.Should().Throw(); + } + + [Test] + public void DirectoryAuthorization_DoesNotAuthorizeAnAdjacentDirectory() + { + var outside = () => _service.ValidatePath(Path.Combine(_directory + "-adjacent", "file.txt")); + outside.Should().Throw(); + } + + [Test] + public void Junction_CannotRedirectAnyNativeFileOperation() + { + if (!OperatingSystem.IsWindows()) Assert.Ignore("Windows junction semantics"); + var target = Path.Combine(_directory, "real"); + var junction = Path.Combine(_directory, "junction"); + Directory.CreateDirectory(target); + var sentinel = Path.Combine(target, "file.txt"); + File.WriteAllText(sentinel, "unchanged"); + Directory.CreateDirectory(junction); + using (var handle = OpenJunction(junction, 0x40000000, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero)) + { + var substitute = System.Text.Encoding.Unicode.GetBytes(@"\??\" + target); + var print = System.Text.Encoding.Unicode.GetBytes(target); + var buffer = new byte[16 + substitute.Length + 2 + print.Length + 2]; + BitConverter.GetBytes(0xA0000003u).CopyTo(buffer, 0); + BitConverter.GetBytes((ushort)(buffer.Length - 8)).CopyTo(buffer, 4); + BitConverter.GetBytes((ushort)substitute.Length).CopyTo(buffer, 10); + BitConverter.GetBytes((ushort)(substitute.Length + 2)).CopyTo(buffer, 12); + BitConverter.GetBytes((ushort)print.Length).CopyTo(buffer, 14); + substitute.CopyTo(buffer, 16); + print.CopyTo(buffer, 18 + substitute.Length); + SetReparsePoint(handle, 0x900A4, buffer, buffer.Length, IntPtr.Zero, 0, out _, IntPtr.Zero).Should().BeTrue(); + } + try + { + var linkedFile = Path.Combine(junction, "file.txt"); + var read = () => LocalPathSafety.OpenRead(linkedFile).Dispose(); + var write = () => LocalPathSafety.OpenWrite(linkedFile).Dispose(); + var dates = () => LocalPathSafety.SetDates(linkedFile, DateTime.UtcNow, DateTime.UtcNow); + var delete = () => LocalPathSafety.Delete(linkedFile); + var create = () => LocalPathSafety.CreateDirectory(Path.Combine(junction, "new-directory")); + read.Should().Throw(); + write.Should().Throw(); + dates.Should().Throw(); + delete.Should().Throw(); + create.Should().Throw(); + File.ReadAllText(sentinel).Should().Be("unchanged"); + Directory.Exists(Path.Combine(target, "new-directory")).Should().BeFalse(); + } + finally { Directory.Delete(junction); } + } + + [System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, EntryPoint = "CreateFileW")] + private static extern Microsoft.Win32.SafeHandles.SafeFileHandle OpenJunction(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template); + [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true, EntryPoint = "DeviceIoControl")] + [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)] + private static extern bool SetReparsePoint(Microsoft.Win32.SafeHandles.SafeFileHandle handle, uint code, byte[] input, int inputSize, IntPtr output, int outputSize, out int returned, IntPtr overlapped); + + [Test] + public async System.Threading.Tasks.Task LegitimateDirectoryDatesAndDeleteActions_StayWithinTheGrant() + { + var directory = Part("new-directory"); + var create = Group(directory); + create.Operator = ActionOperatorTypes.Create; + create.PathIdentity = new PathIdentity(FileSystemTypes.Directory, "dir", "dir", "dir"); + await Handler().RunSynchronizationAction(create); + Directory.Exists(Path.Combine(_directory, "new-directory")).Should().BeTrue(); + var file = Path.Combine(_directory, "file.txt"); + File.WriteAllText(file, "content"); + var dates = Group(Part()); + dates.Operator = ActionOperatorTypes.CopyDatesOnly; + dates.CreationTimeUtc = dates.LastWriteTimeUtc = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + await Handler().RunSynchronizationAction(dates); + File.GetLastWriteTimeUtc(file).Should().Be(dates.LastWriteTimeUtc.Value); + await Handler().RunSynchronizationAction(Group(Part())); + File.Exists(file).Should().BeFalse(); + create.Operator = ActionOperatorTypes.Delete; + await Handler().RunSynchronizationAction(create); + Directory.Exists(Path.Combine(_directory, "new-directory")).Should().BeFalse(); + } + + [TestCase("path")] + [TestCase("owner")] + [TestCase("source-id")] + public void HostileInventory_IsRejectedBeforeAnHonestCreatorCanPropagateIt(string mismatch) + { + var inventory = new ByteSync.Models.Inventories.Inventory + { + InventoryId = "IID", Code = "A", NodeId = "node", Endpoint = new ByteSync.Common.Business.EndPoints.ByteSyncEndpoint + { ClientInstanceId = mismatch == "owner" ? Instance : "remote", OSPlatform = ByteSync.Common.Business.Misc.OSPlatforms.Windows } + }; + var part = new ByteSync.Models.Inventories.InventoryPart(inventory, _directory, FileSystemTypes.Directory) + { SourceId = mismatch == "source-id" ? null : "remote-source", Code = "a" }; + inventory.Add(part); + part.FileDescriptions.Add(new ByteSync.Models.FileSystems.FileDescription { InventoryPart = part, RelativePath = mismatch == "path" ? "/../../outside" : "/file.txt" }); + var zip = Path.Combine(_directory, "inventory.zip"); + var saver = new InventorySaver(); + saver.Start(zip); + saver.WriteInventory(inventory); + saver.Stop(); + + var act = () => { using var loader = new InventoryLoader(zip, "remote"); }; + + act.Should().Throw(); + } + +} diff --git a/tests/ByteSync.Client.UnitTests/Services/Sessions/SynchronizationServiceTests.cs b/tests/ByteSync.Client.UnitTests/Services/Sessions/SynchronizationServiceTests.cs index b8706c214..dd65f33a2 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Sessions/SynchronizationServiceTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Sessions/SynchronizationServiceTests.cs @@ -1,4 +1,4 @@ -using System.Reactive.Subjects; +using System.Reactive.Subjects; using ByteSync.Business.Actions.Shared; using ByteSync.Business.Misc; using ByteSync.Business.Sessions; @@ -55,7 +55,7 @@ public async Task OnSynchronizationStarted_SetsStatus_StartsTimer_PublishesStart var svc = new SynchronizationService(_sessionServiceMock.Object, _sessionMemberServiceMock.Object, _synchronizationApiClientMock.Object, _synchronizationLooperFactoryMock.Object, - _timeTrackingCacheMock.Object, _loggerMock.Object); + _timeTrackingCacheMock.Object, _loggerMock.Object, Moq.Mock.Of()); var startedAt = DateTimeOffset.UtcNow.AddMinutes(-1); var sync = new Synchronization { SessionId = "sid-1", Started = startedAt }; @@ -85,7 +85,7 @@ public async Task OnSynchronizationUpdated_WhenEnded_StopsTimer_PublishesEnd_Upd var svc = new SynchronizationService(_sessionServiceMock.Object, _sessionMemberServiceMock.Object, _synchronizationApiClientMock.Object, _synchronizationLooperFactoryMock.Object, - _timeTrackingCacheMock.Object, _loggerMock.Object); + _timeTrackingCacheMock.Object, _loggerMock.Object, Moq.Mock.Of()); var endedAt = DateTimeOffset.UtcNow; var sync = new Synchronization { SessionId = "sid-end", Ended = endedAt, EndStatus = SynchronizationEndStatuses.Regular }; @@ -113,7 +113,7 @@ public async Task OnSynchronizationUpdated_WhenAbortRequested_PublishesAbortRequ var svc = new SynchronizationService(_sessionServiceMock.Object, _sessionMemberServiceMock.Object, _synchronizationApiClientMock.Object, _synchronizationLooperFactoryMock.Object, - _timeTrackingCacheMock.Object, _loggerMock.Object); + _timeTrackingCacheMock.Object, _loggerMock.Object, Moq.Mock.Of()); var when = DateTimeOffset.UtcNow; var by = new List { "c1", "c2" }; @@ -138,7 +138,7 @@ public async Task OnSynchronizationDataTransmitted_SetsTotals_AndSignalsTransmit var svc = new SynchronizationService(_sessionServiceMock.Object, _sessionMemberServiceMock.Object, _synchronizationApiClientMock.Object, _synchronizationLooperFactoryMock.Object, - _timeTrackingCacheMock.Object, _loggerMock.Object); + _timeTrackingCacheMock.Object, _loggerMock.Object, Moq.Mock.Of()); var data = new SharedSynchronizationStartData { TotalVolumeToProcess = 123, TotalAtomicActionsToProcess = 45 }; @@ -159,7 +159,7 @@ public async Task OnSynchronizationProgressChanged_UpdatesWhenNewerVersion_AndIg var svc = new SynchronizationService(_sessionServiceMock.Object, _sessionMemberServiceMock.Object, _synchronizationApiClientMock.Object, _synchronizationLooperFactoryMock.Object, - _timeTrackingCacheMock.Object, _loggerMock.Object); + _timeTrackingCacheMock.Object, _loggerMock.Object, Moq.Mock.Of()); svc.SynchronizationProcessData.TotalVolumeToProcess = 999; @@ -212,7 +212,7 @@ public async Task AbortSynchronization_CloudSession_AbortsSynchronization() var synchronizationService = new SynchronizationService(_sessionServiceMock.Object, _sessionMemberServiceMock.Object, _synchronizationApiClientMock.Object, - _synchronizationLooperFactoryMock.Object, _timeTrackingCacheMock.Object, _loggerMock.Object); + _synchronizationLooperFactoryMock.Object, _timeTrackingCacheMock.Object, _loggerMock.Object, Moq.Mock.Of()); // Act await synchronizationService.AbortSynchronization(); @@ -251,7 +251,7 @@ public void SynchronizationStart_WhenDataTransmitted_ShouldStartSynchronizationL _synchronizationLooperFactoryMock.Object, _timeTrackingCacheMock.Object, _loggerMock.Object - ); + , Moq.Mock.Of()); var synchronization = new Synchronization { SessionId = "test-session" }; @@ -306,7 +306,7 @@ public void SynchronizationStart_WhenDataTransmitted_ShouldRunInSeparateTask() _synchronizationLooperFactoryMock.Object, _timeTrackingCacheMock.Object, _loggerMock.Object - ); + , Moq.Mock.Of()); var synchronization = new Synchronization { SessionId = "test-session" }; var currentThreadId = Environment.CurrentManagedThreadId; diff --git a/tests/ByteSync.Common.Tests/Business/Versions/ProtocolVersionTests.cs b/tests/ByteSync.Common.Tests/Business/Versions/ProtocolVersionTests.cs index fdd5425ab..063b062db 100644 --- a/tests/ByteSync.Common.Tests/Business/Versions/ProtocolVersionTests.cs +++ b/tests/ByteSync.Common.Tests/Business/Versions/ProtocolVersionTests.cs @@ -8,15 +8,15 @@ namespace TestingCommon.Business.Versions; public class ProtocolVersionTests { [Test] - public void Current_ShouldBeV2() + public void Current_ShouldBeV3() { - ProtocolVersion.CURRENT.Should().Be(ProtocolVersion.V2); + ProtocolVersion.CURRENT.Should().Be(ProtocolVersion.V3); } [Test] - public void MinSupported_ShouldBeV2() + public void MinSupported_ShouldBeV3() { - ProtocolVersion.MIN_SUPPORTED.Should().Be(ProtocolVersion.V2); + ProtocolVersion.MIN_SUPPORTED.Should().Be(ProtocolVersion.V3); } [Test] @@ -46,7 +46,7 @@ public void IsCompatible_WithZero_ShouldReturnFalse() [Test] public void IsCompatible_WithDifferentVersion_ShouldReturnFalse() { - var result = ProtocolVersion.IsCompatible(3); + var result = ProtocolVersion.IsCompatible(ProtocolVersion.CURRENT + 1); result.Should().BeFalse(); } diff --git a/tests/ByteSync.Functions.UnitTests/Http/CloudSessionFunctionTests.cs b/tests/ByteSync.Functions.UnitTests/Http/CloudSessionFunctionTests.cs index 2cd2f6a97..07db2c267 100644 --- a/tests/ByteSync.Functions.UnitTests/Http/CloudSessionFunctionTests.cs +++ b/tests/ByteSync.Functions.UnitTests/Http/CloudSessionFunctionTests.cs @@ -118,7 +118,7 @@ public async Task ValidateJoinCloudSession_ReturnsOk_AndSendsRequest() .ReturnsAsync(Unit.Value); var function = new CloudSessionFunction(mediatorMock.Object); - var context = new Mock().Object; + var context = HttpFunctionTestHelper.BuildFunctionContextWithClient(); var request = new FakeHttpRequestData(context); var parameters = new ValidateJoinCloudSessionParameters diff --git a/tests/ByteSync.Functions.UnitTests/Http/CloudSessionProfileFunctionTests.cs b/tests/ByteSync.Functions.UnitTests/Http/CloudSessionProfileFunctionTests.cs index 39dfc807b..6b40d0010 100644 --- a/tests/ByteSync.Functions.UnitTests/Http/CloudSessionProfileFunctionTests.cs +++ b/tests/ByteSync.Functions.UnitTests/Http/CloudSessionProfileFunctionTests.cs @@ -59,7 +59,7 @@ public async Task GetCloudSessionProfileData_ForwardsRequest_AndReturnsOk() var parameters = new GetCloudSessionProfileDataParameters { SessionId = "P1", CloudSessionProfileId = "PC1" }; await HttpFunctionTestHelper.WriteBodyAsync(request, parameters); - var response = await function.GetCloudSessionProfileData(request, context, "P1"); + var response = await function.GetCloudSessionProfileData(request, context, "PC1"); response.StatusCode.Should().Be(HttpStatusCode.OK); captured.Should().NotBeNull(); @@ -81,7 +81,7 @@ public async Task GetProfileDetailsPassword_ForwardsRequest_AndReturnsOk() var context = HttpFunctionTestHelper.BuildFunctionContextWithClient(); var request = new FakeHttpRequestData(context); - var parameters = new GetProfileDetailsPasswordParameters { ProfileClientId = "PC1" }; + var parameters = new GetProfileDetailsPasswordParameters { CloudSessionProfileId = "P1", ProfileClientId = "PC1" }; await HttpFunctionTestHelper.WriteBodyAsync(request, parameters); var response = await function.GetProfileDetailsPassword(request, context, "P1"); @@ -106,7 +106,7 @@ public async Task DeleteCloudSessionProfile_ForwardsRequest_AndReturnsOk() var context = HttpFunctionTestHelper.BuildFunctionContextWithClient(); var request = new FakeHttpRequestData(context); - var parameters = new DeleteCloudSessionProfileParameters { ProfileClientId = "PC1" }; + var parameters = new DeleteCloudSessionProfileParameters { CloudSessionProfileId = "P1", ProfileClientId = "PC1" }; await HttpFunctionTestHelper.WriteBodyAsync(request, parameters); var response = await function.DeleteCloudSessionProfile(request, context, "P1"); diff --git a/tests/ByteSync.Functions.UnitTests/Http/InventoryFunctionTests.cs b/tests/ByteSync.Functions.UnitTests/Http/InventoryFunctionTests.cs index 397ca0856..377e5566e 100644 --- a/tests/ByteSync.Functions.UnitTests/Http/InventoryFunctionTests.cs +++ b/tests/ByteSync.Functions.UnitTests/Http/InventoryFunctionTests.cs @@ -104,7 +104,7 @@ public async Task GetDataSources_ForwardsRequest_AndReturnsOk() .ReturnsAsync([new EncryptedDataSource { Id = "DS1" }]); var function = new InventoryFunction(mediatorMock.Object); - var context = new Mock().Object; + var context = HttpFunctionTestHelper.BuildFunctionContextWithClient(); var request = new FakeHttpRequestData(context); var response = await function.GetDataSources(request, context, "S1", "CI1", "DN1"); @@ -176,7 +176,7 @@ public async Task GetDataNodes_ForwardsRequest_AndReturnsOk() .ReturnsAsync([new EncryptedDataNode { Id = "DN1" }]); var function = new InventoryFunction(mediatorMock.Object); - var context = new Mock().Object; + var context = HttpFunctionTestHelper.BuildFunctionContextWithClient(); var request = new FakeHttpRequestData(context); var response = await function.GetDataNodes(request, context, "S1", "CI1"); diff --git a/tests/ByteSync.ServerCommon.Tests/Business/SessionMemberDataTests.cs b/tests/ByteSync.ServerCommon.Tests/Business/SessionMemberDataTests.cs index 5a435519d..397eed57b 100644 --- a/tests/ByteSync.ServerCommon.Tests/Business/SessionMemberDataTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Business/SessionMemberDataTests.cs @@ -203,7 +203,7 @@ public void IsAuthCheckedFor_WhenInstanceIdInAuthCheckList_ShouldReturnTrue() } [Test] - public void IsAuthCheckedFor_WhenInstanceIdStartsWithClientId_ShouldReturnTrue() + public void IsAuthCheckedFor_WhenInstanceIdStartsWithClientId_ShouldReturnFalse() { // Arrange _sessionMemberData.ClientId = "client-prefix"; @@ -212,7 +212,7 @@ public void IsAuthCheckedFor_WhenInstanceIdStartsWithClientId_ShouldReturnTrue() bool result = _sessionMemberData.IsAuthCheckedFor("client-prefix-suffix"); // Assert - result.Should().BeTrue(); + result.Should().BeFalse(); } [Test] diff --git a/tests/ByteSync.ServerCommon.Tests/Commands/Authentication/AuthenticateCommandHandlerTests.cs b/tests/ByteSync.ServerCommon.Tests/Commands/Authentication/AuthenticateCommandHandlerTests.cs index 073097e8b..85bc1766c 100644 --- a/tests/ByteSync.ServerCommon.Tests/Commands/Authentication/AuthenticateCommandHandlerTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Commands/Authentication/AuthenticateCommandHandlerTests.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Auth; using ByteSync.Common.Business.EndPoints; using ByteSync.Common.Business.Misc; using ByteSync.Common.Business.Serials; @@ -31,7 +31,7 @@ public void Setup() _mockEndpointFactory, _mockClientsRepository, _mockClientSoftwareVersionService - ); + , FakeItEasy.A.Fake()); } [Test] @@ -75,6 +75,13 @@ public async Task Handle_ValidRequest_ReturnsSuccessResponse() var expectedBindSerialResponse = new BindSerialResponse { Status = BindSerialResponseStatus.Ignored }; var expectedEndpoint = new ByteSync.Common.Business.EndPoints.ByteSyncEndpoint(); + loginData.Identity = "identity"; + client.Identity = "identity"; + client.AuthenticationEpoch = AuthenticationProtocol.Epoch; + var challenges = A.Fake(); + A.CallTo(() => challenges.VerifyAndConsume(loginData)).Returns(true); + _authenticateCommandHandler = new AuthenticateCommandHandler(_mockTokensFactory, _mockEndpointFactory, _mockClientsRepository, _mockClientSoftwareVersionService, challenges); + // Mock version check A.CallTo(() => _mockClientSoftwareVersionService.IsClientVersionAllowed(loginData)).Returns(true); // Mock tokens factory diff --git a/tests/ByteSync.ServerCommon.Tests/Commands/Authentication/RefreshTokensCommandHandlerTests.cs b/tests/ByteSync.ServerCommon.Tests/Commands/Authentication/RefreshTokensCommandHandlerTests.cs index aa7a91d22..9af322e4d 100644 --- a/tests/ByteSync.ServerCommon.Tests/Commands/Authentication/RefreshTokensCommandHandlerTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Commands/Authentication/RefreshTokensCommandHandlerTests.cs @@ -1,4 +1,4 @@ -using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Auth; using ByteSync.Common.Business.Misc; using ByteSync.ServerCommon.Commands.Authentication; using ByteSync.ServerCommon.Interfaces.Factories; @@ -29,7 +29,7 @@ public async Task Handle_ValidRequest_ReturnsSuccessfulRefreshTokensResponse() var refreshTokensData = new RefreshTokensData { Token = "refresh-token", - ClientInstanceId = "client-123", + ClientInstanceId = new string('A', 64) + "_" + Guid.NewGuid().ToString("D"), Version = "2.0.0", OsPlatform = ByteSync.Common.Business.Misc.OSPlatforms.Windows }; @@ -40,6 +40,7 @@ public async Task Handle_ValidRequest_ReturnsSuccessfulRefreshTokensResponse() var expectedRefreshToken = new ByteSync.ServerCommon.Business.Auth.RefreshToken { + AuthenticationEpoch = AuthenticationProtocol.Epoch, Token = "refresh-token", Expires = DateTimeOffset.UtcNow.AddDays(7), Created = DateTimeOffset.UtcNow, @@ -63,6 +64,8 @@ public async Task Handle_ValidRequest_ReturnsSuccessfulRefreshTokensResponse() var client = new ByteSync.ServerCommon.Business.Auth.Client { ClientInstanceId = refreshTokensData.ClientInstanceId, + Identity = new string('A', 64), + AuthenticationEpoch = AuthenticationProtocol.Epoch, RefreshToken = expectedRefreshToken }; diff --git a/tests/ByteSync.ServerCommon.Tests/Commands/CloudSessions/FinalizeJoinCloudSessionCommandHandlerTests.cs b/tests/ByteSync.ServerCommon.Tests/Commands/CloudSessions/FinalizeJoinCloudSessionCommandHandlerTests.cs index 5f0f56d10..53003ebc6 100644 --- a/tests/ByteSync.ServerCommon.Tests/Commands/CloudSessions/FinalizeJoinCloudSessionCommandHandlerTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Commands/CloudSessions/FinalizeJoinCloudSessionCommandHandlerTests.cs @@ -84,9 +84,12 @@ public async Task Handle_SuccessfulFinalization_ReturnsSuccess() ClientInstanceId = joinerInstanceId, ValidatorInstanceId = validatorInstanceId, FinalizationPassword = finalizationPassword, + JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(1), CloudSessionData = cloudSession }; + cloudSession.SessionMembers.Add(new SessionMemberData { ClientInstanceId = validatorInstanceId, + AuthCheckClientInstanceIds = new List { joinerInstanceId } }); cloudSession.PreSessionMembers.Add(joiner); bool funcResult = false; diff --git a/tests/ByteSync.ServerCommon.Tests/Commands/Trusts/SendDigitalSignaturesCommandHandlerTests.cs b/tests/ByteSync.ServerCommon.Tests/Commands/Trusts/SendDigitalSignaturesCommandHandlerTests.cs index 102a28c55..6adc83fd7 100644 --- a/tests/ByteSync.ServerCommon.Tests/Commands/Trusts/SendDigitalSignaturesCommandHandlerTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Commands/Trusts/SendDigitalSignaturesCommandHandlerTests.cs @@ -66,8 +66,9 @@ public async Task Handle_CloudSession_ValidMember_SendsDigitalSignatures() IsAuthCheckOK = true }; - var cloudSession = new CloudSessionData(dataId, new EncryptedSessionSettings(), client); + var cloudSession = new CloudSessionData(dataId, new EncryptedSessionSettings(), client) { AuthenticationEpoch = ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch }; cloudSession.SessionMembers.Add(new SessionMemberData { ClientInstanceId = clientInstanceId }); + cloudSession.PreSessionMembers.Add(new SessionMemberData { ClientInstanceId = recipientInstanceId }); A.CallTo(() => _mockCloudSessionsRepository.Get(dataId)) .Returns(Task.FromResult(cloudSession)); @@ -121,12 +122,14 @@ public async Task Handle_Lobby_ValidMember_SendsDigitalSignatures() .Returns(Task.FromResult(null)); var profileClientId = "profileClient"; - var lobby = new Lobby { LobbyId = dataId }; + var lobby = new Lobby { LobbyId = dataId, AuthenticationEpoch = ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch }; var lobbyMember = new LobbyMember(profileClientId, new PublicKeyInfo(), JoinLobbyModes.Join, client); var lobbyMemberCell = new LobbyMemberCell("profileClient"); lobbyMemberCell.LobbyMember = lobbyMember; lobby.LobbyMemberCells.Add(lobbyMemberCell); + lobby.LobbyMemberCells.Add(new LobbyMemberCell("recipient-profile") { LobbyMember = new LobbyMember("recipient-profile", + new PublicKeyInfo(), JoinLobbyModes.Join, new Client { ClientInstanceId = recipientInstanceId }) }); A.CallTo(() => _mockLobbyRepository.Get(dataId)) .Returns(Task.FromResult(lobby)); @@ -209,7 +212,7 @@ public async Task Handle_CloudSession_ClientNotMember_DoesNotSendSignatures() DigitalSignatureCheckInfos = new List { digitalSignatureCheckInfo } }; - var cloudSession = new CloudSessionData(dataId, new EncryptedSessionSettings(), client); + var cloudSession = new CloudSessionData(dataId, new EncryptedSessionSettings(), client) { AuthenticationEpoch = ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch }; cloudSession.SessionMembers.Add(new SessionMemberData { ClientInstanceId = "differentClientId" }); A.CallTo(() => _mockCloudSessionsRepository.Get(dataId)) diff --git a/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationEpochSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationEpochSecurityTests.cs new file mode 100644 index 000000000..ac00457c2 --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationEpochSecurityTests.cs @@ -0,0 +1,91 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Authentication; +using System.Security.Claims; +using ByteSync.Common.Business.Auth; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Commands.Authentication; +using ByteSync.ServerCommon.Interfaces.Factories; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Security; +using ByteSync.ServerCommon.Tests.Helpers; +using FakeItEasy; +using FluentAssertions; +using Microsoft.IdentityModel.Tokens; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class AuthenticationEpochSecurityTests +{ + private static Client Client() => new() { Identity = new string('A', 64), AuthenticationEpoch = AuthenticationProtocol.Epoch, + ClientInstanceId = new string('A', 64) + "_" + Guid.NewGuid().ToString("D") }; + + [TestCase(0)] + [TestCase(-1)] + public void OldJwtClaims_CannotBecomeVerifiedByLookingUpAMigratedClient(int epoch) + { + var client = Client(); + var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(AuthConstants.CLAIM_CLIENT_INSTANCE_ID, client.ClientInstanceId), + new Claim(AuthConstants.CLAIM_IDENTITY, client.Identity!), new Claim(AuthConstants.CLAIM_AUTHENTICATION_EPOCH, epoch.ToString()) })); + + var act = () => ClientAuthentication.ValidateClaims(client, principal); + + act.Should().Throw(); + } + + [Test] + public void VerifiedClaims_MustMatchTheRegisteredInstanceAndIdentity() + { + var client = Client(); + var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(AuthConstants.CLAIM_CLIENT_INSTANCE_ID, client.ClientInstanceId), + new Claim(AuthConstants.CLAIM_IDENTITY, client.Identity!), new Claim(AuthConstants.CLAIM_AUTHENTICATION_EPOCH, AuthenticationProtocol.Epoch.ToString()) })); + ClientAuthentication.ValidateClaims(client, principal); + client.Identity = new string('B', 64); + + var act = () => ClientAuthentication.ValidateClaims(client, principal); + + act.Should().Throw(); + } + + [Test] + public async Task OldRefreshToken_CannotMintAVerifiedToken() + { + var client = Client(); + client.RefreshToken = new RefreshToken { Token = "old-refresh", AuthenticationEpoch = 0, Expires = DateTimeOffset.UtcNow.AddHours(1) }; + var repository = A.Fake(); + A.CallTo(() => repository.AddOrUpdate(A._, A>._)) + .ReturnsLazily((string id, Func update) => UpdateResultBuilder.BuildAddOrUpdateResult(update(client), false)); + var tokens = A.Fake(); + var handler = new RefreshTokensCommandHandler(tokens, repository); + + var result = await handler.Handle(new RefreshTokensRequest(new RefreshTokensData { ClientInstanceId = client.ClientInstanceId, Token = "old-refresh" }, "127.0.0.1"), CancellationToken.None); + + result.IsSuccess.Should().BeFalse(); + A.CallTo(() => tokens.BuildTokens(A._)).MustNotHaveHappened(); + } + [TestCase(0, false)] + [TestCase(1, true)] + public async Task SignedJwt_ThroughRegisteredBearerAuthentication_RequiresCurrentEpoch(int epoch, bool allowed) + { + var client = Client(); + var repository = A.Fake(); + A.CallTo(() => repository.Get(client.ClientInstanceId)).Returns(client); + const string secret = "local-unit-test-signing-key-with-at-least-32-bytes"; + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(repository); + ByteSync.ServerCommon.Helpers.JwtHelper.AddJwtAuthentication(services, secret); + await using var provider = services.BuildServiceProvider(); + var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(AuthConstants.ISSUER, AuthConstants.AUDIENCE, + new[] { new Claim(AuthConstants.CLAIM_CLIENT_INSTANCE_ID, client.ClientInstanceId), + new Claim(AuthConstants.CLAIM_IDENTITY, client.Identity!), new Claim(AuthConstants.CLAIM_AUTHENTICATION_EPOCH, epoch.ToString()) }, + expires: DateTime.UtcNow.AddMinutes(1), signingCredentials: new SigningCredentials( + new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(secret)), SecurityAlgorithms.HmacSha256)); + var context = new Microsoft.AspNetCore.Http.DefaultHttpContext { RequestServices = provider }; + context.Request.Headers.Authorization = "Bearer " + new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token); + + var result = await context.AuthenticateAsync(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme); + + result.Succeeded.Should().Be(allowed); + } + +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs new file mode 100644 index 000000000..32de4605d --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs @@ -0,0 +1,141 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text.Json.Nodes; +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Misc; +using ByteSync.Common.Business.Versions; +using ByteSync.ServerCommon.Interfaces.Services; +using ByteSync.ServerCommon.Services; +using FakeItEasy; +using FluentAssertions; +using StackExchange.Redis; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class AuthenticationSecurityTests +{ + private RSA _key = null!; + private AuthenticationChallengeService _service = null!; + private ConcurrentDictionary _store = null!; + + [SetUp] + public void SetUp() + { + _key = RSA.Create(2048); + _store = new(); + var database = A.Fake(); + A.CallTo(database).Where(call => call.Method.Name == "StringSetAsync").WithReturnType>() + .ReturnsLazily(call => Task.FromResult(_store.TryAdd(call.Arguments[0]!.ToString()!, call.Arguments[1]!.ToString()!))); + A.CallTo(() => database.StringGetDeleteAsync(A._, A._)) + .ReturnsLazily((RedisKey key, CommandFlags flags) => _store.TryRemove(key.ToString(), out var value) ? (RedisValue)value : RedisValue.Null); + var redis = A.Fake(); + A.CallTo(() => redis.GetDatabase()).Returns(database); + _service = new AuthenticationChallengeService(redis); + } + + [TearDown] + public void TearDown() => _key.Dispose(); + + private LoginData Login() + { + var identity = AuthenticationProtocol.GetIdentity(_key.ExportRSAPublicKey()); + return new LoginData { Identity = identity, ClientId = "legacy-display-id", ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), + PublicKey = _key.ExportRSAPublicKey(), AuthenticationEpoch = AuthenticationProtocol.Epoch, + ProtocolVersion = ProtocolVersion.CURRENT, Version = "2026.1", OsPlatform = OSPlatforms.Windows }; + } + + private void Sign(LoginData login, AuthenticationChallenge challenge) + { + login.ChallengeId = challenge.Id; + login.Signature = _key.SignData(AuthenticationProtocol.GetMessage(login, challenge), HashAlgorithmName.SHA256, RSASignaturePadding.Pss); + } + + [Test] + public async Task Login_WithDurableKey_AllowsDistinctInstancesAndRejectsReplay() + { + var first = Login(); + var second = Login(); + Sign(first, await _service.Create(first)); + Sign(second, await _service.Create(second)); + + (await _service.VerifyAndConsume(first)).Should().BeTrue(); + (await _service.VerifyAndConsume(second)).Should().BeTrue(); + (await _service.VerifyAndConsume(first)).Should().BeFalse(); + first.Identity.Should().Be(second.Identity); + first.Identity.Should().HaveLength(64); + } + + [TestCase("signature")] + [TestCase("key")] + [TestCase("identity")] + [TestCase("instance")] + [TestCase("version")] + [TestCase("epoch")] + [TestCase("protocol")] + public async Task Login_WithAlteredProof_IsRejected(string field) + { + var login = Login(); + Sign(login, await _service.Create(login)); + using var other = RSA.Create(2048); + switch (field) + { + case "signature": login.Signature[0] ^= 1; break; + case "key": login.PublicKey = other.ExportRSAPublicKey(); break; + case "identity": login.Identity = new string('A', 64); break; + case "instance": login.ClientInstanceId = login.Identity + "_" + Guid.NewGuid().ToString("D"); break; + case "version": login.Version = "other"; break; + case "epoch": login.AuthenticationEpoch = 0; break; + case "protocol": login.ProtocolVersion = 2; break; + } + + (await _service.VerifyAndConsume(login)).Should().BeFalse(); + } + + [Test] + public async Task Challenge_ConsumedConcurrently_AuthenticatesExactlyOnce() + { + var login = Login(); + Sign(login, await _service.Create(login)); + + var results = await Task.WhenAll(Enumerable.Range(0, 30).Select(_ => Task.Run(() => _service.VerifyAndConsume(login)))); + + results.Count(ok => ok).Should().Be(1); + } + + [Test] + public async Task Challenge_WhenExpired_IsRejectedEvenIfStillStored() + { + var login = Login(); + var challenge = await _service.Create(login); + var key = _store.Keys.Single(); + var record = JsonNode.Parse(_store[key])!; + challenge.ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(-1); + record["Challenge"]!["ExpiresAt"] = challenge.ExpiresAt; + _store[key] = record.ToJsonString(); + Sign(login, challenge); + + (await _service.VerifyAndConsume(login)).Should().BeFalse(); + } + + [Test] + public async Task Challenge_CannotClaimAnInstanceFromAnotherIdentity() + { + var login = Login(); + login.ClientInstanceId = "old-client-id_" + Guid.NewGuid(); + + var act = () => _service.Create(login); + + await act.Should().ThrowAsync(); + _store.Should().BeEmpty(); + } + + [Test] + public async Task MissingOrMalformedChallenge_IsRejected() + { + var login = Login(); + login.ChallengeId = "invalid"; + (await _service.VerifyAndConsume(login)).Should().BeFalse(); + login.ChallengeId = Guid.NewGuid().ToString("N"); + (await _service.VerifyAndConsume(login)).Should().BeFalse(); + } +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/JoinProofSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/JoinProofSecurityTests.cs new file mode 100644 index 000000000..8c2c14751 --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/JoinProofSecurityTests.cs @@ -0,0 +1,81 @@ +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Sessions.Cloud.Connections; +using ByteSync.Common.Interfaces.Hub; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Business.Repositories; +using ByteSync.ServerCommon.Business.Sessions; +using ByteSync.ServerCommon.Commands.CloudSessions; +using ByteSync.ServerCommon.Interfaces.Mappers; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Services; +using ByteSync.ServerCommon.Interfaces.Services.Clients; +using FakeItEasy; +using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; +using RedLockNet; +using StackExchange.Redis; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class JoinProofSecurityTests +{ + [TestCase("expired")] + [TestCase("password")] + [TestCase("identity")] + [TestCase("validator")] + [TestCase("caller")] + [TestCase("valid")] + public async Task Finalization_RequiresTheBoundUnexpiredProofAndConsumesItOnce(string scenario) + { + var identity = new string('A', 64); + var instance = identity + "_" + Guid.NewGuid().ToString("D"); + var validator = new string('B', 64) + "_" + Guid.NewGuid().ToString("D"); + var client = new Client { Identity = identity, ClientInstanceId = instance, AuthenticationEpoch = AuthenticationProtocol.Epoch }; + var session = new CloudSessionData { SessionId = "session", AuthenticationEpoch = AuthenticationProtocol.Epoch }; + var member = new SessionMemberData { ClientInstanceId = validator, Identity = new string('B', 64), AuthCheckClientInstanceIds = new() { instance } }; + session.SessionMembers.Add(member); + var joiner = new SessionMemberData { ClientInstanceId = instance, Identity = scenario == "identity" ? new string('C', 64) : identity, + ValidatorInstanceId = validator, FinalizationPassword = "test-proof", JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(scenario == "expired" ? -1 : 1), CloudSessionData = session }; + session.PreSessionMembers.Add(joiner); + var parameters = new FinalizeJoinCloudSessionParameters { SessionId = "session", JoinerInstanceId = instance, + ValidatorInstanceId = scenario == "validator" ? "other" : validator, FinalizationPassword = scenario == "password" ? "wrong" : "test-proof" }; + if (scenario == "caller") client.ClientInstanceId = "other-caller"; + var repository = A.Fake(); + A.CallTo(() => repository.Update("session", A>._, A._, A._)) + .ReturnsLazily((string id, Func update, ITransaction? tx, IRedLock? redisLock) => + new UpdateEntityResult(session, update(session) ? UpdateEntityStatus.WaitingForTransaction : UpdateEntityStatus.NoOperation)); + var redis = A.Fake(); + var transaction = A.Fake(); + A.CallTo(() => redis.OpenTransaction()).Returns(transaction); + A.CallTo(() => transaction.ExecuteAsync(A._)).Returns(true); + var groups = A.Fake(); + var pushes = A.Fake(); + var hub = A.Fake(); + A.CallTo(() => pushes.SessionGroup("session")).Returns(hub); + var handler = new FinalizeJoinCloudSessionCommandHandler(repository, A.Fake(), pushes, groups, redis, + NullLogger.Instance); + var request = new FinalizeJoinCloudSessionRequest(parameters, client); + if (scenario == "caller") + { + var act = () => handler.Handle(request, CancellationToken.None); + await act.Should().ThrowAsync(); + } + else + { + var result = await handler.Handle(request, CancellationToken.None); + if (scenario == "valid") + { + result.Status.Should().Be(FinalizeJoinSessionStatuses.FinalizeJoinSessionSucess); + joiner.FinalizationPassword.Should().BeEmpty(); + var replay = await handler.Handle(request, CancellationToken.None); + replay.Status.Should().NotBe(FinalizeJoinSessionStatuses.FinalizeJoinSessionSucess); + A.CallTo(() => hub.MemberJoinedSession(A._)).MustHaveHappenedOnceExactly(); + return; + } + result.Status.Should().NotBe(FinalizeJoinSessionStatuses.FinalizeJoinSessionSucess); + } + session.SessionMembers.Should().NotContain(joiner); + A.CallTo(groups).MustNotHaveHappened(); + A.CallTo(() => hub.MemberJoinedSession(A._)).MustNotHaveHappened(); + } +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/LoginIdentityBindingSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/LoginIdentityBindingSecurityTests.cs new file mode 100644 index 000000000..bf7003d06 --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/LoginIdentityBindingSecurityTests.cs @@ -0,0 +1,53 @@ +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Misc; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Commands.Authentication; +using ByteSync.ServerCommon.Interfaces.Factories; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Services; +using ByteSync.ServerCommon.Interfaces.Services.Clients; +using ByteSync.ServerCommon.Tests.Helpers; +using FakeItEasy; +using FluentAssertions; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class LoginIdentityBindingSecurityTests +{ + [TestCase("same", true)] + [TestCase("different", false)] + [TestCase("legacy", false)] + [TestCase("new", true)] + public async Task Login_CannotAdoptAnExistingInstanceOrLegacyClientAlias(string recordType, bool expected) + { + var identity = new string('A', 64); + var login = new LoginData { ClientId = "victim-legacy-alias", Identity = identity, ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), + OsPlatform = OSPlatforms.Windows, Version = "2026.1" }; + Client? existing = recordType == "new" ? null : new Client(identity, login.ClientInstanceId, "older", OSPlatforms.Windows, "127.0.0.1") + { Identity = recordType == "legacy" ? null : recordType == "same" ? identity : new string('B', 64), + AuthenticationEpoch = recordType == "legacy" ? 0 : AuthenticationProtocol.Epoch }; + Client? saved = null; + var repository = A.Fake(); + A.CallTo(() => repository.AddOrUpdate(login.ClientInstanceId, A>._)) + .ReturnsLazily((string id, Func update) => { saved = update(existing); return UpdateResultBuilder.BuildAddOrUpdateResult(saved, false); }); + var challenges = A.Fake(); + A.CallTo(() => challenges.VerifyAndConsume(login)).Returns(true); + var versions = A.Fake(); + A.CallTo(() => versions.IsClientVersionAllowed(login)).Returns(true); + var tokens = A.Fake(); + A.CallTo(() => tokens.BuildTokens(A._)).Returns(new JwtTokens("test-token", new RefreshToken { Token = "test-refresh", Expires = DateTimeOffset.UtcNow.AddMinutes(5) }, 300)); + var handler = new AuthenticateCommandHandler(tokens, A.Fake(), repository, versions, challenges); + + var result = await handler.Handle(new AuthenticateRequest(login, "127.0.0.2"), CancellationToken.None); + + result.IsSuccess.Should().Be(expected); + if (expected) + { + saved!.ClientId.Should().Be(identity); + saved.Identity.Should().Be(identity); + saved.Version.Should().Be(login.Version); + saved.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); + } + else A.CallTo(() => tokens.BuildTokens(A._)).MustNotHaveHappened(); + } +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/ProfileAuthorizationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/ProfileAuthorizationSecurityTests.cs new file mode 100644 index 000000000..35d326eee --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/ProfileAuthorizationSecurityTests.cs @@ -0,0 +1,81 @@ +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Lobbies.Connections; +using ByteSync.Common.Business.Profiles; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Business.Sessions; +using ByteSync.ServerCommon.Entities; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Services; +using FakeItEasy; +using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class ProfileAuthorizationSecurityTests +{ + private static Client Client() => new() { Identity = new string('A', 64), ClientId = new string('A', 64), + AuthenticationEpoch = AuthenticationProtocol.Epoch, ClientInstanceId = new string('A', 64) + "_" + Guid.NewGuid().ToString("D") }; + + [TestCase("owned")] + [TestCase("other-key")] + [TestCase("legacy-profile")] + public async Task ProfileSecretsAndDeletion_RequireCurrentEpochAndFingerprintOwnership(string scenario) + { + var client = Client(); + var profiles = A.Fake(); + var profile = new CloudSessionProfileEntity { AuthenticationEpoch = AuthenticationProtocol.Epoch, + CloudSessionProfileId = "profile", ProfileDetailsPassword = "local-test-only-value" }; + profile.Slots.Add(new CloudSessionProfileSlot { ClientId = client.Identity!, ProfileClientId = "slot" }); + if (scenario == "other-key") profile.Slots[0].ClientId = new string('B', 64); + if (scenario == "legacy-profile") profile.AuthenticationEpoch = 0; + A.CallTo(() => profiles.Get("profile")).Returns(profile); + var service = new CloudSessionProfileService(profiles, A.Fake(), NullLogger.Instance); + + var password = await service.GetProfileDetailsPassword(new GetProfileDetailsPasswordParameters { CloudSessionProfileId = "profile", ProfileClientId = "slot" }, client); + var delete = () => service.DeleteCloudSessionProfile(new DeleteCloudSessionProfileParameters { CloudSessionProfileId = "profile", ProfileClientId = "slot" }, client); + + if (scenario == "owned") + { + password.Should().Be(profile.ProfileDetailsPassword); + (await delete()).Should().BeTrue(); + A.CallTo(() => profiles.Delete("profile")).MustHaveHappenedOnceExactly(); + } + else + { + password.Should().BeNull(); + await delete.Should().ThrowAsync(); + A.CallTo(() => profiles.Delete(A._)).MustNotHaveHappened(); + } + } + + [Test] + public async Task TwoInstancesOfOneIdentity_ReceiveDistinctProfileSlots() + { + var first = Client(); + var second = Client(); + var session = new CloudSessionData { SessionId = "session", AuthenticationEpoch = AuthenticationProtocol.Epoch }; + foreach (var client in new[] { first, second }) session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, + ClientId = client.ClientId, Identity = client.Identity, CloudSessionData = session }); + var profiles = A.Fake(); + var sessions = A.Fake(); + A.CallTo(() => sessions.GetSessionMember("session", first.ClientInstanceId)).Returns(session.SessionMembers[0]); + var service = new CloudSessionProfileService(profiles, sessions, NullLogger.Instance); + CloudSessionProfileEntity? saved = null; + A.CallTo(() => profiles.Save(A._, A._, null, null)) + .Invokes((string id, CloudSessionProfileEntity value, StackExchange.Redis.ITransaction? transaction, RedLockNet.IRedLock? redisLock) => saved = value); + + await service.CreateCloudSessionProfile("session", first); + A.CallTo(() => profiles.Get(A._)).ReturnsLazily(() => saved); + A.CallTo(() => sessions.GetSessionMember("session", second.ClientInstanceId)).Returns(session.SessionMembers[1]); + var details = await service.GetCloudSessionProfileData(new GetCloudSessionProfileDataParameters + { SessionId = "session", CloudSessionProfileId = saved!.CloudSessionProfileId }, second); + + details.Should().NotBeNull(); + details!.RequesterProfileClientId.Should().Be(saved!.Slots[1].ProfileClientId); + saved.Should().NotBeNull(); + saved!.Slots.Should().HaveCount(2); + saved.Slots.Select(s => s.ProfileClientId).Should().OnlyHaveUniqueItems(); + saved.Slots.Select(s => s.OriginalClientInstanceId).Should().BeEquivalentTo(first.ClientInstanceId, second.ClientInstanceId); + } +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/SessionAuthorizationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/SessionAuthorizationSecurityTests.cs new file mode 100644 index 000000000..a068811d4 --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/SessionAuthorizationSecurityTests.cs @@ -0,0 +1,218 @@ +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Inventories; +using ByteSync.Common.Business.Versions; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Business.Sessions; +using ByteSync.ServerCommon.Commands.Inventories; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Services; +using ByteSync.ServerCommon.Security; +using FakeItEasy; +using FluentAssertions; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class SessionAuthorizationSecurityTests +{ + public static IEnumerable SessionRequests => typeof(ISessionRequest).Assembly.GetTypes() + .Where(t => !t.IsInterface && typeof(ISessionRequest).IsAssignableFrom(t)); + + private static Client Client() => new() { Identity = new string('A', 64), AuthenticationEpoch = AuthenticationProtocol.Epoch, + ClientId = new string('A', 64), ClientInstanceId = new string('A', 64) + "_" + Guid.NewGuid().ToString("D") }; + + private static object Request(Type type, Client client) + { + var constructor = type.GetConstructors().OrderBy(c => c.GetParameters().Length).First(); + var args = constructor.GetParameters().Select(p => + { + if (p.ParameterType == typeof(Client)) return (object)client; + if (p.ParameterType == typeof(string)) return p.Name == "clientInstanceId" ? client.ClientInstanceId : "session"; + var value = Activator.CreateInstance(p.ParameterType); + p.ParameterType.GetProperty("SessionId")?.SetValue(value, "session"); + return value; + }).ToArray(); + return constructor.Invoke(args); + } + + [TestCaseSource(nameof(SessionRequests))] + public async Task NonMember_OnEverySessionRequest_CannotReadMutateOrNotify(Type requestType) + { + var client = Client(); + var repository = A.Fake(); + var transfers = A.Fake(); + A.CallTo(() => repository.Get("session")).Returns(new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch, ProtocolVersion = ProtocolVersion.CURRENT }); + var behavior = new SessionAuthorizationBehavior(repository, transfers, A.Fake(), A.Fake(), A.Fake()); + var calls = 0; + var request = Request(requestType, client); + if (requestType.Name is "AskPasswordExchangeKeyRequest" or "BeginJoinSessionRequest") + { + var data = requestType.GetProperty("Parameters")!.GetValue(request)!; + data.GetType().GetProperty("PublicKeyInfo")!.SetValue(data, new ByteSync.Common.Business.EndPoints.PublicKeyInfo { PublicKey = [] }); + } + + var act = () => behavior.Handle(request, _ => { calls++; return Task.FromResult(new object()); }, CancellationToken.None); + + await act.Should().ThrowAsync(); + calls.Should().Be(0); + A.CallTo(transfers).MustNotHaveHappened(); + } + + [Test] + public async Task Member_CanReadAnotherMembersSources() + { + var client = Client(); + var repository = A.Fake(); + var session = new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch, ProtocolVersion = ProtocolVersion.CURRENT }; + session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, Identity = client.Identity }); + A.CallTo(() => repository.Get("session")).Returns(session); + var behavior = new SessionAuthorizationBehavior(repository, A.Fake(), A.Fake(), A.Fake(), A.Fake()); + var request = new GetDataSourcesRequest("session", "another-member", "another-node", client); + if (request is IFileTransferRequest transfer) { transfer.TransferParameters.PartNumber = 1; transfer.TransferParameters.TotalParts = 1; } + var called = false; + + await behavior.Handle(request, _ => { called = true; return Task.FromResult(new object()); }, CancellationToken.None); + + called.Should().BeTrue(); + } + + [Test] + public async Task Member_CannotModifyAnotherMembersSources() + { + var client = Client(); + var repository = A.Fake(); + var session = new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch, ProtocolVersion = ProtocolVersion.CURRENT }; + session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, Identity = client.Identity }); + A.CallTo(() => repository.Get("session")).Returns(session); + var behavior = new SessionAuthorizationBehavior(repository, A.Fake(), A.Fake(), A.Fake(), A.Fake()); + var request = new AddDataSourceRequest("session", client, "another-member", "node", new EncryptedDataSource()); + + var act = () => behavior.Handle(request, _ => throw new AssertionException("Handler must not run"), CancellationToken.None); + + await act.Should().ThrowAsync(); + } + [Test] + public void SessionEntryRequests_MustDeclareTheirAuthorizationBoundary() + { + var namespaces = new[] { "CloudSessions", "Inventories", "SessionMembers", "Synchronizations", "FileTransfers", "Trusts" }; + var requests = typeof(ISessionRequest).Assembly.GetTypes().Where(t => t.IsClass && t.Name.EndsWith("Request") && + namespaces.Any(n => t.Namespace == "ByteSync.ServerCommon.Commands." + n) && + t.Name is not ("CreateSessionRequest" or "SendDigitalSignaturesRequest")); + + requests.Should().OnlyContain(t => typeof(ISessionRequest).IsAssignableFrom(t)); + } + + [TestCaseSource(nameof(SessionRequests))] + public async Task AuthorizedActor_CanReachTheHandlerForEverySessionOperation(Type requestType) + { + using var rsa = System.Security.Cryptography.RSA.Create(2048); + var client = Client(); + client.Identity = AuthenticationProtocol.GetIdentity(rsa.ExportRSAPublicKey()); + client.ClientInstanceId = client.Identity + "_" + Guid.NewGuid().ToString("D"); + var key = new ByteSync.Common.Business.EndPoints.PublicKeyInfo { PublicKey = rsa.ExportRSAPublicKey() }; + var repository = A.Fake(); + var inventories = A.Fake(); + var actions = A.Fake(); + var session = new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch, ProtocolVersion = ProtocolVersion.CURRENT }; + session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, Identity = client.Identity }); + session.PreSessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, Identity = client.Identity, + JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(1), ValidatorInstanceId = client.ClientInstanceId }); + A.CallTo(() => repository.Get("session")).Returns(session); + A.CallTo(() => inventories.Get("session")).Returns(new ByteSync.ServerCommon.Entities.Inventories.InventoryEntity("session")); + var behavior = new SessionAuthorizationBehavior(repository, A.Fake(), actions, inventories, A.Fake()); + var request = Request(requestType, client); + if (request is ByteSync.ServerCommon.Commands.Synchronizations.StartSynchronizationRequest) session.IsSessionActivated = true; + foreach (var property in requestType.GetProperties()) + { + var value = property.GetValue(request); + if (value == null || value is string || value is Client) continue; + foreach (var field in value.GetType().GetProperties().Where(p => p.CanWrite)) + { + if (field.Name is "ClientInstanceId" or "JoinerClientInstanceId" or "ValidatorInstanceId" or "JoinerInstanceId" or + "SessionMemberInstanceId" or "CheckedClientInstanceId" or "OtherPartyClientInstanceId" or "MemberClientInstanceId") + field.SetValue(value, client.ClientInstanceId); + if (field.Name == "PublicKeyInfo") field.SetValue(value, key); + if (field.Name == "MembersInstanceIdsToCheck") field.SetValue(value, new List { client.ClientInstanceId }); + if (field.Name is "JoinerPublicKeyCheckData" or "PublicKeyCheckData") + field.SetValue(value, new ByteSync.Common.Business.EndPoints.PublicKeyCheckData { IssuerClientInstanceId = client.ClientInstanceId, IssuerPublicKeyInfo = key }); + } + } + if (request is IFileTransferRequest transfer) { transfer.TransferParameters.PartNumber = 1; transfer.TransferParameters.TotalParts = 1; } + var called = false; + + await behavior.Handle(request, _ => { called = true; return Task.FromResult(new object()); }, CancellationToken.None); + + called.Should().BeTrue(); + } + + [TestCase(true)] + [TestCase(false)] + public async Task Member_CannotAcknowledgeActionsOwnedByAnotherInstance(bool localCopy) + { + var client = Client(); + var sessions = A.Fake(); + var session = new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch, ProtocolVersion = ProtocolVersion.CURRENT }; + session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, Identity = client.Identity }); + A.CallTo(() => sessions.Get("session")).Returns(session); + var actions = A.Fake(); + A.CallTo(() => actions.GetOrThrow("session", "action")).Returns(new ByteSync.ServerCommon.Entities.TrackingActionEntity { SourceClientInstanceId = "other" }); + var behavior = new SessionAuthorizationBehavior(sessions, A.Fake(), actions, A.Fake(), A.Fake()); + object request = localCopy ? new ByteSync.ServerCommon.Commands.Synchronizations.LocalCopyIsDoneRequest("session", client, new List { "action" }, "node") + : new ByteSync.ServerCommon.Commands.Synchronizations.SynchronizationErrorsRequest("session", client, new List { "action" }, "node"); + + var act = () => behavior.Handle(request, _ => throw new AssertionException("Handler must not run"), CancellationToken.None); + + await act.Should().ThrowAsync(); + } + + [TestCase(false)] + [TestCase(true)] + public async Task CreateSession_BindsTheCreatorToTheProvenKey(bool wrongKey) + { + using var rsa = System.Security.Cryptography.RSA.Create(2048); + var client = Client(); + client.Identity = AuthenticationProtocol.GetIdentity(rsa.ExportRSAPublicKey()); + client.ClientInstanceId = client.Identity + "_" + Guid.NewGuid().ToString("D"); + var parameters = new ByteSync.Common.Business.Sessions.Cloud.Connections.CreateCloudSessionParameters + { + CreatorPublicKeyInfo = new ByteSync.Common.Business.EndPoints.PublicKeyInfo + { PublicKey = rsa.ExportRSAPublicKey(), ProtocolVersion = ProtocolVersion.CURRENT } + }; + if (wrongKey) client.Identity = new string('A', 64); + var behavior = new SessionAuthorizationBehavior(A.Fake(), + A.Fake(), A.Fake(), A.Fake(), A.Fake()); + var called = false; + var act = () => behavior.Handle(new ByteSync.ServerCommon.Commands.CloudSessions.CreateSessionRequest(parameters, client), + _ => { called = true; return Task.FromResult(new object()); }, CancellationToken.None); + + if (wrongKey) await act.Should().ThrowAsync(); + else await act(); + + called.Should().Be(!wrongKey); + } + + [TestCase(false)] + [TestCase(true)] + public async Task PasswordExchangeResponse_CannotImpersonateAnotherValidator(bool wrongKey) + { + using var rsa = System.Security.Cryptography.RSA.Create(2048); + var client = Client(); + var key = rsa.ExportRSAPublicKey(); + client.Identity = AuthenticationProtocol.GetIdentity(key); + client.ClientInstanceId = client.Identity + "_" + Guid.NewGuid().ToString("D"); + var session = new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch, ProtocolVersion = ProtocolVersion.CURRENT }; + session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, Identity = client.Identity }); + var sessions = A.Fake(); + A.CallTo(() => sessions.Get("session")).Returns(session); + var parameters = new ByteSync.Common.Business.Sessions.Cloud.Connections.GiveCloudSessionPasswordExchangeKeyParameters + { SessionId = "session", JoinerInstanceId = "joiner", ValidatorInstanceId = wrongKey ? client.ClientInstanceId : "other-validator", + PublicKeyInfo = new ByteSync.Common.Business.EndPoints.PublicKeyInfo { PublicKey = wrongKey ? [] : key } }; + var behavior = new SessionAuthorizationBehavior(sessions, A.Fake(), + A.Fake(), A.Fake(), A.Fake()); + + var act = () => behavior.Handle(new ByteSync.ServerCommon.Commands.CloudSessions.GiveCloudSessionPasswordExchangeKeyRequest(client, parameters), + _ => throw new AssertionException("Handler must not run"), CancellationToken.None); + + await act.Should().ThrowAsync(); + } + +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/SignalRAuthorizationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/SignalRAuthorizationSecurityTests.cs new file mode 100644 index 000000000..45f235383 --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/SignalRAuthorizationSecurityTests.cs @@ -0,0 +1,72 @@ +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Interfaces.Hub; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Business.Sessions; +using ByteSync.ServerCommon.Factories; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Services.Clients; +using FakeItEasy; +using FluentAssertions; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Logging.Abstractions; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class SignalRAuthorizationSecurityTests +{ + [Test] + public async Task Reconnection_RechecksMembershipAndIgnoresLegacySubscriptions() + { + var client = new Client { Identity = new string('A', 64), AuthenticationEpoch = AuthenticationProtocol.Epoch, + ClientInstanceId = new string('A', 64) + "_" + Guid.NewGuid().ToString("D") }; + var groups = new ClientsGroupIdFactory(); + client.SubscribedGroups = new() { groups.GetSessionGroupId("allowed"), groups.GetSessionGroupId("removed"), "Session_legacy" }; + var sessions = A.Fake(); + var session = new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch }; + session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, Identity = client.Identity }); + A.CallTo(() => sessions.Get("allowed")).Returns(session); + A.CallTo(() => sessions.Get("removed")).Returns(new CloudSessionData()); + var context = A.Fake, IHubByteSyncPush>>(); + var manager = A.Fake(); + A.CallTo(() => context.Groups).Returns(manager); + var service = new ClientsGroupsHubService(context, groups, NullLogger.Instance, sessions, A.Fake()); + + await service.AddClientGroup("reconnected", client); + + A.CallTo(() => manager.AddToGroupAsync("reconnected", groups.GetClientGroupId(client.ClientInstanceId), A._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => manager.AddToGroupAsync("reconnected", groups.GetSessionGroupId("allowed"), A._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => manager.AddToGroupAsync("reconnected", groups.GetSessionGroupId("removed"), A._)).MustNotHaveHappened(); + A.CallTo(() => manager.AddToGroupAsync("reconnected", "Session_legacy", A._)).MustNotHaveHappened(); + } + + [Test] + public async Task LeavingSession_RemovesEveryConnectionOfTheInstance() + { + var client = new Client { ConnectionIds = new() { "old-connection", "new-connection", "old-connection" } }; + var context = A.Fake, IHubByteSyncPush>>(); + var manager = A.Fake(); + A.CallTo(() => context.Groups).Returns(manager); + var groups = new ClientsGroupIdFactory(); + var service = new ClientsGroupsHubService(context, groups, NullLogger.Instance, + A.Fake(), A.Fake()); + + await service.RemoveFromSessionGroup(client, "session"); + + foreach (var id in client.ConnectionIds.Distinct()) + A.CallTo(() => manager.RemoveFromGroupAsync(id, groups.GetSessionGroupId("session"), A._)).MustHaveHappenedOnceExactly(); + } + + [Test] + public async Task LegacyIdentity_CannotAcquireAnySignalRGroup() + { + var client = new Client { ClientInstanceId = "legacy-instance" }; + var context = A.Fake, IHubByteSyncPush>>(); + var service = new ClientsGroupsHubService(context, new ClientsGroupIdFactory(), NullLogger.Instance, + A.Fake(), A.Fake()); + + var act = () => service.AddClientGroup("connection", client); + + await act.Should().ThrowAsync(); + A.CallTo(context).MustNotHaveHappened(); + } +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/StorageUrlScopeSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/StorageUrlScopeSecurityTests.cs new file mode 100644 index 000000000..fce902e21 --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/StorageUrlScopeSecurityTests.cs @@ -0,0 +1,59 @@ +using Azure.Storage; +using Azure.Storage.Blobs; +using ByteSync.Common.Business.SharedFiles; +using ByteSync.ServerCommon.Interfaces.Services.Storage.Factories; +using ByteSync.ServerCommon.Services.Storage; +using FakeItEasy; +using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class StorageUrlScopeSecurityTests +{ + [TestCase(true, "w")] + [TestCase(false, "r")] + public async Task AzureSas_IsLimitedToTheRegisteredObjectPartAndExpectedOperation(bool upload, string permission) + { + var factory = A.Fake(); + var credential = new StorageSharedKeyCredential("testaccount", Convert.ToBase64String(new byte[32])); + A.CallTo(() => factory.GetCredential()).Returns(credential); + A.CallTo(() => factory.GetOrCreateContainer(A._)).Returns(new BlobContainerClient(new Uri("https://testaccount.blob.core.windows.net/files"), credential)); + var service = new AzureBlobStorageService(factory, NullLogger.Instance); + var objectId = Guid.NewGuid().ToString("N"); + var definition = new SharedFileDefinition { StorageObjectId = objectId, Id = "untrusted", SessionId = "untrusted", AdditionalName = "../untrusted" }; + + var url = upload ? await service.GetUploadFileUrl(definition, 7) : await service.GetDownloadFileUrl(definition, 7); + var uri = new Uri(url); + var query = System.Web.HttpUtility.ParseQueryString(uri.Query); + + uri.AbsolutePath.Should().Be($"/files/{objectId}/part-7"); + query["sp"].Should().Be(permission); + query["sr"].Should().Be("b"); + DateTimeOffset.Parse(query["se"]!).Should().BeCloseTo(DateTimeOffset.UtcNow.AddMinutes(5), TimeSpan.FromSeconds(5)); + } + [TestCase(true)] + [TestCase(false)] + public async Task R2SigningRequest_IsLimitedToTheServerObjectPartAndOperation(bool upload) + { + var client = A.Fake(); + Amazon.S3.Model.GetPreSignedUrlRequest? signed = null; + A.CallTo(() => client.GetPreSignedURLAsync(A._)) + .Invokes((Amazon.S3.Model.GetPreSignedUrlRequest request) => signed = request).Returns("offline-signed-url"); + var factory = A.Fake(); + A.CallTo(() => factory.GetClient()).Returns(client); + var service = new CloudflareR2Service(Microsoft.Extensions.Options.Options.Create(new ByteSync.ServerCommon.Business.Settings.CloudflareR2Settings { BucketName = "local-test-bucket" }), + factory, NullLogger.Instance); + var objectId = Guid.NewGuid().ToString("N"); + var definition = new SharedFileDefinition { StorageObjectId = objectId, SessionId = "other", AdditionalName = "../other" }; + + var url = upload ? await service.GetUploadFileUrl(definition, 2) : await service.GetDownloadFileUrl(definition, 2); + + url.Should().Be("offline-signed-url"); + signed!.Key.Should().Be(objectId + "/part-2"); + signed.BucketName.Should().Be("local-test-bucket"); + signed.Verb.Should().Be(upload ? Amazon.S3.HttpVerb.PUT : Amazon.S3.HttpVerb.GET); + signed.Expires.Should().BeCloseTo(DateTime.UtcNow.AddMinutes(5), TimeSpan.FromSeconds(5)); + } + +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/TransferAuthorizationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/TransferAuthorizationSecurityTests.cs new file mode 100644 index 000000000..7b8723db0 --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/TransferAuthorizationSecurityTests.cs @@ -0,0 +1,166 @@ +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.SharedFiles; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Business.Sessions; +using ByteSync.ServerCommon.Business.Settings; +using ByteSync.ServerCommon.Entities; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Services; +using FakeItEasy; +using FluentAssertions; +using Microsoft.Extensions.Options; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class TransferAuthorizationSecurityTests +{ + private ICloudSessionsRepository _sessions = null!; + private ISharedFilesRepository _files = null!; + private ITrackingActionRepository _actions = null!; + private TransferAuthorizationService _service = null!; + private Client _owner = null!; + private Client _reader = null!; + private CloudSessionData _session = null!; + private SharedFileData? _record; + + private static Client Client(char identity) => new() { Identity = new string(identity, 64), AuthenticationEpoch = AuthenticationProtocol.Epoch, + ClientInstanceId = new string(identity, 64) + "_" + Guid.NewGuid().ToString("D") }; + + [SetUp] + public void SetUp() + { + _owner = Client('A'); + _reader = Client('B'); + _sessions = A.Fake(); + _files = A.Fake(); + _actions = A.Fake(); + _record = null; + _session = new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch, SessionId = "session", IsSessionActivated = true }; + foreach (var client in new[] { _owner, _reader }) + _session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, Identity = client.Identity }); + A.CallTo(() => _sessions.Get("session")).Returns(_session); + A.CallTo(() => _files.AddOrUpdate(A._, A>._)) + .Invokes((SharedFileDefinition definition, Func update) => _record = update(_record)); + A.CallTo(() => _files.Get(A._)).ReturnsLazily(() => _record); + _service = new TransferAuthorizationService(_sessions, _files, _actions, Options.Create(new AppSettings { DefaultStorageProvider = StorageProvider.AzureBlobStorage })); + } + + private TransferParameters Parameters() => new() + { + SessionId = "session", PartNumber = 1, SharedFileDefinition = new SharedFileDefinition { Id = "file", SessionId = "session", + ClientInstanceId = _owner.ClientInstanceId, SharedFileType = SharedFileTypes.FullInventory, AdditionalName = "inventory", IV = new byte[16], StorageObjectId = "attacker-selected-object" } + }; + + [Test] + public async Task Upload_CreatesImmutableServerOwnedObjectAndAllowsRecipientDownload() + { + var upload = Parameters(); + + await _service.Authorize("session", _owner, upload, true, true); + _record!.UploadedPartsNumbers.Add(1); + var download = Parameters(); + await _service.Authorize("session", _reader, download, false, false); + + _record.SharedFileDefinition.StorageObjectId.Should().NotBe("attacker-selected-object"); + Guid.TryParseExact(_record.SharedFileDefinition.StorageObjectId, "N", out _).Should().BeTrue(); + download.SharedFileDefinition.Should().BeSameAs(_record.SharedFileDefinition); + download.StorageProvider.Should().Be(StorageProvider.AzureBlobStorage); + } + + [TestCase("route")] + [TestCase("body")] + [TestCase("owner")] + [TestCase("part")] + public async Task Transfer_WithInconsistentBindings_HasNoRegistrationSideEffect(string mismatch) + { + var parameters = Parameters(); + if (mismatch == "route") parameters.SharedFileDefinition.SessionId = "other-session"; + if (mismatch == "body") parameters.SessionId = "other-session"; + if (mismatch == "owner") parameters.SharedFileDefinition.ClientInstanceId = _reader.ClientInstanceId; + if (mismatch == "part") parameters.PartNumber = -1; + + var act = () => _service.Authorize("session", _owner, parameters, true, true); + + await act.Should().ThrowAsync(); + _record.Should().BeNull(); + A.CallTo(() => _files.AddOrUpdate(A._, A>._)).MustNotHaveHappened(); + } + + [Test] + public async Task RegisteredObject_CannotChangeItsMetadataOrSession() + { + await _service.Authorize("session", _owner, Parameters(), true, true); + var altered = Parameters(); + altered.SharedFileDefinition.AdditionalName = "../other-object"; + + var act = () => _service.Authorize("session", _owner, altered, true, true); + + await act.Should().ThrowAsync(); + _record!.SharedFileDefinition.AdditionalName.Should().Be("inventory"); + } + + [Test] + public async Task Download_RequiresRegisteredUploadedPartAndExplicitRecipient() + { + var parameters = Parameters(); + var missing = () => _service.Authorize("session", _reader, parameters, false, false); + await missing.Should().ThrowAsync(); + await _service.Authorize("session", _owner, parameters, true, true); + var notUploaded = () => _service.Authorize("session", _reader, Parameters(), false, false); + await notUploaded.Should().ThrowAsync(); + _record!.UploadedPartsNumbers.Add(1); + _record.Recipients.Clear(); + var notRecipient = () => _service.Authorize("session", _reader, Parameters(), false, false); + await notRecipient.Should().ThrowAsync(); + } + + [Test] + public async Task SynchronizationUpload_RequiresOwnershipOfEveryReferencedAction() + { + var parameters = Parameters(); + parameters.SharedFileDefinition.SharedFileType = SharedFileTypes.FullSynchronization; + parameters.SharedFileDefinition.ActionsGroupIds = new List { "action" }; + A.CallTo(() => _actions.GetOrThrow("session", "action")).Returns(new TrackingActionEntity { SourceClientInstanceId = _reader.ClientInstanceId }); + + var act = () => _service.Authorize("session", _owner, parameters, true, true); + + await act.Should().ThrowAsync(); + _record.Should().BeNull(); + } + + [Test] + public async Task FinishingUpload_CannotHidePreviouslyUploadedParts() + { + await _service.Authorize("session", _owner, Parameters(), true, true); + _record!.UploadedPartsNumbers.Add(3); + var parameters = Parameters(); + parameters.PartNumber = null; + parameters.TotalParts = 2; + + var act = () => _service.Authorize("session", _owner, parameters, true, false); + + await act.Should().ThrowAsync(); + } + [Test] + public async Task CompletedPart_KeepsServerRecordForAuthorizedFinalAcknowledgement() + { + await _service.Authorize("session", _owner, Parameters(), true, true); + _record!.UploadedPartsNumbers.Add(1); + _record.TotalParts = 1; + var parameters = Parameters(); + await _service.Authorize("session", _reader, parameters, false, false); + var sharedFiles = new SharedFilesService(_files, + A.Fake(), + A.Fake(), + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, + Options.Create(new AppSettings())); + + await sharedFiles.AssertFilePartIsDownloaded(_reader, parameters); + parameters.PartNumber = null; + await _service.Authorize("session", _reader, parameters, false, false); + + _record.IsFullyDownloaded.Should().BeTrue(); + A.CallTo(() => _files.Forget(A._)).MustNotHaveHappened(); + } + +} diff --git a/tests/ByteSync.ServerCommon.Tests/Services/SharedFilesServiceTests.cs b/tests/ByteSync.ServerCommon.Tests/Services/SharedFilesServiceTests.cs index 957bd78ba..bcc1d921c 100644 --- a/tests/ByteSync.ServerCommon.Tests/Services/SharedFilesServiceTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Services/SharedFilesServiceTests.cs @@ -32,7 +32,7 @@ public void SetUp() [Test] [TestCase(StorageProvider.AzureBlobStorage)] [TestCase(StorageProvider.CloudflareR2)] - public async Task AssertFilePartIsDownloaded_WhenPartBecomesFullyDownloaded_DeletesObject_And_Unregisters_WhenRetentionDisabled(StorageProvider storageProvider) + public async Task AssertFilePartIsDownloaded_WhenPartBecomesFullyDownloaded_DeletesObject_And_RetainsAuthorizationRecord_WhenRetentionDisabled(StorageProvider storageProvider) { // Arrange var appSettings = Options.Create(new AppSettings { RetainFilesAfterTransfer = false }); @@ -91,13 +91,13 @@ public async Task AssertFilePartIsDownloaded_WhenPartBecomesFullyDownloaded_Dele } A.CallTo(() => _sharedFilesRepository.Forget(sharedFileDefinition)) - .MustHaveHappenedOnceExactly(); + .MustNotHaveHappened(); } [Test] [TestCase(StorageProvider.AzureBlobStorage)] [TestCase(StorageProvider.CloudflareR2)] - public async Task AssertFilePartIsDownloaded_WhenRetentionEnabled_DoesNotDeleteObject_ButUnregistersWhenFullyDownloaded(StorageProvider storageProvider) + public async Task AssertFilePartIsDownloaded_WhenRetentionEnabled_DoesNotDeleteObject_AndRetainsAuthorizationRecordWhenFullyDownloaded(StorageProvider storageProvider) { // Arrange var appSettings = Options.Create(new AppSettings { RetainFilesAfterTransfer = true }); @@ -143,7 +143,7 @@ public async Task AssertFilePartIsDownloaded_WhenRetentionEnabled_DoesNotDeleteO .MustNotHaveHappened(); A.CallTo(() => _sharedFilesRepository.Forget(sharedFileDefinition)) - .MustHaveHappenedOnceExactly(); + .MustNotHaveHappened(); // Also assert the in-memory state evolved to be fully downloaded for the part preExisting.IsPartFullyDownloaded(partNumber).Should().BeTrue(); From 13c0abfad8854a987fe80d12c89814fbcca72934 Mon Sep 17 00:00:00 2001 From: Paul Fresquet Date: Fri, 13 Nov 2026 18:10:18 +0100 Subject: [PATCH 2/8] [fix] Consume authentication challenges atomically on Redis 6.0 --- docs/security-boundaries.md | 22 ++- .../AuthenticationChallengeService.cs | 11 +- .../AuthenticationChallengeRedis60Tests.cs | 149 ++++++++++++++++++ .../Security/AuthenticationSecurityTests.cs | 68 +++++++- 4 files changed, 241 insertions(+), 9 deletions(-) create mode 100644 tests/ByteSync.ServerCommon.Tests/Integration/AuthenticationChallengeRedis60Tests.cs diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md index 3f40cb05d..1160c17d5 100644 --- a/docs/security-boundaries.md +++ b/docs/security-boundaries.md @@ -10,7 +10,7 @@ This is an implementation and local validation report, not evidence of a deploye `AuthenticationProtocol` derives the identity from SHA-256 of canonical DER SubjectPublicKeyInfo after fully importing the existing PKCS#1 RSA public key. The full uppercase 64-character fingerprint is the security identity. Keys must be 2048–8192 bits; trailing key data is rejected. Instance identifiers consist of that fingerprint, an underscore and a canonical GUID. Multiple instances can prove possession of the same durable key independently. -The client retains its existing RSA private key. Login first obtains a random 256-bit server nonce with a two-minute lifetime, then signs a length-prefixed canonical binary message with RSA-PSS/SHA-256. The message binds the domain, authentication epoch, relay audience, protocol version, challenge ID, nonce, expiry, fingerprint, instance, software version and platform. The relay stores the exact binding, consumes the Redis challenge using atomic `GETDEL`, then verifies the signature. Failed verification does not issue tokens or adopt an existing instance. Redis 6.2 or newer, or a compatible service implementing GETDEL, is a deployment prerequisite. +The client retains its existing RSA private key. Login first obtains a random 256-bit server nonce with a two-minute lifetime, then signs a length-prefixed canonical binary message with RSA-PSS/SHA-256. The message binds the domain, authentication epoch, relay audience, protocol version, challenge ID, nonce, expiry, fingerprint, instance, software version and platform. The relay stores the exact binding, consumes the Redis challenge using a single atomic Lua script (`GET` followed by `DEL` inside the script), then verifies the signature. Failed verification does not issue tokens or adopt an existing instance. The script uses commands available in Azure Cache for Redis 6.0; GETDEL is not required. Scripting must be permitted, and script errors fail closed without a non-atomic fallback. The current authentication epoch is 1 and protocol is V3. Software version remains a separate compatibility check and cannot substitute for proof of possession. The legacy short `ApplicationSettings.ClientId` remains a display/trust alias; it cannot claim a server identity or an old instance. There is no first-key-wins migration of old aliases. Existing mismatched or legacy instance records are rejected. @@ -81,7 +81,7 @@ Microsoft documents that a directory must be empty to establish a reparse point: | Persist locally enrolled permissions | Ask for confirmation at every sync | Local permissions preserve unattended operation without substituting prompts for enforcement. | | Native no-follow access and initial link refusal | GetFullPath/StartsWith or repeated path checks alone | Text does not pin the filesystem object accessed. Supporting links safely needs additional design. | -## Validation +## Initial security-boundary validation The final non-incremental build and each test command were run separately. Final commands and result counts are recorded below. TRX and coverage artifacts are retained locally under `artifacts/security-boundaries/`; build/test logs are local ignored files. They contain no intentionally logged tokens, private keys or session secrets. Test keys and sentinels are synthetic. @@ -130,11 +130,27 @@ Security tests cover real RSA proofs, expiry/replay, concurrent consumption (30 ### Validation not performed * No tests against production, staging or hosted ByteSync, Redis, Azure SignalR, Blob Storage or R2. Server repository and Functions integration suites require configured services and were excluded. R2 upload/download and resume integration classes were excluded explicitly. -* Atomic Redis behavior is implemented with GETDEL and tested with a fake; a real supported Redis deployment, RedLock/transaction failure and failover behavior must be exercised in an isolated environment. +* Challenge consumption uses an atomic Lua script compatible with Redis 6.0. Distributed Redis/RedLock transaction failures and failover behavior still require isolated integration validation. * Docker is installed but its engine was unavailable; no ready Linux/macOS runner was available. POSIX native syscall/ABI behavior, filesystem-specific edge cases and packaged applications need runtime tests on each supported OS/architecture. * Windows ACL-denial integration cases self-skipped because this host did not enforce their synthetic permission changes. POSIX-only tests cannot run on Windows. * No Sonar PR analysis, production-scale/load/rate-limit evaluation, complete UI/manual trust exchange, or live multi-machine automatic synchronization was run. Local tests do not establish a production security certification. +## Redis 6.0 compatibility follow-up + +Azure resource metadata confirmed that the ByteSync development/staging and production caches use Azure Cache for Redis 6.0 (Basic and Standard respectively). GETDEL requires Redis 6.2 and is unavailable on those engines. Authentication now consumes a challenge by executing one short Lua script with one explicitly declared key: GET the value, DEL that same key if present, and return the value. Redis executes the script atomically; there is no separate client-side GET/DEL or weak authentication fallback. Missing/expired values reject authentication, invalid signatures still burn their challenge, and script/server errors propagate without issuing tokens. The RSA binding, two-minute challenge expiry and authentication epoch are preserved. No infrastructure upgrade is required for this change. See [Redis scripting atomicity](https://redis.io/docs/latest/develop/programmability/eval-intro/) and [Azure Cache versions](https://learn.microsoft.com/en-us/azure/azure-cache-for-redis/cache-how-to-upgrade#current-versions). + +The unit fake now rejects GETDEL as Redis 6.0 does. Added cases enforce one ScriptEvaluateAsync call with exactly the challenge key, verify that an invalid signature consumes only its own challenge, and verify that a script failure never falls back to non-atomic commands. Existing concurrent-consumer, replay, expiry, key/instance and signature checks remain active. + +Follow-up validation: solution build succeeded with zero errors (142 warnings); **367 server unit tests and 66 Functions unit tests passed, zero failures**. Coverage of the C# AuthenticationChallengeService is 100.0% (42/42 executable lines). This does not measure execution of the Lua body. Local TRX/Cobertura evidence is indexed by [Redis 6.0 validation](../artifacts/security-boundaries/redis60/validation.json). The initial validation counts above belong to the earlier commit. + +Four explicit integration cases were added in `AuthenticationChallengeRedis60Tests` for a real disposable Redis 6.0: valid proof/replay and TTL, 30 concurrent consumers across independent connections, invalid-signature consumption and isolation, and Redis-side expiry/nil handling. They only connect to 127.0.0.1, require an explicit Redis60Port parameter, check the server is version 6.0, and remove only the randomly generated challenge keys they created. They do not load hosted connection settings. **These four cases were not executed:** Docker failed during startup and Paul stopped it. Docker was not restarted and no test was run against Azure Redis. Run them later with an isolated local Redis 6.0 and an explicit port, for example: + +```powershell +rtk proxy dotnet test tests/ByteSync.ServerCommon.Tests/ByteSync.ServerCommon.Tests.csproj --no-build --no-restore --filter 'FullyQualifiedName~AuthenticationChallengeRedis60Tests' -- 'TestRunParameters.Parameter(name="Redis60Port", value="16379")' +``` + +The server regression run excluded `.Repositories.` and `.Integration.` to avoid running service-dependent suites. This follow-up changed no Azure settings and requires no production or staging data access. + ## Future rollout proposal (not executed) 1. Review this patch and approve the breaking protocol, restrictions and enrollment experience. Complete native multi-platform CI, isolated Redis/SignalR/storage end-to-end tests, load/abuse checks and the coverage gate. Confirm the Redis version before rollout. Back up local RSA/settings/trust/profile data through the existing supported process; do not collect private keys centrally. diff --git a/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs b/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs index d911cc5ac..da3b4ace9 100644 --- a/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs +++ b/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs @@ -11,6 +11,14 @@ public class AuthenticationChallengeService(IRedisInfrastructureService redis) : { private sealed record ChallengeRecord(LoginData Login, AuthenticationChallenge Challenge); + private const string ConsumeChallengeScript = """ + local value = redis.call('GET', KEYS[1]) + if value then + redis.call('DEL', KEYS[1]) + end + return value + """; + public async Task Create(LoginData login) { Validate(login); @@ -32,7 +40,8 @@ public async Task VerifyAndConsume(LoginData login) { Validate(login); if (!Guid.TryParseExact(login.ChallengeId, "N", out _)) return false; - var value = await redis.GetDatabase().StringGetDeleteAsync(Key(login.ChallengeId)); + var value = (RedisValue)await redis.GetDatabase().ScriptEvaluateAsync(ConsumeChallengeScript, + new RedisKey[] { Key(login.ChallengeId) }, Array.Empty()); if (value.IsNullOrEmpty) return false; var record = JsonSerializer.Deserialize((string)value!)!; if (record.Challenge.ExpiresAt <= DateTimeOffset.UtcNow) return false; diff --git a/tests/ByteSync.ServerCommon.Tests/Integration/AuthenticationChallengeRedis60Tests.cs b/tests/ByteSync.ServerCommon.Tests/Integration/AuthenticationChallengeRedis60Tests.cs new file mode 100644 index 000000000..ae1d85a32 --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Integration/AuthenticationChallengeRedis60Tests.cs @@ -0,0 +1,149 @@ +using System.Security.Cryptography; +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Versions; +using ByteSync.ServerCommon.Interfaces.Services; +using ByteSync.ServerCommon.Services; +using FakeItEasy; +using FluentAssertions; +using StackExchange.Redis; + +namespace ByteSync.ServerCommon.Tests.Integration; + +[Explicit("Requires a disposable Redis 6.0 bound to 127.0.0.1 and the Redis60Port test parameter")] +public class AuthenticationChallengeRedis60Tests +{ + private ConnectionMultiplexer _connection = null!; + private IDatabase _database = null!; + private AuthenticationChallengeService _service = null!; + private RSA _key = null!; + private int _port; + private readonly List _challengeKeys = new(); + + [OneTimeSetUp] + public async Task ConnectToDisposableLocalRedis() + { + if (!int.TryParse(TestContext.Parameters.Get("Redis60Port", ""), out _port) || _port is < 1 or > 65535) + Assert.Ignore("Supply Redis60Port for a disposable local Redis 6.0 instance"); + _connection = await ConnectionMultiplexer.ConnectAsync(Options()); + var version = _connection.GetServer("127.0.0.1", _port).Version; + version.Major.Should().Be(6); + version.Minor.Should().Be(0); + _database = _connection.GetDatabase(); + } + + private ConfigurationOptions Options() => new() + { + EndPoints = { { "127.0.0.1", _port } }, + AbortOnConnectFail = true, ConnectRetry = 0, ConnectTimeout = 5000, SyncTimeout = 5000 + }; + + private static AuthenticationChallengeService Service(IDatabase database) + { + var redis = A.Fake(); + A.CallTo(() => redis.GetDatabase()).Returns(database); + return new AuthenticationChallengeService(redis); + } + + [SetUp] + public void SetUp() + { + _key = RSA.Create(2048); + _service = Service(_database); + _challengeKeys.Clear(); + } + + private LoginData Login() + { + var identity = AuthenticationProtocol.GetIdentity(_key.ExportRSAPublicKey()); + return new LoginData { Identity = identity, ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), + PublicKey = _key.ExportRSAPublicKey(), AuthenticationEpoch = AuthenticationProtocol.Epoch, + ProtocolVersion = ProtocolVersion.CURRENT, Version = "local-redis60-test" }; + } + + private async Task CreateAndSign(LoginData login) + { + var challenge = await _service.Create(login); + _challengeKeys.Add(Key(challenge)); + Sign(login, challenge); + return challenge; + } + + private void Sign(LoginData login, AuthenticationChallenge challenge) + { + login.ChallengeId = challenge.Id; + login.Signature = _key.SignData(AuthenticationProtocol.GetMessage(login, challenge), HashAlgorithmName.SHA256, RSASignaturePadding.Pss); + } + + private static RedisKey Key(AuthenticationChallenge challenge) => $"auth:{AuthenticationProtocol.Epoch}:challenge:{challenge.Id}"; + + [Test] + public async Task ValidProof_IsConsumedOnRedis60_AndReplayIsRejected() + { + var login = Login(); + var challenge = await CreateAndSign(login); + var lifetime = await _database.KeyTimeToLiveAsync(Key(challenge)); + + var accepted = await _service.VerifyAndConsume(login); + var replay = await _service.VerifyAndConsume(login); + + lifetime.Should().NotBeNull(); + lifetime!.Value.Should().BePositive().And.BeLessThanOrEqualTo(TimeSpan.FromMinutes(2)); + accepted.Should().BeTrue(); + replay.Should().BeFalse(); + (await _database.KeyExistsAsync(Key(challenge))).Should().BeFalse(); + } + + [Test] + public async Task ConcurrentConsumers_OnIndependentConnections_AuthenticateExactlyOnce() + { + var login = Login(); + await CreateAndSign(login); + using var secondConnection = await ConnectionMultiplexer.ConnectAsync(Options()); + var secondService = Service(secondConnection.GetDatabase()); + + var results = await Task.WhenAll(Enumerable.Range(0, 30) + .Select(i => (i % 2 == 0 ? _service : secondService).VerifyAndConsume(login))); + + results.Count(accepted => accepted).Should().Be(1); + } + + [Test] + public async Task InvalidSignature_BurnsItsChallenge_AndPreservesAnotherChallenge() + { + var login = Login(); + var challenge = await CreateAndSign(login); + var other = Login(); + await CreateAndSign(other); + login.Signature[0] ^= 1; + + (await _service.VerifyAndConsume(login)).Should().BeFalse(); + Sign(login, challenge); + (await _service.VerifyAndConsume(login)).Should().BeFalse(); + + (await _service.VerifyAndConsume(other)).Should().BeTrue(); + } + + [Test] + public async Task RedisExpiredChallenge_ReturnsNil_AndIsRejected() + { + var login = Login(); + var challenge = await CreateAndSign(login); + await _database.KeyExpireAsync(Key(challenge), TimeSpan.FromMilliseconds(1)); + await Task.Delay(50); + + var accepted = await _service.VerifyAndConsume(login); + + accepted.Should().BeFalse(); + (await _database.KeyExistsAsync(Key(challenge))).Should().BeFalse(); + } + + [TearDown] + public async Task RemoveOnlyCreatedChallenges() + { + if (_challengeKeys.Count != 0) await _database.KeyDeleteAsync(_challengeKeys.ToArray()); + _key?.Dispose(); + } + + [OneTimeTearDown] + public void Disconnect() => _connection?.Dispose(); +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs index 32de4605d..8bce8c68f 100644 --- a/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs @@ -17,19 +17,23 @@ public class AuthenticationSecurityTests private RSA _key = null!; private AuthenticationChallengeService _service = null!; private ConcurrentDictionary _store = null!; + private IDatabaseAsync _database = null!; [SetUp] public void SetUp() { _key = RSA.Create(2048); _store = new(); - var database = A.Fake(); - A.CallTo(database).Where(call => call.Method.Name == "StringSetAsync").WithReturnType>() + _database = A.Fake(); + A.CallTo(_database).Where(call => call.Method.Name == "StringSetAsync").WithReturnType>() .ReturnsLazily(call => Task.FromResult(_store.TryAdd(call.Arguments[0]!.ToString()!, call.Arguments[1]!.ToString()!))); - A.CallTo(() => database.StringGetDeleteAsync(A._, A._)) - .ReturnsLazily((RedisKey key, CommandFlags flags) => _store.TryRemove(key.ToString(), out var value) ? (RedisValue)value : RedisValue.Null); + A.CallTo(() => _database.StringGetDeleteAsync(A._, A._)) + .Throws(new RedisServerException("ERR unknown command 'GETDEL'")); + A.CallTo(() => _database.ScriptEvaluateAsync(A._, A._, A._, A._)) + .ReturnsLazily((string script, RedisKey[] keys, RedisValue[] values, CommandFlags flags) => + RedisResult.Create(_store.TryRemove(keys.Single().ToString(), out var value) ? (RedisValue)value : RedisValue.Null)); var redis = A.Fake(); - A.CallTo(() => redis.GetDatabase()).Returns(database); + A.CallTo(() => redis.GetDatabase()).Returns(_database); _service = new AuthenticationChallengeService(redis); } @@ -138,4 +142,58 @@ public async Task MissingOrMalformedChallenge_IsRejected() login.ChallengeId = Guid.NewGuid().ToString("N"); (await _service.VerifyAndConsume(login)).Should().BeFalse(); } + [Test] + public async Task Challenge_Consumption_UsesOneScriptWithAnExplicitKeyAndNoSeparateCommands() + { + var login = Login(); + var challenge = await _service.Create(login); + Sign(login, challenge); + Fake.ClearRecordedCalls(_database); + + var authenticated = await _service.VerifyAndConsume(login); + + authenticated.Should().BeTrue(); + var calls = Fake.GetCalls(_database).ToList(); + calls.Should().ContainSingle(); + var call = calls.Single(); + call.Method.Name.Should().Be(nameof(IDatabaseAsync.ScriptEvaluateAsync)); + call.Arguments.Get(1).Should().Equal((RedisKey)$"auth:{AuthenticationProtocol.Epoch}:challenge:{challenge.Id}"); + call.Arguments.Get(2).Should().BeEmpty(); + } + + [Test] + public async Task InvalidSignature_ConsumesOnlyItsChallengeAndCannotBeRetriedWithAValidSignature() + { + var login = Login(); + var challenge = await _service.Create(login); + var other = Login(); + Sign(other, await _service.Create(other)); + Sign(login, challenge); + login.Signature[0] ^= 1; + + (await _service.VerifyAndConsume(login)).Should().BeFalse(); + Sign(login, challenge); + + (await _service.VerifyAndConsume(login)).Should().BeFalse(); + (await _service.VerifyAndConsume(other)).Should().BeTrue(); + _store.Should().BeEmpty(); + } + + [Test] + public async Task RedisScriptFailure_DoesNotFallBackToNonAtomicConsumption() + { + var login = Login(); + Sign(login, await _service.Create(login)); + A.CallTo(() => _database.ScriptEvaluateAsync(A._, A._, A._, A._)) + .Throws(new RedisServerException("ERR scripting unavailable")); + Fake.ClearRecordedCalls(_database); + + var act = () => _service.VerifyAndConsume(login); + + await act.Should().ThrowAsync(); + Fake.GetCalls(_database).Should().ContainSingle(call => call.Method.Name == nameof(IDatabaseAsync.ScriptEvaluateAsync)); + Fake.GetCalls(_database).Should().HaveCount(1); + _store.Should().ContainSingle(); + } + } From bc6f609cb53b6a59da7b854835be861bf022183c Mon Sep 17 00:00:00 2001 From: Paul Fresquet Date: Fri, 13 Nov 2026 19:48:46 +0100 Subject: [PATCH 3/8] [test] Guard Redis 6.0 and authentication protocol compatibility --- docs/security-boundaries.md | 18 ++ .../Repositories/CacheRepository.cs | 6 +- .../AuthProtocolCompatibilityTests.cs | 101 ++++++++ .../Business/Versions/ProtocolVersionTests.cs | 8 +- .../Security/Redis60CompatibilityTests.cs | 224 ++++++++++++++++++ 5 files changed, 353 insertions(+), 4 deletions(-) create mode 100644 tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs create mode 100644 tests/ByteSync.ServerCommon.Tests/Security/Redis60CompatibilityTests.cs diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md index 1160c17d5..ebda74ed1 100644 --- a/docs/security-boundaries.md +++ b/docs/security-boundaries.md @@ -151,6 +151,24 @@ rtk proxy dotnet test tests/ByteSync.ServerCommon.Tests/ByteSync.ServerCommon.Te The server regression run excluded `.Repositories.` and `.Integration.` to avoid running service-dependent suites. This follow-up changed no Azure settings and requires no production or staging data access. +## Offline Redis 6.0 regression guard + +`Redis60CompatibilityTests` runs in the ordinary server unit suite without a Redis process, Azure access, configuration secrets, Docker or network access. It inspects compiled production IL, including async state machines and generic repository methods, and allows only the reviewed Redis API overloads. Unreviewed command APIs and raw command dispatch fail the test. The audit covers StackExchange.Redis 2.10.1 and RedLock.net 2.3.2; the resolved dependency versions must match that baseline so SDK command-mapping changes require review. + +Lua bodies are restricted to the audited constant script, and RedLock's actual embedded Extend/Unlock resources are checked against audited SHA-256 digests. Line endings are normalized for cross-platform checkouts. Changing Lua commands, options, dynamic dispatch or these dependency versions requires an explicit compatibility review and baseline update. This is a conservative audit allowlist; a new compatible operation also requires review. Reflection-based or dynamically generated production command dispatch is outside this static guard and must not be used to bypass it. + +The guard's negative cases cover GETDEL, GETEX, SET GET/EXAT, read-only scripting APIs, raw dispatch, absolute-expiry/value-condition overloads, and a real GETDEL call in compiled test code that is inspected but never executed. Repository saves now explicitly select the TimeSpan/When overload for their two-day TTL. The former three-argument call selected the modern Expiration/ValueCondition overload; its existing relative-TTL/default-condition usage was compatible, but that broader overload is deliberately refused by the guard. Fake-backed tests exercise both immediate and transactional saves and assert the relative TTL and audited overload. + +Validation: solution build succeeded with zero errors (17 warnings). **1,742 tests passed with zero failures**: 386 server, 1,236 client, 54 Common, 66 Functions. These include 19 Redis guard cases and four new client authentication cases. Twelve existing POSIX-only client cases did not execute on Windows. Evidence: [guard validation](../artifacts/security-boundaries/redis-guard/final/validation.json). Redis runtime/ACL/failover behavior remains outside this run; no Azure endpoint was contacted and Docker was not started. + +### Older relay and client compatibility + +The supplied client log shows a 404 for `auth/challenge` while targeting the remote development API, before SignalR negotiation or any peer exchange. The source before this branch has no challenge endpoint. An old relay or a deployment missing that route therefore cannot authenticate this client. The deployed server version was not probed; this diagnosis uses the supplied log and local source only. + +V3 clients require the matching relay and V3 peers. An older V2 peer is explicitly incompatible, and an older relay cannot provide the required possession proof. Regression tests assert that a missing challenge endpoint fails without calling the legacy login; a supported relay receives a valid RSA-PSS proof with the current epoch/protocol; refresh has no login fallback; and V2 remains rejected. The secure protocol is not downgraded to restore legacy connectivity. + +For local Rider testing, run the Functions project built from this branch and launch the client in Debug with `--use-local-api`. Check the client's `LocalDebugUrl` matches the Functions host's actual port and `/api/` base path, then confirm the client log selects that local URL. Debug defaults to the remote DevelopmentUrl when no API-selection argument is supplied. The local-API switch applies to Debug execution; Release uses ProductionUrl (or its existing staging override). Run all session peers from the same V3 branch and create a fresh session. Coordinated remote deployment remains a separate, unexecuted operation. + ## Future rollout proposal (not executed) 1. Review this patch and approve the breaking protocol, restrictions and enrollment experience. Complete native multi-platform CI, isolated Redis/SignalR/storage end-to-end tests, load/abuse checks and the coverage gate. Confirm the Redis version before rollout. Back up local RSA/settings/trust/profile data through the existing supported process; do not collect private keys centrally. diff --git a/src/ByteSync.ServerCommon/Repositories/CacheRepository.cs b/src/ByteSync.ServerCommon/Repositories/CacheRepository.cs index 3322ebf30..b90b60b97 100644 --- a/src/ByteSync.ServerCommon/Repositories/CacheRepository.cs +++ b/src/ByteSync.ServerCommon/Repositories/CacheRepository.cs @@ -126,11 +126,11 @@ private async Task> SaveInternal(CacheKey cacheKey, T elem if (database is ITransaction) { - _ = database.StringSetAsync(cacheKey.Value, serializedElement, _expiry); + _ = database.StringSetAsync(cacheKey.Value, serializedElement, _expiry, When.Always); return new UpdateEntityResult(element, UpdateEntityStatus.WaitingForTransaction); } - await database.StringSetAsync(cacheKey.Value, serializedElement, _expiry); + await database.StringSetAsync(cacheKey.Value, serializedElement, _expiry, When.Always); return new UpdateEntityResult(element, UpdateEntityStatus.Saved); } -} \ No newline at end of file +} diff --git a/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs b/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs new file mode 100644 index 000000000..0c8f0e8f0 --- /dev/null +++ b/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs @@ -0,0 +1,101 @@ +using System.Net; +using System.Security.Cryptography; +using ByteSync.Business.Configurations; +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Versions; +using ByteSync.Exceptions; +using ByteSync.Interfaces; +using ByteSync.Interfaces.Controls.Communications.Http; +using ByteSync.Services.Communications.Api; +using FluentAssertions; +using Moq; +using NUnit.Framework; + +namespace ByteSync.Client.UnitTests.Services.Security; + +public class AuthProtocolCompatibilityTests +{ + private ApplicationSettings _settings = null!; + private Mock _api = null!; + private AuthApiClient _client = null!; + + [SetUp] + public void SetUp() + { + _settings = new ApplicationSettings { InstallationId = "local-protocol-test" }; + _settings.SetEncryptionPassword("local-test-only-password"); + _settings.InitializeRsa(); + var repository = new Mock(); + repository.Setup(r => r.GetCurrentApplicationSettings()).Returns(_settings); + _api = new Mock(MockBehavior.Strict); + _client = new AuthApiClient(_api.Object, repository.Object); + } + + [TearDown] + public void TearDown() => _settings.PrivateRsa.Dispose(); + + [Test] + public async Task OlderRelayWithoutChallengeEndpoint_IsRejectedWithoutCallingLegacyLogin() + { + var error = new ApiException("Challenge request failed", new ApiException("Not Found", HttpStatusCode.NotFound)); + _api.Setup(a => a.PostAsync("auth/challenge", It.IsAny(), It.IsAny())) + .ThrowsAsync(error); + + var act = () => _client.Login(new LoginData()); + + (await act.Should().ThrowAsync()).Which.Should().BeSameAs(error); + _api.Verify(a => a.PostAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + _api.Verify(a => a.PostAsync("auth/challenge", It.IsAny(), It.IsAny()), Times.Once); + _api.VerifyNoOtherCalls(); + } + + [Test] + public async Task CurrentRelay_ReceivesAValidProofWithTheCurrentEpochAndProtocol() + { + var identity = AuthenticationProtocol.GetIdentity(_settings.DecodedRsaPublicKey!); + var login = new LoginData { ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), Version = "local-test" }; + var challenge = new AuthenticationChallenge { Id = Guid.NewGuid().ToString("N"), Nonce = "local-test-nonce", ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(2) }; + var response = new InitialAuthenticationResponse(InitialConnectionStatus.Success); + var sequence = new MockSequence(); + _api.InSequence(sequence).Setup(a => a.PostAsync("auth/challenge", login, It.IsAny())) + .ReturnsAsync(challenge); + _api.InSequence(sequence).Setup(a => a.PostAsync("auth/login", login, It.IsAny())) + .ReturnsAsync(response); + + var result = await _client.Login(login); + + result.Should().BeSameAs(response); + login.Identity.Should().Be(identity); + login.ProtocolVersion.Should().Be(ProtocolVersion.CURRENT); + login.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); + using var publicKey = RSA.Create(); + publicKey.ImportRSAPublicKey(login.PublicKey, out _); + publicKey.VerifyData(AuthenticationProtocol.GetMessage(login, challenge), login.Signature, + HashAlgorithmName.SHA256, RSASignaturePadding.Pss).Should().BeTrue(); + } + + [Test] + public async Task Refresh_UsesTheDedicatedRefreshEndpoint() + { + var request = new RefreshTokensData(); + var response = new RefreshTokensResponse(RefreshTokensStatus.RefreshTokenOk); + _api.Setup(a => a.PostAsync("auth/refreshTokens", request, It.IsAny())).ReturnsAsync(response); + + var result = await _client.RefreshAuthenticationTokens(request); + + result.Should().BeSameAs(response); + } + + [Test] + public async Task RefreshFailure_DoesNotFallBackToLogin() + { + var error = new ApiException("Refresh failed"); + _api.Setup(a => a.PostAsync("auth/refreshTokens", It.IsAny(), It.IsAny())).ThrowsAsync(error); + + var act = () => _client.RefreshAuthenticationTokens(new RefreshTokensData()); + + (await act.Should().ThrowAsync()).Which.Should().BeSameAs(error); + _api.Verify(a => a.PostAsync("auth/refreshTokens", It.IsAny(), It.IsAny()), Times.Once); + _api.VerifyNoOtherCalls(); + } +} diff --git a/tests/ByteSync.Common.Tests/Business/Versions/ProtocolVersionTests.cs b/tests/ByteSync.Common.Tests/Business/Versions/ProtocolVersionTests.cs index 063b062db..4534e3b54 100644 --- a/tests/ByteSync.Common.Tests/Business/Versions/ProtocolVersionTests.cs +++ b/tests/ByteSync.Common.Tests/Business/Versions/ProtocolVersionTests.cs @@ -34,6 +34,12 @@ public void IsCompatible_WithV1_ShouldReturnFalse() result.Should().BeFalse(); } + + [Test] + public void IsCompatible_WithLegacyV2_ShouldReturnFalse() + { + ProtocolVersion.IsCompatible(ProtocolVersion.V2).Should().BeFalse(); + } [Test] public void IsCompatible_WithZero_ShouldReturnFalse() @@ -58,4 +64,4 @@ public void IsCompatible_WithNegativeVersion_ShouldReturnFalse() result.Should().BeFalse(); } -} \ No newline at end of file +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/Redis60CompatibilityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/Redis60CompatibilityTests.cs new file mode 100644 index 000000000..560304aff --- /dev/null +++ b/tests/ByteSync.ServerCommon.Tests/Security/Redis60CompatibilityTests.cs @@ -0,0 +1,224 @@ +using System.Reflection; +using System.Reflection.Emit; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using ByteSync.ServerCommon.Business.Repositories; +using ByteSync.ServerCommon.Entities; +using ByteSync.ServerCommon.Interfaces.Services; +using ByteSync.ServerCommon.Repositories; +using ByteSync.ServerCommon.Services; +using FakeItEasy; +using FluentAssertions; +using StackExchange.Redis; + +namespace ByteSync.ServerCommon.Tests.Security; + +public class Redis60CompatibilityTests +{ + private const string AuditRequired = "Redis commands, options and SDK mappings must be reviewed against Azure Redis 6.0 before updating this audit baseline"; + + private static readonly HashSet CommandInterfaces = new[] + { typeof(IDatabase), typeof(IDatabaseAsync), typeof(ITransaction), typeof(IServer), typeof(ISubscriber) } + .SelectMany(t => t.GetInterfaces().Append(t)).ToHashSet(); + + private static readonly Dictionary OpCodesByValue = typeof(OpCodes) + .GetFields(BindingFlags.Public | BindingFlags.Static) + .Select(f => (OpCode)f.GetValue(null)!).ToDictionary(o => o.Value); + + private static readonly HashSet AuditedApis = new(StringComparer.Ordinal) + { + Signature("StringGetAsync", typeof(RedisKey), typeof(CommandFlags)), + Signature("StringSetAsync", typeof(RedisKey), typeof(RedisValue), typeof(TimeSpan?), typeof(When)), + Signature("StringSetAsync", typeof(RedisKey), typeof(RedisValue), typeof(TimeSpan?), typeof(When), typeof(CommandFlags)), + Signature("StringSetAsync", typeof(RedisKey), typeof(RedisValue), typeof(TimeSpan?), typeof(bool), typeof(When), typeof(CommandFlags)), + Signature("KeyDeleteAsync", typeof(RedisKey), typeof(CommandFlags)), + Signature("SetAddAsync", typeof(RedisKey), typeof(RedisValue), typeof(CommandFlags)), + Signature("SetRemoveAsync", typeof(RedisKey), typeof(RedisValue), typeof(CommandFlags)), + Signature("SetMembersAsync", typeof(RedisKey), typeof(CommandFlags)), + Signature("ScriptEvaluateAsync", typeof(string), typeof(RedisKey[]), typeof(RedisValue[]), typeof(CommandFlags)), + Signature("CreateTransaction", typeof(object)), + Signature("ExecuteAsync", typeof(CommandFlags)) + }; + + private static readonly HashSet AuditedScripts = new(StringComparer.Ordinal) + { + "9B8A14D849ACA456C4D959D2B256B849361DF9E44C1A903A814533F16FCB2549", + "077D24608F05B5FCC125F221E02CF31FF189127ACF7DF7C6DD12CBE5D43DC197", + "0FC555D8BD3E0FD9BE8FC585E833428D7C75489ABB3290212D4D5D5EE32F459C" + }; + + private sealed record Operand(MethodBase? Method = null, string? Text = null); + private sealed record Body(MethodBase Method, List Operands); + + private static List ProductionBodies() + { + const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | + BindingFlags.Static | BindingFlags.DeclaredOnly; + return typeof(AuthenticationChallengeService).Assembly.GetTypes() + .SelectMany(t => t.GetMethods(flags).Cast().Concat(t.GetConstructors(flags)) + .Concat(t.TypeInitializer == null ? Array.Empty() : new[] { t.TypeInitializer })) + .Distinct().Select(m => new Body(m, ReadOperands(m))).ToList(); + } + + [Test] + public void ProductionRedisCalls_UseOnlyAuditedRedis60Overloads() + { + var calls = ProductionBodies().SelectMany(b => b.Operands + .Where(o => IsCommandApi(o.Method)).Select(o => new { Caller = b.Method, Target = o.Method! })).ToList(); + + calls.Should().NotBeEmpty(); + calls.Where(c => !IsAuditedApi(c.Target)) + .Select(c => c.Caller.DeclaringType + "." + c.Caller.Name + ": " + Signature(c.Target.Name, c.Target.GetParameters().Select(p => p.ParameterType).ToArray())) + .Should().BeEmpty(AuditRequired); + } + + [Test] + public void ProductionLuaCalls_UseOneAuditedConstantScriptPerMethod() + { + var bodies = ProductionBodies().Where(b => b.Operands.Any(o => + IsCommandApi(o.Method) && o.Method!.Name.StartsWith("ScriptEvaluate", StringComparison.Ordinal))).ToList(); + + bodies.Should().NotBeEmpty(); + foreach (var body in bodies) + { + body.Operands.Count(o => IsCommandApi(o.Method) && o.Method!.Name.StartsWith("ScriptEvaluate", StringComparison.Ordinal)) + .Should().Be(1, AuditRequired + ": " + body.Method); + var scripts = body.Operands.Where(o => o.Text?.Contains("redis.", StringComparison.Ordinal) == true).ToList(); + scripts.Should().ContainSingle(AuditRequired + ": " + body.Method); + IsAuditedScript(scripts.Single().Text!).Should().BeTrue(AuditRequired + ": " + body.Method); + } + } + + [Test] + public void RedLockEmbeddedScripts_MatchTheAuditedRedis60Scripts() + { + var assembly = typeof(RedLockNet.SERedis.RedLockFactory).Assembly; + var resources = assembly.GetManifestResourceNames().Where(n => n.EndsWith(".lua", StringComparison.Ordinal)).ToList(); + + resources.Should().BeEquivalentTo("RedLockNet.SERedis.Lua.Extend.lua", "RedLockNet.SERedis.Lua.Unlock.lua"); + foreach (var resource in resources) + { + using var reader = new StreamReader(assembly.GetManifestResourceStream(resource)!); + IsAuditedScript(reader.ReadToEnd()).Should().BeTrue(AuditRequired + ": " + resource); + } + } + + [Test] + public void RedisDependencies_MatchTheAuditedCommandMappings() + { + var path = Path.Combine(AppContext.BaseDirectory, typeof(Redis60CompatibilityTests).Assembly.GetName().Name + ".deps.json"); + using var document = JsonDocument.Parse(File.ReadAllText(path)); + var libraries = document.RootElement.GetProperty("libraries").EnumerateObject().Select(p => p.Name) + .Where(n => n.StartsWith("StackExchange.Redis/", StringComparison.Ordinal) || n.StartsWith("RedLock.net/", StringComparison.Ordinal)); + + libraries.Should().BeEquivalentTo(new[] { "StackExchange.Redis/2.10.1", "RedLock.net/2.3.2" }, AuditRequired); + } + + [TestCase(false)] + [TestCase(true)] + public async Task CacheSave_UsesRelativeTtlOnTheAuditedOverload(bool transactional) + { + var transaction = transactional ? A.Fake() : null; + var database = (IDatabaseAsync?)transaction ?? A.Fake(); + var redis = A.Fake(); + A.CallTo(() => redis.GetDatabase(transaction)).Returns(database); + var repository = new CacheRepository(redis); + var key = new CacheKey { EntityType = EntityType.Session, EntityId = "local-test", Value = "local-test-cache-key" }; + + var result = await repository.Save(key, "local-test-value", transaction, A.Fake()); + + var calls = Fake.GetCalls(database).ToList(); + calls.Should().ContainSingle(); + var call = calls.Single(); + IsAuditedApi(call.Method).Should().BeTrue(); + call.Arguments.Get(0).Should().Be((RedisKey)key.Value); + call.Arguments.Get(2).Should().Be(TimeSpan.FromDays(2)); + call.Arguments.Get(3).Should().Be(When.Always); + result.IsWaitingForTransaction.Should().Be(transactional); + result.IsSaved.Should().Be(!transactional); + } + + [TestCase("StringGetDeleteAsync")] + [TestCase("StringSetAndGetAsync")] + [TestCase("KeyCopyAsync")] + [TestCase("KeyExpireTimeAsync")] + [TestCase("ScriptEvaluateReadOnlyAsync")] + [TestCase("ExecuteAsync")] + public void Guard_RejectsUnauditedRedisApisAndRawCommandDispatch(string methodName) + { + var methods = CommandInterfaces.SelectMany(t => t.GetMethods()).Where(m => m.Name == methodName) + .Where(m => methodName != "ExecuteAsync" || m.GetParameters().FirstOrDefault()?.ParameterType == typeof(string)).ToList(); + + methods.Should().NotBeEmpty(); + methods.Should().OnlyContain(m => !IsAuditedApi(m)); + } + + [Test] + public void Guard_RejectsSetOverloadsAllowingAbsoluteExpiryAndNewValueConditions() + { + var methods = typeof(IDatabaseAsync).GetMethods().Where(m => m.Name == "StringSetAsync" && + m.GetParameters().Any(p => p.ParameterType == typeof(Expiration))).ToList(); + + methods.Should().NotBeEmpty(); + methods.Should().OnlyContain(m => !IsAuditedApi(m)); + } + + [TestCase("return redis.call('GETDEL', KEYS[1])")] + [TestCase("return redis.call('GETEX', KEYS[1], 'EX', 60)")] + [TestCase("return redis.call('SET', KEYS[1], ARGV[1], 'GET')")] + [TestCase("return redis.call('SET', KEYS[1], ARGV[1], 'EXAT', ARGV[2])")] + [TestCase("return redis.call(ARGV[1], KEYS[1])")] + public void Guard_RequiresReauditForChangedLuaIncludingNewCommandsAndOptions(string script) + { + IsAuditedScript(script).Should().BeFalse(); + } + + [Test] + public void Guard_DetectsAnIncompatibleCallInsideCompiledCode() + { + var method = typeof(Redis60CompatibilityTests).GetMethod(nameof(IncompatibleCall), BindingFlags.Static | BindingFlags.NonPublic)!; + var calls = ReadOperands(method).Where(o => IsCommandApi(o.Method)).ToList(); + + calls.Should().ContainSingle(); + calls.Single().Method!.Name.Should().Be("StringGetDeleteAsync"); + IsAuditedApi(calls.Single().Method!).Should().BeFalse(); + } + + private static Task IncompatibleCall(IDatabaseAsync database) => database.StringGetDeleteAsync("unused-test-key"); + + private static bool IsCommandApi(MethodBase? method) => method?.DeclaringType != null && CommandInterfaces.Contains(method.DeclaringType); + private static bool IsAuditedApi(MethodBase method) => AuditedApis.Contains(Signature(method.Name, method.GetParameters().Select(p => p.ParameterType).ToArray())); + private static string Signature(string name, params Type[] parameters) => name + "(" + string.Join(",", parameters.Select(t => t.FullName)) + ")"; + private static bool IsAuditedScript(string text) => AuditedScripts.Contains(Convert.ToHexString( + SHA256.HashData(Encoding.UTF8.GetBytes(text.ReplaceLineEndings("\n").Trim())))); + + private static List ReadOperands(MethodBase method) + { + var bytes = method.GetMethodBody()?.GetILAsByteArray(); + var result = new List(); + if (bytes == null) return result; + for (var offset = 0; offset < bytes.Length;) + { + var first = bytes[offset++]; + var code = OpCodesByValue[first == 0xfe ? unchecked((short)(0xfe00 | bytes[offset++])) : first]; + if (code.OperandType == OperandType.InlineMethod) + result.Add(new Operand(method.Module.ResolveMethod(BitConverter.ToInt32(bytes, offset), + method.DeclaringType?.GetGenericArguments(), (method as MethodInfo)?.GetGenericArguments()))); + else if (code.OperandType == OperandType.InlineString) + result.Add(new Operand(Text: method.Module.ResolveString(BitConverter.ToInt32(bytes, offset)))); + offset += code.OperandType switch + { + OperandType.InlineNone => 0, + OperandType.ShortInlineBrTarget or OperandType.ShortInlineI or OperandType.ShortInlineVar => 1, + OperandType.InlineVar => 2, + OperandType.InlineBrTarget or OperandType.InlineField or OperandType.InlineI or OperandType.InlineMethod or + OperandType.InlineSig or OperandType.InlineString or OperandType.InlineTok or OperandType.InlineType or OperandType.ShortInlineR => 4, + OperandType.InlineI8 or OperandType.InlineR => 8, + OperandType.InlineSwitch => 4 + 4 * BitConverter.ToInt32(bytes, offset), + _ => throw new InvalidOperationException("Unsupported IL operand in " + method) + }; + } + return result; + } +} From 099ce751b1f6c2bf1548cb3e790f5276ad8f88df Mon Sep 17 00:00:00 2001 From: Paul Fresquet Date: Fri, 13 Nov 2026 22:22:47 +0100 Subject: [PATCH 4/8] [fix] Stop reconnecting when relay challenge endpoint is unavailable --- docs/security-boundaries.md | 4 + .../Assets/Resources/Resources.en.resx | 6 + .../Assets/Resources/Resources.fr.resx | 6 + .../Assets/Resources/Resources.resx | 6 + .../Communications/ConnectionStatuses.cs | 3 +- .../Exceptions/RelayIncompatibleException.cs | 10 ++ .../Services/Communications/Api/ApiInvoker.cs | 13 +- .../Communications/Api/AuthApiClient.cs | 35 ++++- .../Communications/ConnectionService.cs | 65 +++++--- .../Headers/ConnectionStatusViewModel.cs | 11 +- .../Views/Headers/ConnectionStatusView.axaml | 3 +- .../Communications/Api/ApiInvokerTests.cs | 147 ++++++++++++++++++ .../Communications/ConnectionServiceTests.cs | 53 ++++++- .../AuthProtocolCompatibilityTests.cs | 100 +++++++++++- .../Headers/ConnectionStatusViewModelTests.cs | 97 ++++++++++++ 15 files changed, 520 insertions(+), 39 deletions(-) create mode 100644 src/ByteSync.Client/Exceptions/RelayIncompatibleException.cs create mode 100644 tests/ByteSync.Client.UnitTests/Services/Communications/Api/ApiInvokerTests.cs create mode 100644 tests/ByteSync.Client.UnitTests/ViewModels/Headers/ConnectionStatusViewModelTests.cs diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md index ebda74ed1..d9485a268 100644 --- a/docs/security-boundaries.md +++ b/docs/security-boundaries.md @@ -165,6 +165,10 @@ Validation: solution build succeeded with zero errors (17 warnings). **1,742 tes The supplied client log shows a 404 for `auth/challenge` while targeting the remote development API, before SignalR negotiation or any peer exchange. The source before this branch has no challenge endpoint. An old relay or a deployment missing that route therefore cannot authenticate this client. The deployed server version was not probed; this diagnosis uses the supplied log and local source only. +An HTTP 404 from `auth/challenge` now stops automatic reconnection after the first request. The client shows "Incompatible relay server" ("Serveur relais incompatible" in French), with details asking the user to check the relay address or update the relay server. The diagnostic log names the missing route and HTTP status. This applies to empty, HTML and JSON error responses, without attempting login, storing tokens or opening SignalR. Other HTTP and network errors retain their existing retry behavior; a 404 from `auth/login` is not classified as a missing challenge route. An explicit new connection attempt remains possible after correcting the relay. This message concerns the relay; an older V2 peer separately requires a client update. + +Offline validation of this error handling: solution build succeeded with zero errors; all 1,272 client unit tests passed, including 36 added cases. Twelve existing POSIX-only cases did not execute on Windows. Line coverage was 93.75% for `ApiInvoker`, 96.25% for `ConnectionStatusViewModel`, and 100% for `AuthApiClient` and `RelayIncompatibleException`. HTTP responses were supplied by in-process handlers; no Azure endpoint was contacted and Docker was not started. Evidence is under `artifacts/security-boundaries/relay-error/client/`. + V3 clients require the matching relay and V3 peers. An older V2 peer is explicitly incompatible, and an older relay cannot provide the required possession proof. Regression tests assert that a missing challenge endpoint fails without calling the legacy login; a supported relay receives a valid RSA-PSS proof with the current epoch/protocol; refresh has no login fallback; and V2 remains rejected. The secure protocol is not downgraded to restore legacy connectivity. For local Rider testing, run the Functions project built from this branch and launch the client in Debug with `--use-local-api`. Check the client's `LocalDebugUrl` matches the Functions host's actual port and `/api/` base path, then confirm the client log selects that local URL. Debug defaults to the remote DevelopmentUrl when no API-selection argument is supplied. The local-API switch applies to Debug execution; Release uses ProductionUrl (or its existing staging override). Run all session peers from the same V3 branch and create a fresh session. Coordinated remote deployment remains a separate, unexecuted operation. diff --git a/src/ByteSync.Client/Assets/Resources/Resources.en.resx b/src/ByteSync.Client/Assets/Resources/Resources.en.resx index 722f831f8..398dd826e 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.en.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.en.resx @@ -39,4 +39,10 @@ You must select at least 2 data nodes. Local Inventory not launched + + Incompatible relay server + + + The relay server does not provide the secure authentication required by this client. Check the relay address or update the relay server. Automatic reconnection has stopped. + diff --git a/src/ByteSync.Client/Assets/Resources/Resources.fr.resx b/src/ByteSync.Client/Assets/Resources/Resources.fr.resx index bb2186922..7d9f43063 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.fr.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.fr.resx @@ -1831,5 +1831,11 @@ Voulez-vous enregistrer ce nouveau Profil de Session avec ce nom ? ANNULER + + Serveur relais incompatible + + + Le serveur relais ne fournit pas l’authentification sécurisée requise par ce client. Vérifiez l’adresse du relais ou mettez à jour le serveur. La reconnexion automatique est arrêtée. + diff --git a/src/ByteSync.Client/Assets/Resources/Resources.resx b/src/ByteSync.Client/Assets/Resources/Resources.resx index 69dc16029..56fec3338 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.resx @@ -1856,4 +1856,10 @@ Do you want to save this new Session Profile with this name? CANCEL + + Incompatible relay server + + + The relay server does not provide the secure authentication required by this client. Check the relay address or update the relay server. Automatic reconnection has stopped. + diff --git a/src/ByteSync.Client/Business/Communications/ConnectionStatuses.cs b/src/ByteSync.Client/Business/Communications/ConnectionStatuses.cs index d914b9a4c..8bc059aee 100644 --- a/src/ByteSync.Client/Business/Communications/ConnectionStatuses.cs +++ b/src/ByteSync.Client/Business/Communications/ConnectionStatuses.cs @@ -7,4 +7,5 @@ public enum ConnectionStatuses Connected = 2, RetryConnectingSoon = 3, ConnectionFailed = 4, -} \ No newline at end of file + RelayIncompatible = 5, +} diff --git a/src/ByteSync.Client/Exceptions/RelayIncompatibleException.cs b/src/ByteSync.Client/Exceptions/RelayIncompatibleException.cs new file mode 100644 index 000000000..3b2afc7c6 --- /dev/null +++ b/src/ByteSync.Client/Exceptions/RelayIncompatibleException.cs @@ -0,0 +1,10 @@ +namespace ByteSync.Exceptions; + +public sealed class RelayIncompatibleException : BuildConnectionException +{ + public RelayIncompatibleException(Exception innerException) + : base("The relay returned HTTP 404 for auth/challenge, which is required for this client's secure authentication. " + + "Check the relay address or update the relay server. Automatic reconnection has stopped.", innerException) + { + } +} diff --git a/src/ByteSync.Client/Services/Communications/Api/ApiInvoker.cs b/src/ByteSync.Client/Services/Communications/Api/ApiInvoker.cs index e272887b2..0b244e287 100644 --- a/src/ByteSync.Client/Services/Communications/Api/ApiInvoker.cs +++ b/src/ByteSync.Client/Services/Communications/Api/ApiInvoker.cs @@ -58,16 +58,21 @@ private async Task DoInvokeRestAsync(HttpMethod httpMethod, string resourc object? requestObject, bool handleResult, CancellationToken cancellationToken) { using var request = await BuildRequest(httpMethod, resource, additionalHeaders, requestObject); + HttpStatusCode? responseStatusCode = null; try { - var response = await _httpClient.SendAsync(request, cancellationToken); + using var response = await _httpClient.SendAsync(request, cancellationToken); + responseStatusCode = response.StatusCode; return await HandleResponse(handleResult, response); } catch (Exception ex) { _logger.LogError(ex, "Exception occurred while invoking API: {Resource}", resource); - throw new ApiException($"An error occurred while invoking the API on resource {resource}", ex); + throw new ApiException($"An error occurred while invoking the API on resource {resource}", ex) + { + HttpStatusCode = responseStatusCode ?? (ex as ApiException)?.HttpStatusCode + }; } } @@ -124,7 +129,7 @@ private async Task HandleResponse(bool handleResult, HttpResponseMessage r errorMessage += $" Reason: {response.ReasonPhrase}"; } - if (!ApiResponseContentHelper.IsEmptyContent(content) && handleResult) + if (response.StatusCode != HttpStatusCode.NotFound && !ApiResponseContentHelper.IsEmptyContent(content) && handleResult) { return DeserializeContent(content); } @@ -152,4 +157,4 @@ private T DeserializeContent(string content) throw new ApiException("Failed to deserialize the response content.", ex); } } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs b/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs index 46356eba9..cfece7661 100644 --- a/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs +++ b/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs @@ -1,9 +1,11 @@ +using System.Net; using System.Runtime.CompilerServices; using System.Security.Cryptography; using ByteSync.Interfaces; using ByteSync.Common.Business.Versions; using System.Threading.Tasks; using ByteSync.Common.Business.Auth; +using ByteSync.Exceptions; using ByteSync.Interfaces.Controls.Communications.Http; using Serilog; @@ -30,8 +32,7 @@ public AuthApiClient(IApiInvoker apiInvoker, IApplicationSettingsRepository sett loginData.Identity = AuthenticationProtocol.GetIdentity(loginData.PublicKey); loginData.AuthenticationEpoch = AuthenticationProtocol.Epoch; loginData.ProtocolVersion = ProtocolVersion.CURRENT; - var challenge = await _apiInvoker.PostAsync("auth/challenge", loginData) - ?? throw new CryptographicException("Missing authentication challenge"); + var challenge = await GetChallenge(loginData); loginData.ChallengeId = challenge.Id; loginData.Signature = settings.PrivateRsa.SignData(AuthenticationProtocol.GetMessage(loginData, challenge), HashAlgorithmName.SHA256, RSASignaturePadding.Pss); @@ -47,6 +48,34 @@ public AuthApiClient(IApiInvoker apiInvoker, IApplicationSettingsRepository sett } } + private async Task GetChallenge(LoginData loginData) + { + try + { + return await _apiInvoker.PostAsync("auth/challenge", loginData) + ?? throw new CryptographicException("Missing authentication challenge"); + } + catch (ApiException ex) when (IsNotFound(ex)) + { + throw new RelayIncompatibleException(ex); + } + } + + private static bool IsNotFound(Exception? exception) + { + while (exception != null) + { + if (exception is ApiException { HttpStatusCode: HttpStatusCode.NotFound }) + { + return true; + } + + exception = exception.InnerException; + } + + return false; + } + public async Task RefreshAuthenticationTokens(RefreshTokensData refreshTokensData) { try @@ -68,4 +97,4 @@ private void LogError(Exception exception, [CallerMemberName] string caller = "" // ReSharper disable once TemplateIsNotCompileTimeConstantProblem Log.Error(exception, caller); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Services/Communications/ConnectionService.cs b/src/ByteSync.Client/Services/Communications/ConnectionService.cs index 7b2a9900f..04b8ee08f 100644 --- a/src/ByteSync.Client/Services/Communications/ConnectionService.cs +++ b/src/ByteSync.Client/Services/Communications/ConnectionService.cs @@ -73,7 +73,8 @@ public async Task StartConnectionAsync() var retryDelaySleepDurationProvider = RetryDelaySleepDurationProvider; var retryPolicy = Policy - .Handle(ex => !(ex is BuildConnectionException bce && bce.InitialConnectionStatus is InitialConnectionStatus.VersionNotAllowed or InitialConnectionStatus.InvalidProof)) + .Handle(ex => ex is not RelayIncompatibleException && + !(ex is BuildConnectionException bce && bce.InitialConnectionStatus is InitialConnectionStatus.VersionNotAllowed or InitialConnectionStatus.InvalidProof)) .WaitAndRetryForeverAsync( retryAttempt => retryDelaySleepDurationProvider?.Invoke(retryAttempt) ?? TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (exception, _, _) => @@ -83,35 +84,46 @@ public async Task StartConnectionAsync() _logger.LogError(exception, "An error occurred while starting the connection"); }); - - await retryPolicy.ExecuteAsync(async () => + + try { - _logger.LogInformation("Starting connection"); + await retryPolicy.ExecuteAsync(async () => + { + _logger.LogInformation("Starting connection"); - ConnectionStatusSubject.OnNext(ConnectionStatuses.Connecting); + ConnectionStatusSubject.OnNext(ConnectionStatuses.Connecting); - var result = await _connectionFactory.BuildConnection(); - - ConnectionSubject.OnNext(result.HubConnection); - - if (result.HubConnection != null) - { - CurrentEndPoint = result.EndPoint!; - - ConnectionStatusSubject.OnNext(ConnectionStatuses.Connected); - } - else - { - if (result.AuthenticateResponseStatus is InitialConnectionStatus.VersionNotAllowed or InitialConnectionStatus.InvalidProof) + var result = await _connectionFactory.BuildConnection(); + + ConnectionSubject.OnNext(result.HubConnection); + + if (result.HubConnection != null) { - ConnectionStatusSubject.OnNext(ConnectionStatuses.NotConnected); + CurrentEndPoint = result.EndPoint!; + + ConnectionStatusSubject.OnNext(ConnectionStatuses.Connected); } - - throw new BuildConnectionException("Unable to connect", result.AuthenticateResponseStatus); - } - }); + else + { + if (result.AuthenticateResponseStatus is InitialConnectionStatus.VersionNotAllowed or InitialConnectionStatus.InvalidProof) + { + ConnectionStatusSubject.OnNext(ConnectionStatuses.NotConnected); + } + + throw new BuildConnectionException("Unable to connect", result.AuthenticateResponseStatus); + } + }); + } + catch (RelayIncompatibleException ex) + { + await StopConnection(); + CurrentEndPoint = null; + ConnectionStatusSubject.OnNext(ConnectionStatuses.RelayIncompatible); + _logger.LogError(ex, "{RelayCompatibilityError}", ex.Message); + throw; + } } - + private async Task StartOrRestartJwtTokensRefreshTimer() { await CancelCurrentRefreshCancellationTokenSource(); @@ -216,6 +228,11 @@ public void Dispose() private async Task RestartConnection() { + if (CurrentConnectionStatus == ConnectionStatuses.RelayIncompatible) + { + return; + } + await StopConnection(); await StartConnectionAsync(); } diff --git a/src/ByteSync.Client/ViewModels/Headers/ConnectionStatusViewModel.cs b/src/ByteSync.Client/ViewModels/Headers/ConnectionStatusViewModel.cs index 67d7e0943..e0c1e66d3 100644 --- a/src/ByteSync.Client/ViewModels/Headers/ConnectionStatusViewModel.cs +++ b/src/ByteSync.Client/ViewModels/Headers/ConnectionStatusViewModel.cs @@ -82,6 +82,7 @@ private void SetBrush() ConnectionStatuses.Connected => ConnectedBadgeBrush, ConnectionStatuses.Connecting => ConnectingBadgeBrush, ConnectionStatuses.ConnectionFailed => ConnectionFailedBadgeBrush, + ConnectionStatuses.RelayIncompatible => ConnectionFailedBadgeBrush, ConnectionStatuses.NotConnected => NotConnectedBadgeBrush, ConnectionStatuses.RetryConnectingSoon => RetryConnectingSoonBadgeBrush, _ => UnknownBadgeBrush @@ -109,15 +110,23 @@ private void SetText() ConnectionStatuses.Connected => _localizationService[nameof(Resources.ConnectionStatus_Connected)], ConnectionStatuses.Connecting => _localizationService[nameof(Resources.ConnectionStatus_Connecting)], ConnectionStatuses.ConnectionFailed => _localizationService[nameof(Resources.ConnectionStatus_ConnectionFailed)], + ConnectionStatuses.RelayIncompatible => _localizationService["ConnectionStatus_RelayIncompatible"], ConnectionStatuses.NotConnected => _localizationService[nameof(Resources.ConnectionStatus_NotConnected)], ConnectionStatuses.RetryConnectingSoon => _localizationService[nameof(Resources.ConnectionStatus_RetryConnectingSoon)], _ => _localizationService[nameof(Resources.ConnectionStatus_Unkown)] }; + + Details = connectionStatus == ConnectionStatuses.RelayIncompatible + ? _localizationService["ConnectionStatus_RelayIncompatibleDetails"] + : null; } [Reactive] public string Text { get; set; } + + [Reactive] + public string? Details { get; set; } [Reactive] public IBrush BadgeBrush { get; set; } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Views/Headers/ConnectionStatusView.axaml b/src/ByteSync.Client/Views/Headers/ConnectionStatusView.axaml index 7ea5afcc6..92292763c 100644 --- a/src/ByteSync.Client/Views/Headers/ConnectionStatusView.axaml +++ b/src/ByteSync.Client/Views/Headers/ConnectionStatusView.axaml @@ -12,7 +12,8 @@ - + diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/Api/ApiInvokerTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/Api/ApiInvokerTests.cs new file mode 100644 index 000000000..2365e1dfd --- /dev/null +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/Api/ApiInvokerTests.cs @@ -0,0 +1,147 @@ +using System.Net; +using System.Net.Http; +using ByteSync.Common.Business.Auth; +using ByteSync.Exceptions; +using ByteSync.Interfaces.Services.Communications; +using ByteSync.Services.Communications.Api; +using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using NUnit.Framework; + +namespace ByteSync.Client.UnitTests.Services.Communications.Api; + +public class ApiInvokerTests +{ + private Mock _tokens = null!; + private HttpClient _httpClient = null!; + private Func> _send = null!; + private ApiInvoker _api = null!; + + [SetUp] + public void SetUp() + { + _tokens = new Mock(); + _httpClient = new HttpClient(new StubHttpHandler((request, token) => _send(request, token))); + var factory = new Mock(); + factory.Setup(f => f.CreateClient("ApiClient")).Returns(_httpClient); + var constants = new Mock(); + constants.Setup(c => c.GetApiUrl()).ReturnsAsync("https://relay.invalid/api/"); + _api = new ApiInvoker(factory.Object, _tokens.Object, constants.Object, NullLogger.Instance); + } + + [TearDown] + public void TearDown() => _httpClient.Dispose(); + + [TestCase("")] + [TestCase("Not Found")] + [TestCase("{\"error\":\"Not Found\"}")] + public async Task NotFound_PreservesStatusRegardlessOfResponseBody(string body) + { + _send = (_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(body) }); + + var act = () => _api.PostAsync("auth/challenge", new LoginData()); + + var error = (await act.Should().ThrowAsync()).Which; + error.HttpStatusCode.Should().Be(HttpStatusCode.NotFound); + error.Message.Should().Contain("auth/challenge"); + } + + [TestCase("")] + [TestCase("Unavailable")] + public async Task ServerFailure_PreservesStatusWhenResponseCannotBeDeserialized(string body) + { + _send = (_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new StringContent(body) }); + + var act = () => _api.GetAsync("auth/challenge"); + + (await act.Should().ThrowAsync()).Which.HttpStatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + } + + [Test] + public async Task NetworkFailure_PreservesCauseWithoutInventingAnHttpStatus() + { + var failure = new HttpRequestException("Connection failed"); + _send = (_, _) => throw failure; + + var act = () => _api.PostAsync("auth/challenge", new LoginData()); + + var error = (await act.Should().ThrowAsync()).Which; + error.HttpStatusCode.Should().BeNull(); + error.InnerException.Should().BeSameAs(failure); + } + + [TestCase("GET")] + [TestCase("POST")] + [TestCase("DELETE")] + public async Task SuccessfulRequest_PreservesTypedResponseAndRequest(string method) + { + _tokens.Setup(t => t.GetTokens()).ReturnsAsync(new AuthenticationTokens { JwtToken = "local-test-token" }); + _send = async (request, token) => + { + request.Method.Method.Should().Be(method); + request.RequestUri!.AbsoluteUri.Should().Be("https://relay.invalid/api/test"); + request.Headers.GetValues("authorization").Should().Equal("local-test-token"); + token.CanBeCanceled.Should().BeTrue(); + if (method == "GET") + { + request.Content.Should().BeNull(); + } + else + { + (await request.Content!.ReadAsStringAsync(token)).Should().Contain("request"); + } + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"Id\":\"challenge\"}") }; + }; + using var cancellation = new CancellationTokenSource(); + + var result = method switch + { + "GET" => await _api.GetAsync("test", cancellation.Token), + "POST" => await _api.PostAsync("test", new AuthenticationChallenge { Id = "request" }, cancellation.Token), + _ => await _api.DeleteAsync("test", new AuthenticationChallenge { Id = "request" }, cancellation.Token) + }; + + result.Id.Should().Be("challenge"); + } + + [Test] + public async Task BusinessErrorResponse_RemainsDeserializable() + { + _send = (_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized) + { + Content = new StringContent("{\"InitialConnectionStatus\":\"InvalidProof\"}") + }); + + var response = await _api.PostAsync("auth/login", new LoginData()); + + response.InitialConnectionStatus.Should().Be(InitialConnectionStatus.InvalidProof); + } + + [Test] + public async Task PostWithoutResponse_DoesNotRequireJson() + { + _send = (_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent)); + + var act = () => _api.PostAsync("test", null); + + await act.Should().NotThrowAsync(); + } + + [TestCase("")] + [TestCase("null")] + [TestCase("Invalid JSON")] + public async Task InvalidSuccessfulResponse_IsRejected(string body) + { + _send = (_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) }); + + var act = () => _api.GetAsync("test"); + + await act.Should().ThrowAsync(); + } + + private sealed class StubHttpHandler(Func> send) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => send(request, cancellationToken); + } +} diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/ConnectionServiceTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/ConnectionServiceTests.cs index 7b7664d97..317c38fde 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Communications/ConnectionServiceTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/ConnectionServiceTests.cs @@ -36,6 +36,57 @@ public void SetUp() _connectionService.RetryDelaySleepDurationProvider = _ => TimeSpan.Zero; } + + [TearDown] + public void TearDown() => _connectionService.Dispose(); + + [Test] + public async Task MissingChallengeEndpoint_ClearsConnectionAndPublishesTerminalStatusWithoutRetrying() + { + var error = new RelayIncompatibleException(new ApiException("Not Found", System.Net.HttpStatusCode.NotFound)); + _mockConnectionFactory.SetupSequence(f => f.BuildConnection()) + .ThrowsAsync(error) + .ThrowsAsync(new BuildConnectionException("Unexpected retry", InitialConnectionStatus.VersionNotAllowed)); + _connectionService.CurrentEndPoint = new ByteSyncEndpoint { ClientId = "stale", ClientInstanceId = "stale" }; + var statuses = new List(); + using var subscription = _connectionService.ConnectionStatus.Subscribe(statuses.Add); + Microsoft.AspNetCore.SignalR.Client.HubConnection? currentConnection = null; + using var connectionSubscription = _connectionService.Connection.Subscribe(c => currentConnection = c); + + var act = () => _connectionService.StartConnectionAsync(); + + (await act.Should().ThrowAsync()).Which.Should().BeSameAs(error); + _mockConnectionFactory.Verify(f => f.BuildConnection(), Times.Once); + statuses.Should().Equal(ConnectionStatuses.NotConnected, ConnectionStatuses.Connecting, + ConnectionStatuses.NotConnected, ConnectionStatuses.RelayIncompatible); + _connectionService.CurrentEndPoint.Should().BeNull(); + _connectionService.ClientInstanceId.Should().BeNull(); + currentConnection.Should().BeNull(); + _mockLogger.Verify(l => l.Log(LogLevel.Error, It.IsAny(), + It.Is((state, _) => state.ToString()!.Contains("auth/challenge") && state.ToString()!.Contains("Automatic reconnection has stopped")), + error, It.IsAny>()), Times.Once); + } + + [Test] + public async Task ManualStartAfterRelayUpgrade_CanConnectAgain() + { + _mockAuthenticationTokensRepository.Setup(r => r.GetTokens()).ReturnsAsync((AuthenticationTokens?)null); + _mockConnectionFactory.SetupSequence(f => f.BuildConnection()) + .ThrowsAsync(new RelayIncompatibleException(new ApiException("Not Found"))) + .ReturnsAsync(new BuildConnectionResult + { + HubConnection = new TestableHubConnection(), + EndPoint = new ByteSyncEndpoint { ClientId = "compatible", ClientInstanceId = "compatible" } + }); + var initialStart = () => _connectionService.StartConnectionAsync(); + await initialStart.Should().ThrowAsync(); + + await _connectionService.StartConnectionAsync(); + + _connectionService.CurrentConnectionStatus.Should().Be(ConnectionStatuses.Connected); + _connectionService.ClientInstanceId.Should().Be("compatible"); + _mockConnectionFactory.Verify(f => f.BuildConnection(), Times.Exactly(2)); + } [Test] public async Task StartConnectionAsync_ShouldRetryOnException_ExceptVersionNotAllowed() @@ -117,4 +168,4 @@ await FluentActions.Invoking(async () => await _connectionService.StartConnectio attemptCount.Should().Be(1, "The system should not retry with an exception VersionNotAllowed"); } -} \ No newline at end of file +} diff --git a/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs b/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs index 0c8f0e8f0..4237badba 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs @@ -1,13 +1,21 @@ using System.Net; +using System.Net.Http; using System.Security.Cryptography; using ByteSync.Business.Configurations; +using ByteSync.Business.Communications; using ByteSync.Common.Business.Auth; using ByteSync.Common.Business.Versions; using ByteSync.Exceptions; +using ByteSync.Factories; using ByteSync.Interfaces; +using ByteSync.Interfaces.Controls.Applications; using ByteSync.Interfaces.Controls.Communications.Http; +using ByteSync.Interfaces.Factories; +using ByteSync.Interfaces.Services.Communications; +using ByteSync.Services.Communications; using ByteSync.Services.Communications.Api; using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; using Moq; using NUnit.Framework; @@ -34,21 +42,94 @@ public void SetUp() [TearDown] public void TearDown() => _settings.PrivateRsa.Dispose(); - [Test] - public async Task OlderRelayWithoutChallengeEndpoint_IsRejectedWithoutCallingLegacyLogin() + [TestCase(false)] + [TestCase(true)] + public async Task OlderRelayWithoutChallengeEndpoint_IsRejectedWithoutCallingLegacyLogin(bool wrapped) { - var error = new ApiException("Challenge request failed", new ApiException("Not Found", HttpStatusCode.NotFound)); + var notFound = new ApiException("Not Found", HttpStatusCode.NotFound); + var error = wrapped ? new ApiException("Challenge request failed", notFound) : notFound; _api.Setup(a => a.PostAsync("auth/challenge", It.IsAny(), It.IsAny())) .ThrowsAsync(error); var act = () => _client.Login(new LoginData()); - (await act.Should().ThrowAsync()).Which.Should().BeSameAs(error); + var exception = (await act.Should().ThrowAsync()).Which; + exception.InnerException.Should().BeSameAs(error); + exception.Message.Should().Contain("auth/challenge").And.Contain("HTTP 404") + .And.Contain("Check the relay address").And.Contain("update the relay server").And.Contain("Automatic reconnection has stopped"); _api.Verify(a => a.PostAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); _api.Verify(a => a.PostAsync("auth/challenge", It.IsAny(), It.IsAny()), Times.Once); _api.VerifyNoOtherCalls(); } + [TestCase("")] + [TestCase("Not Found")] + [TestCase("{\"message\":\"Not Found\"}")] + [TestCase("{\"Id\":\"unexpected-challenge\",\"Nonce\":\"unexpected-nonce\"}")] + public async Task MissingChallengeEndpoint_StopsConnectionAfterOneHttpRequest(string body) + { + using var handler = new MissingChallengeHandler(body); + using var httpClient = new HttpClient(handler); + var httpClientFactory = new Mock(); + httpClientFactory.Setup(f => f.CreateClient("ApiClient")).Returns(httpClient); + var tokens = new Mock(MockBehavior.Strict); + tokens.Setup(t => t.GetTokens()).ReturnsAsync((AuthenticationTokens?)null); + var constants = new Mock(); + constants.Setup(c => c.GetApiUrl()).ReturnsAsync("https://relay.invalid/api/"); + var api = new ApiInvoker(httpClientFactory.Object, tokens.Object, constants.Object, NullLogger.Instance); + var settings = new Mock(); + settings.Setup(s => s.GetCurrentApplicationSettings()).Returns(_settings); + var auth = new AuthApiClient(api, settings.Object); + var environment = new Mock(); + environment.SetupGet(e => e.ApplicationVersion).Returns(new Version(1, 0, 0)); + var hubFactory = new Mock(MockBehavior.Strict); + var factory = new ConnectionFactory(tokens.Object, environment.Object, auth, hubFactory.Object, NullLogger.Instance); + using var connection = new ConnectionService(factory, tokens.Object, NullLogger.Instance) + { + RetryDelaySleepDurationProvider = _ => throw new InvalidOperationException("Unexpected reconnection attempt") + }; + + var act = () => connection.StartConnectionAsync(); + + await act.Should().ThrowAsync(); + connection.CurrentConnectionStatus.Should().Be(ConnectionStatuses.RelayIncompatible); + handler.Requests.Should().Equal("/api/auth/challenge"); + tokens.Verify(t => t.Store(It.IsAny()), Times.Never); + hubFactory.VerifyNoOtherCalls(); + } + + [TestCase(HttpStatusCode.BadRequest)] + [TestCase(HttpStatusCode.Unauthorized)] + [TestCase(HttpStatusCode.InternalServerError)] + [TestCase(HttpStatusCode.ServiceUnavailable)] + public async Task OtherChallengeFailures_KeepTheirOriginalErrorWithoutCallingLogin(HttpStatusCode status) + { + var error = new ApiException("Challenge request failed", status); + _api.Setup(a => a.PostAsync("auth/challenge", It.IsAny(), It.IsAny())) + .ThrowsAsync(error); + + var act = () => _client.Login(new LoginData()); + + (await act.Should().ThrowAsync()).Which.Should().BeSameAs(error); + _api.Verify(a => a.PostAsync("auth/challenge", It.IsAny(), It.IsAny()), Times.Once); + _api.VerifyNoOtherCalls(); + } + + [Test] + public async Task LoginEndpointNotFound_IsNotReportedAsAMissingChallengeEndpoint() + { + var error = new ApiException("Login not found", HttpStatusCode.NotFound); + _api.Setup(a => a.PostAsync("auth/challenge", It.IsAny(), It.IsAny())) + .ReturnsAsync(new AuthenticationChallenge { Id = "challenge", Nonce = "nonce" }); + _api.Setup(a => a.PostAsync("auth/login", It.IsAny(), It.IsAny())) + .ThrowsAsync(error); + + var act = () => _client.Login(new LoginData { ClientInstanceId = "local-test-instance", Version = "local-test" }); + + (await act.Should().ThrowAsync()).Which.Should().BeSameAs(error); + _api.Verify(a => a.PostAsync("auth/login", It.IsAny(), It.IsAny()), Times.Once); + } + [Test] public async Task CurrentRelay_ReceivesAValidProofWithTheCurrentEpochAndProtocol() { @@ -98,4 +179,15 @@ public async Task RefreshFailure_DoesNotFallBackToLogin() _api.Verify(a => a.PostAsync("auth/refreshTokens", It.IsAny(), It.IsAny()), Times.Once); _api.VerifyNoOtherCalls(); } + + private sealed class MissingChallengeHandler(string body) : HttpMessageHandler + { + public List Requests { get; } = []; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request.RequestUri!.AbsolutePath); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(body) }); + } + } } diff --git a/tests/ByteSync.Client.UnitTests/ViewModels/Headers/ConnectionStatusViewModelTests.cs b/tests/ByteSync.Client.UnitTests/ViewModels/Headers/ConnectionStatusViewModelTests.cs new file mode 100644 index 000000000..e2571cb33 --- /dev/null +++ b/tests/ByteSync.Client.UnitTests/ViewModels/Headers/ConnectionStatusViewModelTests.cs @@ -0,0 +1,97 @@ +using System.Globalization; +using System.Reactive.Subjects; +using System.Resources; +using Avalonia.Media; +using ByteSync.Business; +using ByteSync.Business.Communications; +using ByteSync.Business.Themes; +using ByteSync.Interfaces.Controls.Themes; +using ByteSync.Interfaces.Services.Communications; +using ByteSync.Interfaces.Services.Localizations; +using ByteSync.ViewModels.Headers; +using FluentAssertions; +using Moq; +using NUnit.Framework; + +namespace ByteSync.Client.UnitTests.ViewModels.Headers; + +public class ConnectionStatusViewModelTests +{ + private static readonly ResourceManager Resources = new("ByteSync.Assets.Resources.Resources", typeof(ConnectionStatusViewModel).Assembly); + + [TestCase("fr", "Serveur relais incompatible", "La reconnexion automatique est arrêtée.")] + [TestCase("en", "Incompatible relay server", "Automatic reconnection has stopped.")] + [TestCase("", "Incompatible relay server", "Automatic reconnection has stopped.")] + public void MissingChallengeEndpoint_DisplaysLocalizedActionableError(string cultureName, string title, string details) + { + using var statuses = new BehaviorSubject(ConnectionStatuses.RelayIncompatible); + using var cultures = new BehaviorSubject(new(CultureInfo.GetCultureInfo(cultureName))); + using var themes = new BehaviorSubject(new("test", ThemeModes.Light, null!, null!)); + var viewModel = CreateViewModel(statuses, cultures, themes); + + using var activation = viewModel.Activator.Activate(); + + viewModel.Text.Should().Be(title); + viewModel.Details.Should().Contain(details); + viewModel.BadgeBrush.Should().BeSameAs(Brushes.Red); + } + + [TestCase(ConnectionStatuses.Connected, "ConnectionStatus_Connected")] + [TestCase(ConnectionStatuses.Connecting, "ConnectionStatus_Connecting")] + [TestCase(ConnectionStatuses.ConnectionFailed, "ConnectionStatus_ConnectionFailed")] + [TestCase(ConnectionStatuses.NotConnected, "ConnectionStatus_NotConnected")] + [TestCase(ConnectionStatuses.RetryConnectingSoon, "ConnectionStatus_RetryConnectingSoon")] + [TestCase((ConnectionStatuses)99, "ConnectionStatus_Unkown")] + public void StatusChange_ClearsRelayErrorDetails(ConnectionStatuses nextStatus, string textKey) + { + using var statuses = new BehaviorSubject(ConnectionStatuses.RelayIncompatible); + using var cultures = new BehaviorSubject(new(CultureInfo.GetCultureInfo("fr"))); + using var themes = new BehaviorSubject(new("test", ThemeModes.Light, null!, null!)); + var viewModel = CreateViewModel(statuses, cultures, themes); + using var activation = viewModel.Activator.Activate(); + + statuses.OnNext(nextStatus); + + viewModel.Text.Should().Be(Resources.GetString(textKey, cultures.Value.CultureInfo)); + viewModel.Details.Should().BeNull(); + viewModel.BadgeBrush.Should().BeSameAs(nextStatus switch + { + ConnectionStatuses.Connected => Brushes.Green, + ConnectionStatuses.Connecting => Brushes.Gray, + _ => Brushes.Red + }); + } + + [Test] + public void CultureChange_UpdatesTheVisibleRelayErrorAndDetails() + { + using var statuses = new BehaviorSubject(ConnectionStatuses.RelayIncompatible); + using var cultures = new BehaviorSubject(new(CultureInfo.GetCultureInfo("en"))); + using var themes = new BehaviorSubject(new("test", ThemeModes.Light, null!, null!)); + var viewModel = CreateViewModel(statuses, cultures, themes); + using var activation = viewModel.Activator.Activate(); + + cultures.OnNext(new CultureDefinition(CultureInfo.GetCultureInfo("fr"))); + + viewModel.Text.Should().Be("Serveur relais incompatible"); + viewModel.Details.Should().Contain("Vérifiez l’adresse du relais ou mettez à jour le serveur."); + } + + private static ConnectionStatusViewModel CreateViewModel(BehaviorSubject statuses, + BehaviorSubject cultures, BehaviorSubject themes) + { + var connection = new Mock(); + connection.SetupGet(c => c.ConnectionStatus).Returns(statuses); + connection.SetupGet(c => c.CurrentConnectionStatus).Returns(() => statuses.Value); + var localization = new Mock(); + localization.SetupGet(l => l.CurrentCultureObservable).Returns(cultures); + localization.Setup(l => l[It.IsAny()]) + .Returns((string key) => Resources.GetString(key, cultures.Value.CultureInfo)!); + var theme = new Mock(); + theme.SetupGet(t => t.SelectedTheme).Returns(themes); + theme.Setup(t => t.GetBrush("HomeCloudSynchronizationBackGround")).Returns(Brushes.Green); + theme.Setup(t => t.GetBrush("SystemControlForegroundBaseHighBrush")).Returns(Brushes.Gray); + theme.Setup(t => t.GetBrush("HomeLocalSynchronizationBackGround")).Returns(Brushes.Red); + return new ConnectionStatusViewModel(connection.Object, localization.Object, theme.Object); + } +} From 59179a01c47230110aa21fe2dab0c87a0b66c9d5 Mon Sep 17 00:00:00 2001 From: Paul Fresquet Date: Sat, 21 Nov 2026 09:52:27 +0100 Subject: [PATCH 5/8] [fix] Retry join notifications and migrate V3 integration fixtures [skip ci] --- docs/security-boundaries.md | 10 ++ .../Services/CloudSessionsService.cs | 13 +- ...ByteSync.Functions.IntegrationTests.csproj | 1 + .../End2End/E2E_Auth_Session_Tests.cs | 39 +++--- .../AuthenticateCommandHandler_Tests.cs | 37 +++-- .../Services/AzureBlobStorageService_Tests.cs | 22 ++- .../RefreshTokensCommandHandler_Tests.cs | 30 ++-- .../Security/AuthenticationSecurityTests.cs | 55 ++++++++ .../Security/JoinProofSecurityTests.cs | 132 ++++++++++++++++++ .../Security/StorageUrlScopeSecurityTests.cs | 16 ++- .../TestHelpers/AuthenticationTestIdentity.cs | 49 +++++++ 11 files changed, 338 insertions(+), 66 deletions(-) create mode 100644 tests/ByteSync.TestsCommon/TestHelpers/AuthenticationTestIdentity.cs diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md index d9485a268..4257e1b86 100644 --- a/docs/security-boundaries.md +++ b/docs/security-boundaries.md @@ -173,6 +173,16 @@ V3 clients require the matching relay and V3 peers. An older V2 peer is explicit For local Rider testing, run the Functions project built from this branch and launch the client in Debug with `--use-local-api`. Check the client's `LocalDebugUrl` matches the Functions host's actual port and `/api/` base path, then confirm the client log selects that local URL. Debug defaults to the remote DevelopmentUrl when no API-selection argument is supplied. The local-API switch applies to Debug execution; Release uses ProductionUrl (or its existing staging override). Run all session peers from the same V3 branch and create a fresh session. Coordinated remote deployment remains a separate, unexecuted operation. +## PR review corrections (2026-11-21) + +Join validation now resends the existing finalization proof after a failed or lost SignalR notification. Retries preserve both the proof and its original expiry, still require the bound current validator and an eligible pending member, and cannot recreate a proof after finalization. Regression tests cover successful and failed first notifications, ineligible retries, and exactly one finalization after resending. + +Functions integration fixtures and the HTTP end-to-end scenario now use a shared real RSA identity, request and sign an authentication challenge, bind refresh records to the current identity/epoch, and use server-generated storage object IDs instead of client metadata in object paths. The end-to-end join validation is authenticated as the validator rather than the joining client. Offline regressions exercise the shared identity with the real challenge, login, token and refresh services, reject challenge/refresh replay, and check SAS object/part/operation scope without making storage requests. + +Validation: solution build succeeded with zero errors; 402 server unit tests (excluding service-dependent repository and integration suites), 66 Functions unit tests and 54 Common unit tests passed, zero failures. These include 16 new regression cases; the shared RSA fixture helper has 100% line coverage. The migrated integration fixtures and E2E compile but were not executed because this correction was explicitly required to avoid Azure access and Docker. Restore used the local NuGet package cache. Evidence is under `artifacts/pr351-fixes/`. + +The correction commit uses `[skip ci]` to prevent the PR workflows from contacting configured Azure services or starting container-based tests after the requested push. Those workflows and the actual integration/E2E suites must be run later when external-service testing is authorized; no production checks were weakened to accommodate legacy fixtures. + ## Future rollout proposal (not executed) 1. Review this patch and approve the breaking protocol, restrictions and enrollment experience. Complete native multi-platform CI, isolated Redis/SignalR/storage end-to-end tests, load/abuse checks and the coverage gate. Confirm the Redis version before rollout. Back up local RSA/settings/trust/profile data through the existing supported process; do not collect private keys centrally. diff --git a/src/ByteSync.ServerCommon/Services/CloudSessionsService.cs b/src/ByteSync.ServerCommon/Services/CloudSessionsService.cs index 09c76cad2..18e3b3ca0 100644 --- a/src/ByteSync.ServerCommon/Services/CloudSessionsService.cs +++ b/src/ByteSync.ServerCommon/Services/CloudSessionsService.cs @@ -173,14 +173,15 @@ public async Task ValidateJoinCloudSession(ValidateJoinCloudSessionParameters pa .FirstOrDefault(m => Equals(m.ClientInstanceId, parameters.JoinerClientInstanceId) && Equals(m.ValidatorInstanceId, parameters.ValidatorInstanceId) && - m.JoinExpiresAt > DateTimeOffset.UtcNow && string.IsNullOrEmpty(m.FinalizationPassword)); + m.JoinExpiresAt > DateTimeOffset.UtcNow); if (joiner != null) { - var finaliationPassword = $"FP_{Guid.NewGuid()}"; - - joiner.FinalizationPassword = finaliationPassword; - parameters.FinalizationPassword = finaliationPassword; + if (string.IsNullOrEmpty(joiner.FinalizationPassword)) + { + joiner.FinalizationPassword = $"FP_{Guid.NewGuid()}"; + } + parameters.FinalizationPassword = joiner.FinalizationPassword; } return joiner != null; @@ -324,4 +325,4 @@ public async Task GiveCloudSessionPasswordExchangeKey(Client client, GiveCloudSe preSessionMemberData.BuildLog()); await _invokeClientsService.Client(preSessionMemberData).GiveCloudSessionPasswordExchangeKey(parameters).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/tests/ByteSync.Functions.IntegrationTests/ByteSync.Functions.IntegrationTests.csproj b/tests/ByteSync.Functions.IntegrationTests/ByteSync.Functions.IntegrationTests.csproj index 82ba9441c..6700f1eb9 100644 --- a/tests/ByteSync.Functions.IntegrationTests/ByteSync.Functions.IntegrationTests.csproj +++ b/tests/ByteSync.Functions.IntegrationTests/ByteSync.Functions.IntegrationTests.csproj @@ -36,6 +36,7 @@ + diff --git a/tests/ByteSync.Functions.IntegrationTests/End2End/E2E_Auth_Session_Tests.cs b/tests/ByteSync.Functions.IntegrationTests/End2End/E2E_Auth_Session_Tests.cs index d410541c4..b7e05ef43 100644 --- a/tests/ByteSync.Functions.IntegrationTests/End2End/E2E_Auth_Session_Tests.cs +++ b/tests/ByteSync.Functions.IntegrationTests/End2End/E2E_Auth_Session_Tests.cs @@ -8,6 +8,7 @@ using ByteSync.Common.Controls.Json; using FluentAssertions; using ByteSync.Functions.IntegrationTests.TestHelpers; +using ByteSync.TestsCommon.TestHelpers; namespace ByteSync.Functions.IntegrationTests.End2End; @@ -37,14 +38,9 @@ public async Task OneTimeTeardown() [Test] public async Task Auth_Login_Then_CreateCloudSession_ShouldSucceed() { - var loginA = new LoginData - { - ClientId = "e2e-client-A", - ClientInstanceId = Guid.NewGuid().ToString("N"), - Version = "9.9.9", - OsPlatform = Common.Business.Misc.OSPlatforms.Windows - }; - var tokenA = await LoginAsync(loginA); + using var identityA = new AuthenticationTestIdentity(); + var loginA = identityA.CreateLogin(); + var tokenA = await LoginAsync(loginA, identityA); _api.SetBearerToken(tokenA.AuthenticationTokens!.JwtToken); var createParams = new CreateCloudSessionParameters { @@ -52,7 +48,7 @@ public async Task Auth_Login_Then_CreateCloudSession_ShouldSucceed() CreatorProfileClientId = null, SessionSettings = new EncryptedSessionSettings { Id = Guid.NewGuid().ToString("N"), Data = new byte[16], IV = new byte[16] }, - CreatorPublicKeyInfo = new PublicKeyInfo { ClientId = loginA.ClientId, PublicKey = new byte[32] }, + CreatorPublicKeyInfo = identityA.CreatePublicKeyInfo(), CreatorPrivateData = new EncryptedSessionMemberPrivateData { Id = Guid.NewGuid().ToString("N"), Data = new byte[16], IV = new byte[16] } }; @@ -61,20 +57,18 @@ public async Task Auth_Login_Then_CreateCloudSession_ShouldSucceed() var sessionId = createResult.SessionId; var creatorMembers = await _api.GetJsonAsync>($"session/{sessionId}/members"); creatorMembers.Any(m => m.ClientInstanceId == loginA.ClientInstanceId).Should().BeTrue(); - var loginB = new LoginData - { - ClientId = "e2e-client-B", - ClientInstanceId = Guid.NewGuid().ToString("N"), - Version = "9.9.9", - OsPlatform = Common.Business.Misc.OSPlatforms.Windows - }; - var tokenB = await LoginAsync(loginB); + using var identityB = new AuthenticationTestIdentity(); + var loginB = identityB.CreateLogin(); + var tokenB = await LoginAsync(loginB, identityB); var askParams = new AskCloudSessionPasswordExchangeKeyParameters(sessionId, - new PublicKeyInfo { ClientId = loginB.ClientId, PublicKey = new byte[32] }) + identityB.CreatePublicKeyInfo()) { LobbyId = null, ProfileClientId = null }; + var members = await _api.PostJsonAsync>($"session/{sessionId}/beginJoin", + askParams, tokenB.AuthenticationTokens!.JwtToken); + members.Should().Contain(loginA.ClientInstanceId); var askResult = await _api.PostJsonAsync($"session/{sessionId}/askPasswordExchangeKey", askParams, tokenB.AuthenticationTokens!.JwtToken); askResult.Should().NotBeNull(); @@ -82,11 +76,14 @@ public async Task Auth_Login_Then_CreateCloudSession_ShouldSucceed() var validateParams = new ValidateJoinCloudSessionParameters(sessionId, loginB.ClientInstanceId, loginA.ClientInstanceId, new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }); await _api.PostJsonAsync($"session/{sessionId}/validateJoin", validateParams, - tokenB.AuthenticationTokens!.JwtToken); + tokenA.AuthenticationTokens!.JwtToken); } - private async Task LoginAsync(LoginData login) + private async Task LoginAsync(LoginData login, AuthenticationTestIdentity identity) { + var challenge = await _api.PostJsonAsync("auth/challenge", login); + challenge.Should().NotBeNull(); + identity.Sign(login, challenge!); var loginJson = JsonSerializer.Serialize(login); using var loginContent = new StringContent(loginJson, Encoding.UTF8, "application/json"); TestContext.Progress.WriteLine($"{DateTime.UtcNow:o} | POST /auth/login"); @@ -94,7 +91,7 @@ private async Task LoginAsync(LoginData login) if (!authResponse.IsSuccessStatusCode) { var body = await authResponse.Content.ReadAsStringAsync(); - Assert.Fail($"auth/login failed: {(int)authResponse.StatusCode} {authResponse.ReasonPhrase}. Body: {body}"); + throw new HttpRequestException($"auth/login failed: {(int)authResponse.StatusCode} {authResponse.ReasonPhrase}. Body: {body}"); } var authJson = await authResponse.Content.ReadAsStringAsync(); diff --git a/tests/ByteSync.Functions.IntegrationTests/Integration/Services/AuthenticateCommandHandler_Tests.cs b/tests/ByteSync.Functions.IntegrationTests/Integration/Services/AuthenticateCommandHandler_Tests.cs index 752764810..3e9ef705e 100644 --- a/tests/ByteSync.Functions.IntegrationTests/Integration/Services/AuthenticateCommandHandler_Tests.cs +++ b/tests/ByteSync.Functions.IntegrationTests/Integration/Services/AuthenticateCommandHandler_Tests.cs @@ -4,6 +4,9 @@ using ByteSync.ServerCommon.Commands.Authentication; using ByteSync.ServerCommon.Interfaces.Services.Clients; using FakeItEasy; +using ByteSync.ServerCommon.Interfaces.Services; +using ByteSync.TestsCommon.TestHelpers; +using FluentAssertions; namespace ByteSync.Functions.IntegrationTests.Integration.Services; @@ -40,31 +43,27 @@ public void Teardown() [Test] public async Task Authenticate_WithValidData_ReturnsSuccessResponse() { - var clientId = "integration-client-id"; - var clientInstanceId = "integration-client-instance"; - var version = "2.0.0"; - var osPlatform = Common.Business.Misc.OSPlatforms.Windows; + using var identity = new AuthenticationTestIdentity(); + var loginData = identity.CreateLogin(); + var challengeService = _scope.Resolve(); + identity.Sign(loginData, await challengeService.Create(loginData)); var ipAddress = "127.0.0.1"; - var loginData = new LoginData - { - ClientId = clientId, - ClientInstanceId = clientInstanceId, - Version = version, - OsPlatform = osPlatform - }; - var request = new AuthenticateRequest(loginData, ipAddress); var handler = _scope.Resolve(); // Act var response = await handler.Handle(request, CancellationToken.None); - // Assert - Assert.That(response, Is.Not.Null); - Assert.That(response.IsSuccess, Is.True, "Authentication should succeed with valid data"); - Assert.That(response.InitialConnectionStatus, Is.EqualTo(InitialConnectionStatus.Success)); - Assert.That(response.AuthenticationTokens, Is.Not.Null, "AuthenticationTokens should not be null"); - Assert.That(response.EndPoint, Is.Not.Null, "EndPoint should not be null"); + response.IsSuccess.Should().BeTrue(); + response.InitialConnectionStatus.Should().Be(InitialConnectionStatus.Success); + response.AuthenticationTokens.Should().NotBeNull(); + response.EndPoint.Should().NotBeNull(); + response.EndPoint!.ClientInstanceId.Should().Be(identity.ClientInstanceId); + + var replay = await handler.Handle(request, CancellationToken.None); + + replay.InitialConnectionStatus.Should().Be(InitialConnectionStatus.InvalidProof); + replay.AuthenticationTokens.Should().BeNull(); } -} \ No newline at end of file +} diff --git a/tests/ByteSync.Functions.IntegrationTests/Integration/Services/AzureBlobStorageService_Tests.cs b/tests/ByteSync.Functions.IntegrationTests/Integration/Services/AzureBlobStorageService_Tests.cs index c05f0e44b..2153bb0e7 100644 --- a/tests/ByteSync.Functions.IntegrationTests/Integration/Services/AzureBlobStorageService_Tests.cs +++ b/tests/ByteSync.Functions.IntegrationTests/Integration/Services/AzureBlobStorageService_Tests.cs @@ -1,4 +1,4 @@ -using Autofac; +using Autofac; using ByteSync.ServerCommon.Services.Storage; using ByteSync.ServerCommon.Business.Settings; using Microsoft.Extensions.Options; @@ -47,6 +47,7 @@ public async Task GetUploadAndDownloadUrls_ShouldContainSas_WithExpectedPermissi var service = _scope.Resolve(); var shared = new SharedFileDefinition { + StorageObjectId = Guid.NewGuid().ToString("N"), SessionId = "sess123", ClientInstanceId = "cliABC", SharedFileType = SharedFileTypes.FullSynchronization, @@ -70,8 +71,11 @@ public async Task GetUploadAndDownloadUrls_ShouldContainSas_WithExpectedPermissi downloadQuery["se"].Should().NotBeNull(); downloadQuery["sp"].Should().NotBeNull(); - uploadQuery["sp"]!.Should().Contain("w"); - downloadQuery["sp"]!.Should().Contain("r"); + uploadQuery["sp"].Should().Be("w"); + downloadQuery["sp"].Should().Be("r"); + uploadUri.AbsolutePath.Should().EndWith($"/{shared.StorageObjectId}/part-{partNumber}"); + downloadUri.AbsolutePath.Should().Be(uploadUri.AbsolutePath); + DateTimeOffset.Parse(uploadQuery["se"]!).Should().BeCloseTo(DateTimeOffset.UtcNow.AddMinutes(5), TimeSpan.FromSeconds(15)); } [Test] @@ -80,6 +84,7 @@ public async Task Urls_ShouldDiffer_AndPartNumberImpactsKey() var service = _scope.Resolve(); var shared = new SharedFileDefinition { + StorageObjectId = Guid.NewGuid().ToString("N"), SessionId = "sessA", ClientInstanceId = "cliA", SharedFileType = SharedFileTypes.FullSynchronization @@ -88,14 +93,17 @@ public async Task Urls_ShouldDiffer_AndPartNumberImpactsKey() var url1 = await service.GetUploadFileUrl(shared, 1); var url2 = await service.GetUploadFileUrl(shared, 2); url1.Should().NotBe(url2); + new Uri(url1).AbsolutePath.Should().EndWith($"/{shared.StorageObjectId}/part-1"); + new Uri(url2).AbsolutePath.Should().EndWith($"/{shared.StorageObjectId}/part-2"); } [Test] - public async Task InventoryType_ShouldUseAdditionalNameInKey() + public async Task InventoryType_ShouldUseServerObjectIdWithoutEmbeddingClientMetadata() { var service = _scope.Resolve(); var shared = new SharedFileDefinition { + StorageObjectId = Guid.NewGuid().ToString("N"), SessionId = "sessInvA", ClientInstanceId = "cliInvA", SharedFileType = SharedFileTypes.BaseInventory, @@ -104,6 +112,10 @@ public async Task InventoryType_ShouldUseAdditionalNameInKey() var url = await service.GetDownloadFileUrl(shared, 1); var uri = new Uri(url); - uri.ToString().Should().Contain("base_inventory_profileABC"); + uri.AbsolutePath.Should().EndWith($"/{shared.StorageObjectId}/part-1"); + uri.AbsolutePath.Should().NotContain(shared.SessionId).And.NotContain(shared.ClientInstanceId).And.NotContain(shared.AdditionalName); + shared.AdditionalName = "different-profile-name"; + var renamed = new Uri(await service.GetDownloadFileUrl(shared, 1)); + renamed.AbsolutePath.Should().Be(uri.AbsolutePath); } } \ No newline at end of file diff --git a/tests/ByteSync.Functions.IntegrationTests/Integration/Services/RefreshTokensCommandHandler_Tests.cs b/tests/ByteSync.Functions.IntegrationTests/Integration/Services/RefreshTokensCommandHandler_Tests.cs index 221b0e64f..4c3f5fcf9 100644 --- a/tests/ByteSync.Functions.IntegrationTests/Integration/Services/RefreshTokensCommandHandler_Tests.cs +++ b/tests/ByteSync.Functions.IntegrationTests/Integration/Services/RefreshTokensCommandHandler_Tests.cs @@ -4,6 +4,8 @@ using ByteSync.Functions.IntegrationTests.TestHelpers.Autofac; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Commands.Authentication; +using ByteSync.TestsCommon.TestHelpers; +using FluentAssertions; namespace ByteSync.Functions.IntegrationTests.Integration.Services; @@ -36,8 +38,9 @@ public async Task RefreshTokens_WithValidToken_UpdatesTokenAndReturnsSuccess() { // Arrange var clientsRepository = _scope.Resolve(); - var clientInstanceId = "integration-client-instance"; - var clientId = "integration-client-id"; + using var identity = new AuthenticationTestIdentity(); + var clientInstanceId = identity.ClientInstanceId; + var clientId = identity.Identity; var refreshToken = "valid-refresh-token"; var version = "2.0.0"; var osPlatform = Common.Business.Misc.OSPlatforms.Windows; @@ -46,12 +49,15 @@ public async Task RefreshTokens_WithValidToken_UpdatesTokenAndReturnsSuccess() await clientsRepository.AddOrUpdate(clientInstanceId, c => { c ??= new Client(); + c.Identity = identity.Identity; + c.AuthenticationEpoch = AuthenticationProtocol.Epoch; c.ClientId = clientId; c.ClientInstanceId = clientInstanceId; c.Version = version; c.OsPlatform = osPlatform; c.IpAddress = ipAddress; c.RefreshToken = new RefreshToken { + AuthenticationEpoch = AuthenticationProtocol.Epoch, Token = refreshToken, Expires = now.AddMinutes(10), Created = now, @@ -77,15 +83,17 @@ await clientsRepository.AddOrUpdate(clientInstanceId, c => { // Act var response = await handler.Handle(request, CancellationToken.None); - // Assert - Assert.That(response.RefreshTokensStatus, Is.EqualTo(RefreshTokensStatus.RefreshTokenOk)); - Assert.That(response.AuthenticationTokens, Is.Not.Null); + response.RefreshTokensStatus.Should().Be(RefreshTokensStatus.RefreshTokenOk); + response.AuthenticationTokens.Should().NotBeNull(); - // Assert that the refresh token was updated (rotated) var updatedClient = await clientsRepository.Get(clientInstanceId); - Assert.That(updatedClient, Is.Not.Null); - Assert.That(updatedClient.RefreshToken, Is.Not.Null); - Assert.That(updatedClient.RefreshToken.Token, Is.Not.EqualTo(refreshToken), "Refresh token should be rotated and not equal to the old token."); - Assert.That(updatedClient.RefreshToken.Expires, Is.GreaterThan(now), "New refresh token should have a later expiration."); + updatedClient.Should().NotBeNull(); + updatedClient!.Identity.Should().Be(identity.Identity); + updatedClient.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); + updatedClient.RefreshToken.Should().NotBeNull(); + updatedClient.RefreshToken!.Token.Should().NotBe(refreshToken); + updatedClient.RefreshToken.Expires.Should().BeAfter(now); + updatedClient.RefreshToken.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); + response.AuthenticationTokens!.RefreshToken.Should().Be(updatedClient.RefreshToken.Token); } -} \ No newline at end of file +} diff --git a/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs index 8bce8c68f..6c0834595 100644 --- a/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs @@ -9,6 +9,15 @@ using FakeItEasy; using FluentAssertions; using StackExchange.Redis; +using ByteSync.ServerCommon.Business.Auth; +using ByteSync.ServerCommon.Business.Settings; +using ByteSync.ServerCommon.Commands.Authentication; +using ByteSync.ServerCommon.Interfaces.Factories; +using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Services.Clients; +using ByteSync.ServerCommon.Tests.Helpers; +using ByteSync.TestsCommon.TestHelpers; +using Microsoft.Extensions.Options; namespace ByteSync.ServerCommon.Tests.Security; @@ -54,6 +63,52 @@ private void Sign(LoginData login, AuthenticationChallenge challenge) login.Signature = _key.SignData(AuthenticationProtocol.GetMessage(login, challenge), HashAlgorithmName.SHA256, RSASignaturePadding.Pss); } + [Test] + public async Task IntegrationIdentity_UsesSignedChallengesAndProducesRefreshableCurrentEpochTokens() + { + using var identity = new AuthenticationTestIdentity(); + var login = identity.CreateLogin(); + var keyInfo = identity.CreatePublicKeyInfo(); + AuthenticationProtocol.GetIdentity(keyInfo.PublicKey).Should().Be(identity.Identity); + keyInfo.ProtocolVersion.Should().Be(ProtocolVersion.CURRENT); + keyInfo.ClientId.Should().Be(identity.Identity); + identity.Sign(login, await _service.Create(login)); + Client? saved = null; + var clients = A.Fake(); + A.CallTo(() => clients.AddOrUpdate(identity.ClientInstanceId, A>._)) + .ReturnsLazily((string _, Func update) => + { + var updated = update(saved); + if (updated != null) saved = updated; + return UpdateResultBuilder.BuildAddOrUpdateResult(updated, false); + }); + var versions = A.Fake(); + A.CallTo(() => versions.IsClientVersionAllowed(login)).Returns(true); + var tokens = new TokensFactory(Options.Create(new AppSettings + { + Secret = "offline-fixture-validation-signing-key-at-least-32-bytes", JwtDurationInSeconds = 300 + })); + var handler = new AuthenticateCommandHandler(tokens, A.Fake(), clients, versions, _service); + + var response = await handler.Handle(new AuthenticateRequest(login, "127.0.0.1"), CancellationToken.None); + var originalRefresh = response.AuthenticationTokens!.RefreshToken; + var refreshed = await new RefreshTokensCommandHandler(tokens, clients).Handle(new RefreshTokensRequest( + new RefreshTokensData { ClientInstanceId = identity.ClientInstanceId, Token = originalRefresh }, "127.0.0.1"), CancellationToken.None); + var replay = await handler.Handle(new AuthenticateRequest(login, "127.0.0.1"), CancellationToken.None); + + response.IsSuccess.Should().BeTrue(); + saved!.Identity.Should().Be(identity.Identity); + saved.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); + refreshed.RefreshTokensStatus.Should().Be(RefreshTokensStatus.RefreshTokenOk); + refreshed.AuthenticationTokens!.RefreshToken.Should().NotBe(originalRefresh); + saved.RefreshToken!.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); + var reusedRefresh = await new RefreshTokensCommandHandler(tokens, clients).Handle(new RefreshTokensRequest( + new RefreshTokensData { ClientInstanceId = identity.ClientInstanceId, Token = originalRefresh }, "127.0.0.1"), CancellationToken.None); + reusedRefresh.IsSuccess.Should().BeFalse(); + replay.InitialConnectionStatus.Should().Be(InitialConnectionStatus.InvalidProof); + replay.AuthenticationTokens.Should().BeNull(); + } + [Test] public async Task Login_WithDurableKey_AllowsDistinctInstancesAndRejectsReplay() { diff --git a/tests/ByteSync.ServerCommon.Tests/Security/JoinProofSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/JoinProofSecurityTests.cs index 8c2c14751..2dfd1dfe4 100644 --- a/tests/ByteSync.ServerCommon.Tests/Security/JoinProofSecurityTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Security/JoinProofSecurityTests.cs @@ -9,6 +9,7 @@ using ByteSync.ServerCommon.Interfaces.Repositories; using ByteSync.ServerCommon.Interfaces.Services; using ByteSync.ServerCommon.Interfaces.Services.Clients; +using ByteSync.ServerCommon.Services; using FakeItEasy; using FluentAssertions; using Microsoft.Extensions.Logging.Abstractions; @@ -19,6 +20,137 @@ namespace ByteSync.ServerCommon.Tests.Security; public class JoinProofSecurityTests { + [TestCase(false)] + [TestCase(true)] + public async Task ValidationRetry_ResendsTheSameUnexpiredProof(bool firstNotificationFails) + { + var context = ValidationContext(); + var expiry = context.Joiner.JoinExpiresAt; + var deliveredProofs = new List(); + A.CallTo(() => context.Hub.YouJoinedSession(A._, A._)) + .ReturnsLazily((CloudSessionResult _, ValidateJoinCloudSessionParameters parameters) => + { + deliveredProofs.Add(parameters.FinalizationPassword); + return firstNotificationFails && deliveredProofs.Count == 1 + ? Task.FromException(new IOException("Simulated lost notification")) : Task.CompletedTask; + }); + var first = () => context.Service.ValidateJoinCloudSession(ValidationParameters(context.Joiner), context.Validator); + if (firstNotificationFails) await first.Should().ThrowAsync(); + else await first.Should().NotThrowAsync(); + var proof = context.Joiner.FinalizationPassword; + var retry = ValidationParameters(context.Joiner); + retry.FinalizationPassword = "caller-supplied-proof"; + + await context.Service.ValidateJoinCloudSession(retry, context.Validator); + + proof.Should().StartWith("FP_"); + deliveredProofs.Should().Equal(proof, proof); + retry.FinalizationPassword.Should().Be(proof); + context.Joiner.FinalizationPassword.Should().Be(proof); + context.Joiner.JoinExpiresAt.Should().Be(expiry); + context.Session.PreSessionMembers.Should().ContainSingle(); + } + + [TestCase("expired")] + [TestCase("activated")] + [TestCase("removed")] + [TestCase("identity")] + [TestCase("finalized")] + [TestCase("unknown-joiner")] + [TestCase("validator")] + [TestCase("epoch")] + public async Task ValidationRetry_DoesNotReissueAnIneligibleProof(string scenario) + { + var context = ValidationContext(); + context.Joiner.FinalizationPassword = "existing-proof"; + var parameters = ValidationParameters(context.Joiner); + switch (scenario) + { + case "expired": context.Joiner.JoinExpiresAt = DateTimeOffset.UtcNow.AddSeconds(-1); break; + case "activated": context.Session.IsSessionActivated = true; break; + case "removed": context.Session.IsSessionRemoved = true; break; + case "identity": context.Validator.Identity = "another-identity"; break; + case "finalized": + context.Joiner.FinalizationPassword = ""; + context.Session.PreSessionMembers.Clear(); + context.Session.SessionMembers.Add(context.Joiner); + break; + case "unknown-joiner": parameters.JoinerClientInstanceId = "another-joiner"; break; + case "validator": parameters.ValidatorInstanceId = "another-validator"; break; + case "epoch": context.Validator.AuthenticationEpoch = 0; break; + } + var proof = context.Joiner.FinalizationPassword; + var expiry = context.Joiner.JoinExpiresAt; + + var act = () => context.Service.ValidateJoinCloudSession(parameters, context.Validator); + + if (scenario is "validator" or "epoch") await act.Should().ThrowAsync(); + else await act.Should().NotThrowAsync(); + context.Joiner.FinalizationPassword.Should().Be(proof); + context.Joiner.JoinExpiresAt.Should().Be(expiry); + A.CallTo(context.Hub).MustNotHaveHappened(); + } + + private static ValidateJoinCloudSessionParameters ValidationParameters(SessionMemberData joiner) => + new("session", joiner.ClientInstanceId, joiner.ValidatorInstanceId, new byte[] { 1 }); + + [Test] + public async Task ResentProof_CanStillBeFinalizedOnlyOnce() + { + var context = ValidationContext(); + var validation = ValidationParameters(context.Joiner); + await context.Service.ValidateJoinCloudSession(validation, context.Validator); + await context.Service.ValidateJoinCloudSession(ValidationParameters(context.Joiner), context.Validator); + context.Session.SessionMembers[0].AuthCheckClientInstanceIds.Add(context.Joiner.ClientInstanceId); + var redis = A.Fake(); + var transaction = A.Fake(); + A.CallTo(() => redis.OpenTransaction()).Returns(transaction); + A.CallTo(() => transaction.ExecuteAsync(A._)).Returns(true); + var handler = new FinalizeJoinCloudSessionCommandHandler(context.Repository, A.Fake(), + A.Fake(), A.Fake(), redis, NullLogger.Instance); + var caller = new Client { ClientInstanceId = context.Joiner.ClientInstanceId, Identity = context.Joiner.Identity, + AuthenticationEpoch = AuthenticationProtocol.Epoch }; + var request = new FinalizeJoinCloudSessionRequest(new FinalizeJoinCloudSessionParameters + { + SessionId = "session", JoinerInstanceId = caller.ClientInstanceId, + ValidatorInstanceId = context.Validator.ClientInstanceId, FinalizationPassword = validation.FinalizationPassword + }, caller); + + var first = await handler.Handle(request, CancellationToken.None); + var replay = await handler.Handle(request, CancellationToken.None); + + first.Status.Should().Be(FinalizeJoinSessionStatuses.FinalizeJoinSessionSucess); + replay.Status.Should().NotBe(FinalizeJoinSessionStatuses.FinalizeJoinSessionSucess); + context.Joiner.FinalizationPassword.Should().BeEmpty(); + context.Session.PreSessionMembers.Should().BeEmpty(); + context.Session.SessionMembers.Count(m => m.ClientInstanceId == caller.ClientInstanceId).Should().Be(1); + } + + private static (CloudSessionsService Service, Client Validator, CloudSessionData Session, SessionMemberData Joiner, IHubByteSyncPush Hub, ICloudSessionsRepository Repository) ValidationContext() + { + var identity = new string('A', 64); + var validator = new Client { ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), + Identity = identity, AuthenticationEpoch = AuthenticationProtocol.Epoch }; + var session = new CloudSessionData { SessionId = "session", CreatorInstanceId = validator.ClientInstanceId }; + session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = validator.ClientInstanceId, Identity = identity }); + var joinerIdentity = new string('B', 64); + var joiner = new SessionMemberData { ClientInstanceId = joinerIdentity + "_" + Guid.NewGuid().ToString("D"), + Identity = joinerIdentity, ValidatorInstanceId = validator.ClientInstanceId, + CloudSessionData = session, JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(2) }; + session.PreSessionMembers.Add(joiner); + var repository = A.Fake(); + A.CallTo(() => repository.Update("session", A>._, A._, A._)) + .ReturnsLazily((string _, Func update, ITransaction? tx, IRedLock? redisLock) => + new UpdateEntityResult(session, update(session) + ? tx == null ? UpdateEntityStatus.Saved : UpdateEntityStatus.WaitingForTransaction + : UpdateEntityStatus.NoOperation)); + var pushes = A.Fake(); + var hub = A.Fake(); + A.CallTo(() => pushes.Client(joiner)).Returns(hub); + var service = new CloudSessionsService(NullLogger.Instance, repository, A.Fake(), pushes); + return (service, validator, session, joiner, hub, repository); + } + [TestCase("expired")] [TestCase("password")] [TestCase("identity")] diff --git a/tests/ByteSync.ServerCommon.Tests/Security/StorageUrlScopeSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/StorageUrlScopeSecurityTests.cs index fce902e21..8adaf2282 100644 --- a/tests/ByteSync.ServerCommon.Tests/Security/StorageUrlScopeSecurityTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Security/StorageUrlScopeSecurityTests.cs @@ -11,9 +11,13 @@ namespace ByteSync.ServerCommon.Tests.Security; public class StorageUrlScopeSecurityTests { - [TestCase(true, "w")] - [TestCase(false, "r")] - public async Task AzureSas_IsLimitedToTheRegisteredObjectPartAndExpectedOperation(bool upload, string permission) + [TestCase(true, "w", SharedFileTypes.FullSynchronization)] + [TestCase(false, "r", SharedFileTypes.FullSynchronization)] + [TestCase(true, "w", SharedFileTypes.BaseInventory)] + [TestCase(false, "r", SharedFileTypes.BaseInventory)] + [TestCase(true, "w", SharedFileTypes.FullInventory)] + [TestCase(false, "r", SharedFileTypes.ProfileDetails)] + public async Task AzureSas_IsLimitedToTheRegisteredObjectPartAndExpectedOperation(bool upload, string permission, SharedFileTypes type) { var factory = A.Fake(); var credential = new StorageSharedKeyCredential("testaccount", Convert.ToBase64String(new byte[32])); @@ -21,7 +25,8 @@ public async Task AzureSas_IsLimitedToTheRegisteredObjectPartAndExpectedOperatio A.CallTo(() => factory.GetOrCreateContainer(A._)).Returns(new BlobContainerClient(new Uri("https://testaccount.blob.core.windows.net/files"), credential)); var service = new AzureBlobStorageService(factory, NullLogger.Instance); var objectId = Guid.NewGuid().ToString("N"); - var definition = new SharedFileDefinition { StorageObjectId = objectId, Id = "untrusted", SessionId = "untrusted", AdditionalName = "../untrusted" }; + var definition = new SharedFileDefinition { StorageObjectId = objectId, Id = "untrusted", SessionId = "untrusted", + SharedFileType = type, AdditionalName = "../untrusted" }; var url = upload ? await service.GetUploadFileUrl(definition, 7) : await service.GetDownloadFileUrl(definition, 7); var uri = new Uri(url); @@ -31,6 +36,9 @@ public async Task AzureSas_IsLimitedToTheRegisteredObjectPartAndExpectedOperatio query["sp"].Should().Be(permission); query["sr"].Should().Be("b"); DateTimeOffset.Parse(query["se"]!).Should().BeCloseTo(DateTimeOffset.UtcNow.AddMinutes(5), TimeSpan.FromSeconds(5)); + definition.AdditionalName = "another-inventory-name"; + var renamed = upload ? await service.GetUploadFileUrl(definition, 7) : await service.GetDownloadFileUrl(definition, 7); + new Uri(renamed).AbsolutePath.Should().Be(uri.AbsolutePath); } [TestCase(true)] [TestCase(false)] diff --git a/tests/ByteSync.TestsCommon/TestHelpers/AuthenticationTestIdentity.cs b/tests/ByteSync.TestsCommon/TestHelpers/AuthenticationTestIdentity.cs new file mode 100644 index 000000000..1cb01942e --- /dev/null +++ b/tests/ByteSync.TestsCommon/TestHelpers/AuthenticationTestIdentity.cs @@ -0,0 +1,49 @@ +using System.Security.Cryptography; +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.EndPoints; +using ByteSync.Common.Business.Misc; +using ByteSync.Common.Business.Versions; + +namespace ByteSync.TestsCommon.TestHelpers; + +public sealed class AuthenticationTestIdentity : IDisposable +{ + private readonly RSA _key = RSA.Create(2048); + + public AuthenticationTestIdentity() + { + Identity = AuthenticationProtocol.GetIdentity(_key.ExportRSAPublicKey()); + ClientInstanceId = $"{Identity}_{Guid.NewGuid():D}"; + } + + public string Identity { get; } + public string ClientInstanceId { get; } + + public LoginData CreateLogin() => new() + { + ClientId = Identity, + Identity = Identity, + ClientInstanceId = ClientInstanceId, + PublicKey = _key.ExportRSAPublicKey(), + AuthenticationEpoch = AuthenticationProtocol.Epoch, + ProtocolVersion = ProtocolVersion.CURRENT, + Version = "9.9.9", + OsPlatform = OSPlatforms.Windows + }; + + public PublicKeyInfo CreatePublicKeyInfo() => new() + { + ClientId = Identity, + PublicKey = _key.ExportRSAPublicKey(), + ProtocolVersion = ProtocolVersion.CURRENT + }; + + public void Sign(LoginData login, AuthenticationChallenge challenge) + { + login.ChallengeId = challenge.Id; + login.Signature = _key.SignData(AuthenticationProtocol.GetMessage(login, challenge), + HashAlgorithmName.SHA256, RSASignaturePadding.Pss); + } + + public void Dispose() => _key.Dispose(); +} From e900eb6135b709bd12a3375fbf6b831eeb2479c3 Mon Sep 17 00:00:00 2001 From: Paul Fresquet Date: Sat, 21 Nov 2026 16:14:48 +0100 Subject: [PATCH 6/8] fix: preserve readable ClientId alongside verified identity [skip ci] --- docs/security-boundaries.md | 18 +++- .../DependencyInjection/ServiceRegistrar.cs | 5 +- .../Applications/IEnvironmentService.cs | 6 +- .../Applications/EnvironmentService.cs | 12 ++- .../Communications/Api/AuthApiClient.cs | 1 + .../Communications/PublicKeysTruster.cs | 4 +- .../Business/Auth/AuthenticationProtocol.cs | 1 + .../Profiles/CloudSessionProfileSlot.cs | 3 +- .../AuthenticateCommandHandler.cs | 3 +- .../Lobbies/TryJoinLobbyCommandHandler.cs | 4 +- .../AuthenticationChallengeService.cs | 3 +- .../Services/CloudSessionProfileService.cs | 11 +-- .../Applications/EnvironmentService_Tests.cs | 11 +-- .../Communications/PublicKeysManagerTests.cs | 22 ++++- .../Communications/PublicKeysTrusterTests.cs | 25 ++++++ .../AuthProtocolCompatibilityTests.cs | 83 +++++++++++++++++- .../AuthenticationChallengeRedis60Tests.cs | 2 +- .../Security/AuthenticationSecurityTests.cs | 85 ++++++++++++++++++- .../LoginIdentityBindingSecurityTests.cs | 2 +- .../ProfileAuthorizationSecurityTests.cs | 51 ++++++++++- .../TestHelpers/AuthenticationTestIdentity.cs | 8 +- 21 files changed, 321 insertions(+), 39 deletions(-) diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md index 4257e1b86..57604c333 100644 --- a/docs/security-boundaries.md +++ b/docs/security-boundaries.md @@ -10,7 +10,7 @@ This is an implementation and local validation report, not evidence of a deploye `AuthenticationProtocol` derives the identity from SHA-256 of canonical DER SubjectPublicKeyInfo after fully importing the existing PKCS#1 RSA public key. The full uppercase 64-character fingerprint is the security identity. Keys must be 2048–8192 bits; trailing key data is rejected. Instance identifiers consist of that fingerprint, an underscore and a canonical GUID. Multiple instances can prove possession of the same durable key independently. -The client retains its existing RSA private key. Login first obtains a random 256-bit server nonce with a two-minute lifetime, then signs a length-prefixed canonical binary message with RSA-PSS/SHA-256. The message binds the domain, authentication epoch, relay audience, protocol version, challenge ID, nonce, expiry, fingerprint, instance, software version and platform. The relay stores the exact binding, consumes the Redis challenge using a single atomic Lua script (`GET` followed by `DEL` inside the script), then verifies the signature. Failed verification does not issue tokens or adopt an existing instance. The script uses commands available in Azure Cache for Redis 6.0; GETDEL is not required. Scripting must be permitted, and script errors fail closed without a non-atomic fallback. +The client retains its existing RSA private key. Login first obtains a random 256-bit server nonce with a two-minute lifetime, then signs a length-prefixed canonical binary message with RSA-PSS/SHA-256. The message binds the domain, authentication epoch, relay audience, protocol version, challenge ID, nonce, expiry, fingerprint, readable ClientId, instance, software version and platform. The relay stores the exact binding, consumes the Redis challenge using a single atomic Lua script (`GET` followed by `DEL` inside the script), then verifies the signature. Failed verification does not issue tokens or adopt an existing instance. The script uses commands available in Azure Cache for Redis 6.0; GETDEL is not required. Scripting must be permitted, and script errors fail closed without a non-atomic fallback. The current authentication epoch is 1 and protocol is V3. Software version remains a separate compatibility check and cannot substitute for proof of possession. The legacy short `ApplicationSettings.ClientId` remains a display/trust alias; it cannot claim a server identity or an old instance. There is no first-key-wins migration of old aliases. Existing mismatched or legacy instance records are rejected. @@ -183,6 +183,20 @@ Validation: solution build succeeded with zero errors; 402 server unit tests (ex The correction commit uses `[skip ci]` to prevent the PR workflows from contacting configured Azure services or starting container-based tests after the requested push. Those workflows and the actual integration/E2E suites must be run later when external-service testing is authorized; no production checks were weakened to accommodate legacy fixtures. +## ClientId and Identity clarification (2026-11-21) + +`ClientId` remains the stored readable installation code, in the existing `ABCD-EFG-HIJ` format. Environment initialization, About/display consumers, public-key information, login requests, server records, endpoints and the JWT ClientId claim all retain that alias. No migration rewrites `ApplicationSettings.ClientId`, regenerates the RSA key pair or clears existing trusted keys. Trust continues to require the previously accepted public key; an identical readable alias with a different key is not trusted. + +`Identity` separately holds the full canonical RSA fingerprint. It owns authentication, instance binding and authorization. `ClientInstanceId` remains `_`; reverting its prefix to the short code would restore an unsafe identity shortcut. The readable alias is now included in both the signed login message and the stored challenge binding. Two different keys can share an alias without merging server records or claiming an existing instance. Legacy records without a verified identity/epoch remain rejected. + +Dormant profile/lobby ownership checks now use an explicit slot `Identity`, while slot `ClientId` retains the readable code. Missing identities fail closed. This is an authorization correction, with no profile migration or new profile behavior. + +This does not restore the legacy network protocol: clients, relay and peers still need matched V3 builds. The revised canonical login message is part of this unreleased PR; intermediate builds of the PR must also be rebuilt together. + +Offline validation: solution build succeeded with zero errors. **1,816 tests passed, zero failures**: 1,284 client, 412 server (excluding service-dependent repository/integration suites), 66 Functions and 54 Common. Twelve existing POSIX-only client cases did not execute on Windows. The 22 added regression cases cover retained aliases/keys/trust, identity-based instance filtering, alias collisions, signed challenge binding and profile/lobby authorization. The Functions adapter initially failed to load; cleaning and rebuilding its local test outputs resolved this, and all 66 tests then passed. Integration/E2E fixtures compile but were not run. + +Combined client/server coverage covers 20 of the 22 changed executable production lines (90.9%); the two bootstrap wiring lines were not executed. `AuthApiClient`, `AuthenticationChallengeService`, `CloudSessionProfileService` and the shared RSA fixture helper have 100% line coverage in these runs. This local change metric does not establish the PR-wide Sonar coverage gate. Evidence is under `artifacts/clientid-identity/`, including `validation.json`, TRX and coverage files. No Azure endpoint was contacted and Docker was not started. The same PR branch receives the correction with `[skip ci]` to avoid Azure/container workflows. + ## Future rollout proposal (not executed) 1. Review this patch and approve the breaking protocol, restrictions and enrollment experience. Complete native multi-platform CI, isolated Redis/SignalR/storage end-to-end tests, load/abuse checks and the coverage gate. Confirm the Redis version before rollout. Back up local RSA/settings/trust/profile data through the existing supported process; do not collect private keys centrally. @@ -208,4 +222,4 @@ Relay authorization checks use current repository state before dispatch; they do HTTP bodies/archives still need a broader resource-abuse budget/rate-limit review. Peer possession proves control of a key, not that the key owner is honest. A session member may still request destructive actions within sources the local user authorized. The relay cannot inspect encrypted file contents. Cryptographic content integrity/AEAD, security-word entropy and update authenticity remain separate tracked work. Existing dependency vulnerability warnings were observed during build; this patch does not update those packages. -No push, public PR, publication, deployment, production configuration change or external message was performed. Network use was limited to read-only repository-head/documentation checks; all executed tests used local files, synthetic credentials, fakes or offline signing. +No deployment or production configuration change was performed. The PR and its follow-up commits are hosted on GitHub; no Azure service was tested. Executed validation used local files, synthetic credentials, fakes or offline signing, subject to the OS exclusions and unexecuted integration cases recorded above. diff --git a/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs b/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs index 5cb5d8cba..6685b7ca7 100644 --- a/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs +++ b/src/ByteSync.Client/DependencyInjection/ServiceRegistrar.cs @@ -86,7 +86,8 @@ private static void FeedClientId(this IContainer container) var environmentService = scope.Resolve(); var applicationSettings = applicationSettingsRepository.GetCurrentApplicationSettings(); - environmentService.SetClientId(ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(applicationSettings.DecodedRsaPublicKey!)); + environmentService.SetClientIdentity(applicationSettings.ClientId, + ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(applicationSettings.DecodedRsaPublicKey!)); } private static void LogBootstrapHeader(this IContainer container) @@ -104,4 +105,4 @@ private static void LogBootstrap(this IContainer container) var logger = scope.Resolve(); logger.LogBootstrapContent(); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Interfaces/Controls/Applications/IEnvironmentService.cs b/src/ByteSync.Client/Interfaces/Controls/Applications/IEnvironmentService.cs index 5ef88fe5c..44b025001 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Applications/IEnvironmentService.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Applications/IEnvironmentService.cs @@ -19,7 +19,7 @@ public interface IEnvironmentService public bool IsAutoRunProfile(); - public void SetClientId(string clientId); + public void SetClientIdentity(string clientId, string identity); string AssemblyFullName { get; } @@ -35,5 +35,7 @@ public interface IEnvironmentService string ClientId { get; } + string Identity { get; } + string ClientInstanceId { get; } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Services/Applications/EnvironmentService.cs b/src/ByteSync.Client/Services/Applications/EnvironmentService.cs index d455d7823..dd9101543 100644 --- a/src/ByteSync.Client/Services/Applications/EnvironmentService.cs +++ b/src/ByteSync.Client/Services/Applications/EnvironmentService.cs @@ -29,6 +29,8 @@ public EnvironmentService(IMsixPfnParser msixPfnParser) } public string ClientId { get; private set; } = null!; + + public string Identity { get; private set; } = null!; public string ClientInstanceId { get; private set; } = null!; @@ -227,11 +229,13 @@ public Version ApplicationVersion } } - public void SetClientId(string clientId) + public void SetClientIdentity(string clientId, string identity) { - if (!ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf($"{clientId}_{Guid.Empty:D}", clientId)) - throw new ArgumentException("A full RSA key fingerprint is required", nameof(clientId)); + ArgumentException.ThrowIfNullOrWhiteSpace(clientId); + if (identity == null || !ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf($"{identity}_{Guid.Empty:D}", identity)) + throw new ArgumentException("A full RSA key fingerprint is required", nameof(identity)); ClientId = clientId; - ClientInstanceId = $"{ClientId}_{Guid.NewGuid():D}"; + Identity = identity; + ClientInstanceId = $"{Identity}_{Guid.NewGuid():D}"; } } diff --git a/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs b/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs index cfece7661..f8fbb72ab 100644 --- a/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs +++ b/src/ByteSync.Client/Services/Communications/Api/AuthApiClient.cs @@ -28,6 +28,7 @@ public AuthApiClient(IApiInvoker apiInvoker, IApplicationSettingsRepository sett try { var settings = _settings.GetCurrentApplicationSettings(); + loginData.ClientId = settings.ClientId; loginData.PublicKey = settings.DecodedRsaPublicKey!; loginData.Identity = AuthenticationProtocol.GetIdentity(loginData.PublicKey); loginData.AuthenticationEpoch = AuthenticationProtocol.Epoch; diff --git a/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs b/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs index 7cba4efc9..fd3f601ef 100644 --- a/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs +++ b/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs @@ -274,7 +274,7 @@ private async Task InitiateAndWaitForTrustCheck(string sessio return JoinSessionResult.BuildFrom(JoinSessionStatus.SessionNotFound); } - memberIdsToCheck.RemoveAll(id => ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf(id, _environmentService.ClientId)); + memberIdsToCheck.RemoveAll(id => ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf(id, _environmentService.Identity)); if (memberIdsToCheck.Count == 0) { return JoinSessionResult.BuildProcessingNormally(); @@ -335,4 +335,4 @@ private void LogProblem(string problemDescription, [CallerMemberName] string cal // ReSharper disable once TemplateIsNotCompileTimeConstantProblem _logger.LogWarning($"CloudSessionConnector.{caller}: {problemDescription}"); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Common/Business/Auth/AuthenticationProtocol.cs b/src/ByteSync.Common/Business/Auth/AuthenticationProtocol.cs index 49b55727c..9ea7b5a44 100644 --- a/src/ByteSync.Common/Business/Auth/AuthenticationProtocol.cs +++ b/src/ByteSync.Common/Business/Auth/AuthenticationProtocol.cs @@ -41,6 +41,7 @@ public static byte[] GetMessage(LoginData login, AuthenticationChallenge challen writer.Write(challenge.Nonce); writer.Write(challenge.ExpiresAt.UtcTicks); writer.Write(login.Identity); + writer.Write(login.ClientId); writer.Write(login.ClientInstanceId); writer.Write(login.Version); writer.Write((int)(login.OsPlatform ?? 0)); diff --git a/src/ByteSync.Common/Business/Profiles/CloudSessionProfileSlot.cs b/src/ByteSync.Common/Business/Profiles/CloudSessionProfileSlot.cs index 74452904d..c82960327 100644 --- a/src/ByteSync.Common/Business/Profiles/CloudSessionProfileSlot.cs +++ b/src/ByteSync.Common/Business/Profiles/CloudSessionProfileSlot.cs @@ -4,5 +4,6 @@ public class CloudSessionProfileSlot { public string ProfileClientId { get; set; } = null!; public string ClientId { get; set; } = null!; + public string? Identity { get; set; } public string? OriginalClientInstanceId { get; set; } -} \ No newline at end of file +} diff --git a/src/ByteSync.ServerCommon/Commands/Authentication/AuthenticateCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Authentication/AuthenticateCommandHandler.cs index 5cb94024f..6957f53d4 100644 --- a/src/ByteSync.ServerCommon/Commands/Authentication/AuthenticateCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Authentication/AuthenticateCommandHandler.cs @@ -66,7 +66,7 @@ public async Task Handle(AuthenticateRequest requ { if (client == null) { - client = new Client(request.LoginData.Identity, request.LoginData.ClientInstanceId, + client = new Client(request.LoginData.ClientId, request.LoginData.ClientInstanceId, request.LoginData.Version, request.LoginData.OsPlatform!.Value, request.IpAddress); client.Identity = request.LoginData.Identity; client.AuthenticationEpoch = AuthenticationProtocol.Epoch; @@ -75,6 +75,7 @@ public async Task Handle(AuthenticateRequest requ { if (client.Identity != request.LoginData.Identity || client.AuthenticationEpoch != AuthenticationProtocol.Epoch) return null; + client.ClientId = request.LoginData.ClientId; client.IpAddress = request.IpAddress; client.Version = request.LoginData.Version; client.OsPlatform = request.LoginData.OsPlatform.Value; diff --git a/src/ByteSync.ServerCommon/Commands/Lobbies/TryJoinLobbyCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Lobbies/TryJoinLobbyCommandHandler.cs index 058798b13..83f7280db 100644 --- a/src/ByteSync.ServerCommon/Commands/Lobbies/TryJoinLobbyCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Lobbies/TryJoinLobbyCommandHandler.cs @@ -44,7 +44,7 @@ public async Task Handle(TryJoinLobbyRequest request, Cancellat if (ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(joinLobbyParameters.PublicKeyInfo.PublicKey) != client.Identity) throw new UnauthorizedAccessException(); var authorizedProfile = await _cloudSessionProfileRepository.Get(joinLobbyParameters.CloudSessionProfileId); - if (authorizedProfile == null || authorizedProfile.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || !authorizedProfile.Slots.Any(s => s.ProfileClientId == joinLobbyParameters.ProfileClientId && s.ClientId == client.Identity)) + if (authorizedProfile == null || authorizedProfile.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || !authorizedProfile.Slots.Any(s => s.ProfileClientId == joinLobbyParameters.ProfileClientId && s.Identity == client.Identity)) throw new UnauthorizedAccessException(); JoinLobbyResult? joinLobbyResult = null; @@ -149,4 +149,4 @@ await _clientsGroupsService.AddToLobbyGroup(client, lobbyInfo.LobbyId) return joinLobbyResult!; } -} \ No newline at end of file +} diff --git a/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs b/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs index da3b4ace9..f8cb3d83d 100644 --- a/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs +++ b/src/ByteSync.ServerCommon/Services/AuthenticationChallengeService.cs @@ -61,7 +61,8 @@ public async Task VerifyAndConsume(LoginData login) private static void Validate(LoginData login) { - if (login.PublicKey == null || login.PublicKey.Length > 2048 || login.Signature == null || login.Signature.Length > 1024 || + if (string.IsNullOrWhiteSpace(login.ClientId) || login.ClientId.Length > 100 || + login.PublicKey == null || login.PublicKey.Length > 2048 || login.Signature == null || login.Signature.Length > 1024 || login.AuthenticationEpoch != AuthenticationProtocol.Epoch || login.ProtocolVersion != ProtocolVersion.CURRENT || string.IsNullOrEmpty(login.Version) || login.Version.Length > 100 || AuthenticationProtocol.GetIdentity(login.PublicKey) != login.Identity || diff --git a/src/ByteSync.ServerCommon/Services/CloudSessionProfileService.cs b/src/ByteSync.ServerCommon/Services/CloudSessionProfileService.cs index 46c957d47..144b69abd 100644 --- a/src/ByteSync.ServerCommon/Services/CloudSessionProfileService.cs +++ b/src/ByteSync.ServerCommon/Services/CloudSessionProfileService.cs @@ -50,6 +50,7 @@ public async Task CreateCloudSessionProfile(str { ProfileClientId = profileClientId, ClientId = sessionMember.ClientId, + Identity = sessionMember.Identity, OriginalClientInstanceId = sessionMember.ClientInstanceId }; @@ -86,7 +87,7 @@ public async Task CreateCloudSessionProfile(str { var cloudSessionProfileEntity = await _cloudSessionProfileRepository.Get(getCloudSessionProfileDataParameters.CloudSessionProfileId); - if (cloudSessionProfileEntity != null && cloudSessionProfileEntity.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && cloudSessionProfileEntity.Slots.Any(s => s.ClientId == sessionMemberData.ClientId)) + if (cloudSessionProfileEntity != null && cloudSessionProfileEntity.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && cloudSessionProfileEntity.Slots.Any(s => s.Identity == client.Identity)) { var result = BuildCloudSessionProfileCreationData(sessionMemberData, cloudSessionProfileEntity); @@ -102,7 +103,7 @@ public async Task CreateCloudSessionProfile(str Security.SessionAuthorizationBehavior.RequireIdentity(client); var cloudSessionProfile = await _cloudSessionProfileRepository.Get(parameters.CloudSessionProfileId); - if (cloudSessionProfile != null && cloudSessionProfile.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && cloudSessionProfile.Slots.Any(s => s.ProfileClientId == parameters.ProfileClientId && s.ClientId == client.Identity)) + if (cloudSessionProfile != null && cloudSessionProfile.AuthenticationEpoch == ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch && cloudSessionProfile.Slots.Any(s => s.ProfileClientId == parameters.ProfileClientId && s.Identity == client.Identity)) { _logger.LogInformation("GetProfileDetailsPassword: result OK for Client:{ClientInstanceId} with CloudSessionProfileId:{CloudSessionProfileId}", client.ClientInstanceId, parameters.CloudSessionProfileId); @@ -120,7 +121,7 @@ public async Task DeleteCloudSessionProfile(DeleteCloudSessionProfileParam { Security.SessionAuthorizationBehavior.RequireIdentity(byteSyncEndpoint); var profile = await _cloudSessionProfileRepository.Get(parameters.CloudSessionProfileId); - if (profile == null || profile.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || !profile.Slots.Any(s => s.ClientId == byteSyncEndpoint.Identity)) throw new UnauthorizedAccessException(); + if (profile == null || profile.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || !profile.Slots.Any(s => s.Identity == byteSyncEndpoint.Identity)) throw new UnauthorizedAccessException(); await _cloudSessionProfileRepository.Delete(parameters.CloudSessionProfileId); return true; @@ -135,9 +136,9 @@ private CloudSessionProfileData BuildCloudSessionProfileCreationData(SessionMemb cloudSessionProfileCreationData.ProfileDetailsPassword = cloudSessionProfileEntity.ProfileDetailsPassword; cloudSessionProfileCreationData.CreationDateTime = cloudSessionProfileEntity.CreationDateTime; cloudSessionProfileCreationData.RequesterProfileClientId = - cloudSessionProfileEntity.Slots.Single(s => s.ClientId == sessionMemberData.ClientId && + cloudSessionProfileEntity.Slots.Single(s => s.Identity == sessionMemberData.Identity && (s.OriginalClientInstanceId == sessionMemberData.ClientInstanceId || s.ProfileClientId == sessionMemberData.ProfileClientId)).ProfileClientId; return cloudSessionProfileCreationData; } -} \ No newline at end of file +} diff --git a/tests/ByteSync.Client.IntegrationTests/Services/Applications/EnvironmentService_Tests.cs b/tests/ByteSync.Client.IntegrationTests/Services/Applications/EnvironmentService_Tests.cs index ca0fff1d6..6afce52d8 100644 --- a/tests/ByteSync.Client.IntegrationTests/Services/Applications/EnvironmentService_Tests.cs +++ b/tests/ByteSync.Client.IntegrationTests/Services/Applications/EnvironmentService_Tests.cs @@ -137,17 +137,18 @@ public void ApplicationVersion_uses_override_when_argument_present_otherwise_ass } [Test] - public void SetClientId_sets_ids_and_instance_contains_guid() + public void SetClientIdentity_preserves_readable_id_and_binds_instance_to_identity() { var service = new EnvironmentService(new MsixPfnParser()); - var clientId = new string('A', 64); - service.SetClientId(clientId); + var clientId = "ABCD-EFG-HIJ"; + var identity = new string('A', 64); + service.SetClientIdentity(clientId, identity); service.ClientId.Should().Be(clientId); - service.ClientInstanceId.Should().StartWith(clientId + "_"); + service.ClientInstanceId.Should().StartWith(identity + "_"); - var suffix = service.ClientInstanceId.Substring(clientId.Length + 1); + var suffix = service.ClientInstanceId.Substring(identity.Length + 1); Guid.TryParse(suffix, out _).Should().BeTrue(); } } diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysManagerTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysManagerTests.cs index 39fb3075f..01a894c5f 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysManagerTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysManagerTests.cs @@ -1,5 +1,6 @@ using System.Security.Cryptography; using System.Text; +using ByteSync.Business.Communications; using ByteSync.Business.Configurations; using ByteSync.Common.Business.EndPoints; using ByteSync.Common.Business.Versions; @@ -80,6 +81,25 @@ public void GetMyPublicKeyInfo_ShouldIncludePublicKey() result.PublicKey.Should().BeEquivalentTo(applicationSettings.DecodedRsaPublicKey); } + + [TestCase(false)] + [TestCase(true)] + public void ExistingReadableAliasTrust_RequiresThePreviouslyTrustedKey(bool differentKey) + { + var settings = _applicationSettingsRepository.Object.GetCurrentApplicationSettings(); + var trustedKey = settings.DecodedRsaPublicKey!; + settings.InitializeTrustedPublicKeys(); + settings.AddTrustedKey(new TrustedPublicKey { ClientId = "ABCD-EFG-HIJ", PublicKey = trustedKey, + ValidationDate = DateTimeOffset.UtcNow }); + using var otherKey = RSA.Create(2048); + var peer = new PublicKeyInfo { ClientId = "ABCD-EFG-HIJ", + PublicKey = differentKey ? otherKey.ExportRSAPublicKey() : trustedKey }; + + var trusted = _publicKeysManager.IsTrusted(peer); + + trusted.Should().Be(!differentKey); + settings.DecodedTrustedPublicKeys.Should().ContainSingle().Which.PublicKey.Should().Equal(trustedKey); + } [Test] public void BuildJoinerPublicKeyCheckData_ShouldIncludeProtocolVersion() @@ -115,4 +135,4 @@ public void BuildMemberPublicKeyCheckData_ShouldIncludeProtocolVersion() result.ProtocolVersion.Should().Be(ProtocolVersion.CURRENT); } -} \ No newline at end of file +} diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysTrusterTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysTrusterTests.cs index f8714a102..82da58a1b 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysTrusterTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysTrusterTests.cs @@ -48,6 +48,8 @@ public void SetUp() .Setup(e => e.ClientId) .Returns("TestClientId"); + _environmentService.SetupGet(e => e.Identity).Returns(new string('A', 64)); + _environmentService .Setup(e => e.ClientInstanceId) .Returns("TestClientInstanceId"); @@ -74,6 +76,29 @@ public void SetUp() } + [Test] + public async Task TrustCheck_SkipsOnlyInstancesOfTheCryptographicIdentity() + { + const string alias = "ABCD-EFG-HIJ"; + var identity = new string('A', 64); + var ownInstance = identity + "_" + Guid.NewGuid().ToString("D"); + var aliasInstance = alias + "_" + Guid.NewGuid().ToString("D"); + var otherInstance = new string('B', 64) + "_" + Guid.NewGuid().ToString("D"); + _environmentService.SetupGet(e => e.ClientId).Returns(alias); + _environmentService.SetupGet(e => e.Identity).Returns(identity); + _sessionMemberApiClient.Setup(c => c.GetMembersClientInstanceIds("session", It.IsAny())) + .ReturnsAsync([ownInstance, aliasInstance, otherInstance]); + _trustApiClient.Setup(c => c.StartTrustCheck(It.IsAny(), It.IsAny())) + .ReturnsAsync(new StartTrustCheckResult { IsOK = false }); + + await _publicKeysTruster.TrustAllMembersPublicKeys("session"); + + _trustApiClient.Verify(c => c.StartTrustCheck(It.Is(p => + p.MembersInstanceIdsToCheck.Count == 2 && p.MembersInstanceIdsToCheck.Contains(aliasInstance) && + p.MembersInstanceIdsToCheck.Contains(otherInstance) && !p.MembersInstanceIdsToCheck.Contains(ownInstance)), + It.IsAny()), Times.Once); + } + [Test] public async Task OnTrustPublicKeyRequestedAsync_WithIncompatibleProtocolVersion_ShouldThrowInvalidOperationException() { diff --git a/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs b/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs index 4237badba..9f84548f2 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs @@ -14,6 +14,7 @@ using ByteSync.Interfaces.Services.Communications; using ByteSync.Services.Communications; using ByteSync.Services.Communications.Api; +using ByteSync.Services.Applications; using FluentAssertions; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -42,6 +43,74 @@ public void SetUp() [TearDown] public void TearDown() => _settings.PrivateRsa.Dispose(); + [Test] + public void EnvironmentInitialization_PreservesTheStoredReadableIdAndExistingKeys() + { + var clientId = _settings.ClientId; + var publicKey = _settings.DecodedRsaPublicKey!.ToArray(); + var privateKey = _settings.DecodedRsaPrivateKey!.ToArray(); + _settings.InitializeTrustedPublicKeys(); + _settings.AddTrustedKey(new TrustedPublicKey { ClientId = "PEER-CLI-ENT", PublicKey = _settings.DecodedRsaPublicKey!, + ValidationDate = DateTimeOffset.UtcNow }); + var trustedKeys = _settings.TrustedPublicKeys; + var identity = AuthenticationProtocol.GetIdentity(publicKey); + var environment = new EnvironmentService(Mock.Of()); + + environment.SetClientIdentity(clientId, identity); + + environment.ClientId.Should().Be(clientId).And.MatchRegex("^[A-Z]{4}-[A-Z]{3}-[A-Z]{3}$"); + environment.Identity.Should().Be(identity).And.NotBe(clientId); + AuthenticationProtocol.IsInstanceOf(environment.ClientInstanceId, identity).Should().BeTrue(); + _settings.ClientId.Should().Be(clientId); + _settings.DecodedRsaPublicKey.Should().Equal(publicKey); + _settings.DecodedRsaPrivateKey.Should().Equal(privateKey); + _settings.TrustedPublicKeys.Should().Be(trustedKeys); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("ABCD-EFG-HIJ")] + [TestCase("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] + public void EnvironmentInitialization_RejectsAnAliasOrInvalidFingerprintAsIdentity(string? identity) + { + var environment = new EnvironmentService(Mock.Of()); + + var act = () => environment.SetClientIdentity(_settings.ClientId, identity!); + + act.Should().Throw(); + } + + [TestCase(null)] + [TestCase("")] + [TestCase(" ")] + public void EnvironmentInitialization_RejectsAMissingReadableId(string? clientId) + { + var environment = new EnvironmentService(Mock.Of()); + var identity = AuthenticationProtocol.GetIdentity(_settings.DecodedRsaPublicKey!); + + var act = () => environment.SetClientIdentity(clientId!, identity); + + act.Should().Throw(); + } + + [Test] + public void TwoInstallationsWithOneKey_KeepDistinctAliasesAndInstancesOfTheSameIdentity() + { + var identity = AuthenticationProtocol.GetIdentity(_settings.DecodedRsaPublicKey!); + var first = new EnvironmentService(Mock.Of()); + var second = new EnvironmentService(Mock.Of()); + + first.SetClientIdentity("ABCD-EFG-HIJ", identity); + second.SetClientIdentity("KLMN-OPQ-RST", identity); + + first.ClientId.Should().Be("ABCD-EFG-HIJ"); + second.ClientId.Should().Be("KLMN-OPQ-RST"); + first.Identity.Should().Be(second.Identity); + first.ClientInstanceId.Should().NotBe(second.ClientInstanceId); + AuthenticationProtocol.IsInstanceOf(first.ClientInstanceId, identity).Should().BeTrue(); + AuthenticationProtocol.IsInstanceOf(second.ClientInstanceId, identity).Should().BeTrue(); + } + [TestCase(false)] [TestCase(true)] public async Task OlderRelayWithoutChallengeEndpoint_IsRejectedWithoutCallingLegacyLogin(bool wrapped) @@ -133,8 +202,15 @@ public async Task LoginEndpointNotFound_IsNotReportedAsAMissingChallengeEndpoint [Test] public async Task CurrentRelay_ReceivesAValidProofWithTheCurrentEpochAndProtocol() { + var clientId = _settings.ClientId; + var publicKeyBeforeLogin = _settings.DecodedRsaPublicKey!.ToArray(); + var privateKeyBeforeLogin = _settings.DecodedRsaPrivateKey!.ToArray(); + _settings.InitializeTrustedPublicKeys(); + _settings.AddTrustedKey(new TrustedPublicKey { ClientId = "PEER-CLI-ENT", PublicKey = _settings.DecodedRsaPublicKey!, + ValidationDate = DateTimeOffset.UtcNow }); + var trustedKeys = _settings.TrustedPublicKeys; var identity = AuthenticationProtocol.GetIdentity(_settings.DecodedRsaPublicKey!); - var login = new LoginData { ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), Version = "local-test" }; + var login = new LoginData { ClientId = "caller-supplied-alias", ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), Version = "local-test" }; var challenge = new AuthenticationChallenge { Id = Guid.NewGuid().ToString("N"), Nonce = "local-test-nonce", ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(2) }; var response = new InitialAuthenticationResponse(InitialConnectionStatus.Success); var sequence = new MockSequence(); @@ -146,6 +222,11 @@ public async Task CurrentRelay_ReceivesAValidProofWithTheCurrentEpochAndProtocol var result = await _client.Login(login); result.Should().BeSameAs(response); + login.ClientId.Should().Be(clientId).And.NotBe(identity); + _settings.ClientId.Should().Be(clientId); + _settings.DecodedRsaPublicKey.Should().Equal(publicKeyBeforeLogin); + _settings.DecodedRsaPrivateKey.Should().Equal(privateKeyBeforeLogin); + _settings.TrustedPublicKeys.Should().Be(trustedKeys); login.Identity.Should().Be(identity); login.ProtocolVersion.Should().Be(ProtocolVersion.CURRENT); login.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); diff --git a/tests/ByteSync.ServerCommon.Tests/Integration/AuthenticationChallengeRedis60Tests.cs b/tests/ByteSync.ServerCommon.Tests/Integration/AuthenticationChallengeRedis60Tests.cs index ae1d85a32..5dd9c5b14 100644 --- a/tests/ByteSync.ServerCommon.Tests/Integration/AuthenticationChallengeRedis60Tests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Integration/AuthenticationChallengeRedis60Tests.cs @@ -55,7 +55,7 @@ public void SetUp() private LoginData Login() { var identity = AuthenticationProtocol.GetIdentity(_key.ExportRSAPublicKey()); - return new LoginData { Identity = identity, ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), + return new LoginData { ClientId = "ABCD-EFG-HIJ", Identity = identity, ClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), PublicKey = _key.ExportRSAPublicKey(), AuthenticationEpoch = AuthenticationProtocol.Epoch, ProtocolVersion = ProtocolVersion.CURRENT, Version = "local-redis60-test" }; } diff --git a/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs index 6c0834595..974ecc944 100644 --- a/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Security/AuthenticationSecurityTests.cs @@ -63,6 +63,80 @@ private void Sign(LoginData login, AuthenticationChallenge challenge) login.Signature = _key.SignData(AuthenticationProtocol.GetMessage(login, challenge), HashAlgorithmName.SHA256, RSASignaturePadding.Pss); } + [Test] + public async Task ReadableAlias_CannotMergeDifferentKeysOrClaimALegacyRecord() + { + using var first = new AuthenticationTestIdentity(); + using var second = new AuthenticationTestIdentity(first.ClientId); + var legacy = new Client(first.ClientId, "legacy-instance", "old", OSPlatforms.Windows, "127.0.0.1"); + var records = new Dictionary { [legacy.ClientInstanceId] = legacy }; + var clients = A.Fake(); + A.CallTo(() => clients.AddOrUpdate(A._, A>._)) + .ReturnsLazily((string instance, Func update) => + { + var updated = update(records.GetValueOrDefault(instance)); + if (updated != null) records[instance] = updated; + return UpdateResultBuilder.BuildAddOrUpdateResult(updated, false); + }); + var versions = A.Fake(); + A.CallTo(() => versions.IsClientVersionAllowed(A._)).Returns(true); + var tokens = new TokensFactory(Options.Create(new AppSettings + { + Secret = "offline-alias-collision-signing-key-at-least-32-bytes", JwtDurationInSeconds = 300 + })); + var handler = new AuthenticateCommandHandler(tokens, new ByteSync.ServerCommon.Factories.ByteSyncEndpointFactory(), clients, versions, _service); + + foreach (var identity in new[] { first, second }) + { + var login = identity.CreateLogin(); + identity.Sign(login, await _service.Create(login)); + var response = await handler.Handle(new AuthenticateRequest(login, "127.0.0.1"), CancellationToken.None); + response.IsSuccess.Should().BeTrue(); + response.EndPoint!.ClientId.Should().Be(first.ClientId); + response.EndPoint.ClientInstanceId.Should().Be(identity.ClientInstanceId); + } + + records.Should().HaveCount(3); + records[first.ClientInstanceId].Identity.Should().Be(first.Identity); + records[second.ClientInstanceId].Identity.Should().Be(second.Identity).And.NotBe(first.Identity); + records[legacy.ClientInstanceId].Should().BeSameAs(legacy); + legacy.Identity.Should().BeNull(); + legacy.AuthenticationEpoch.Should().Be(0); + var takeover = second.CreateLogin(); + takeover.ClientInstanceId = first.ClientInstanceId; + var act = () => _service.Create(takeover); + await act.Should().ThrowAsync(); + } + + [Test] + public async Task ClientAliasChangedAfterChallenge_IsRejectedEvenWithANewValidSignature() + { + using var identity = new AuthenticationTestIdentity(); + var login = identity.CreateLogin(); + var challenge = await _service.Create(login); + login.ClientId = "KLMN-OPQ-RST"; + identity.Sign(login, challenge); + + var accepted = await _service.VerifyAndConsume(login); + + accepted.Should().BeFalse(); + _store.Should().BeEmpty(); + } + + [TestCase(null)] + [TestCase("")] + [TestCase(" ")] + public async Task MissingClientAlias_CannotCreateAChallenge(string? clientId) + { + var login = Login(); + login.ClientId = clientId!; + + var act = () => _service.Create(login); + + await act.Should().ThrowAsync(); + _store.Should().BeEmpty(); + } + [Test] public async Task IntegrationIdentity_UsesSignedChallengesAndProducesRefreshableCurrentEpochTokens() { @@ -71,7 +145,7 @@ public async Task IntegrationIdentity_UsesSignedChallengesAndProducesRefreshable var keyInfo = identity.CreatePublicKeyInfo(); AuthenticationProtocol.GetIdentity(keyInfo.PublicKey).Should().Be(identity.Identity); keyInfo.ProtocolVersion.Should().Be(ProtocolVersion.CURRENT); - keyInfo.ClientId.Should().Be(identity.Identity); + keyInfo.ClientId.Should().Be(identity.ClientId).And.NotBe(identity.Identity); identity.Sign(login, await _service.Create(login)); Client? saved = null; var clients = A.Fake(); @@ -88,7 +162,7 @@ public async Task IntegrationIdentity_UsesSignedChallengesAndProducesRefreshable { Secret = "offline-fixture-validation-signing-key-at-least-32-bytes", JwtDurationInSeconds = 300 })); - var handler = new AuthenticateCommandHandler(tokens, A.Fake(), clients, versions, _service); + var handler = new AuthenticateCommandHandler(tokens, new ByteSync.ServerCommon.Factories.ByteSyncEndpointFactory(), clients, versions, _service); var response = await handler.Handle(new AuthenticateRequest(login, "127.0.0.1"), CancellationToken.None); var originalRefresh = response.AuthenticationTokens!.RefreshToken; @@ -97,7 +171,12 @@ public async Task IntegrationIdentity_UsesSignedChallengesAndProducesRefreshable var replay = await handler.Handle(new AuthenticateRequest(login, "127.0.0.1"), CancellationToken.None); response.IsSuccess.Should().BeTrue(); + saved!.ClientId.Should().Be(identity.ClientId); + response.EndPoint!.ClientId.Should().Be(identity.ClientId); saved!.Identity.Should().Be(identity.Identity); + var jwt = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().ReadJwtToken(response.AuthenticationTokens.JwtToken); + jwt.Claims.Single(c => c.Type == AuthConstants.CLAIM_CLIENT_ID).Value.Should().Be(identity.ClientId); + jwt.Claims.Single(c => c.Type == AuthConstants.CLAIM_IDENTITY).Value.Should().Be(identity.Identity); saved.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); refreshed.RefreshTokensStatus.Should().Be(RefreshTokensStatus.RefreshTokenOk); refreshed.AuthenticationTokens!.RefreshToken.Should().NotBe(originalRefresh); @@ -131,6 +210,7 @@ public async Task Login_WithDurableKey_AllowsDistinctInstancesAndRejectsReplay() [TestCase("version")] [TestCase("epoch")] [TestCase("protocol")] + [TestCase("client-id")] public async Task Login_WithAlteredProof_IsRejected(string field) { var login = Login(); @@ -145,6 +225,7 @@ public async Task Login_WithAlteredProof_IsRejected(string field) case "version": login.Version = "other"; break; case "epoch": login.AuthenticationEpoch = 0; break; case "protocol": login.ProtocolVersion = 2; break; + case "client-id": login.ClientId = "OTHER-CLI-ENT"; break; } (await _service.VerifyAndConsume(login)).Should().BeFalse(); diff --git a/tests/ByteSync.ServerCommon.Tests/Security/LoginIdentityBindingSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/LoginIdentityBindingSecurityTests.cs index bf7003d06..a2347b49d 100644 --- a/tests/ByteSync.ServerCommon.Tests/Security/LoginIdentityBindingSecurityTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Security/LoginIdentityBindingSecurityTests.cs @@ -43,7 +43,7 @@ public async Task Login_CannotAdoptAnExistingInstanceOrLegacyClientAlias(string result.IsSuccess.Should().Be(expected); if (expected) { - saved!.ClientId.Should().Be(identity); + saved!.ClientId.Should().Be(login.ClientId); saved.Identity.Should().Be(identity); saved.Version.Should().Be(login.Version); saved.AuthenticationEpoch.Should().Be(AuthenticationProtocol.Epoch); diff --git a/tests/ByteSync.ServerCommon.Tests/Security/ProfileAuthorizationSecurityTests.cs b/tests/ByteSync.ServerCommon.Tests/Security/ProfileAuthorizationSecurityTests.cs index 35d326eee..80f8ab4e4 100644 --- a/tests/ByteSync.ServerCommon.Tests/Security/ProfileAuthorizationSecurityTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Security/ProfileAuthorizationSecurityTests.cs @@ -3,9 +3,14 @@ using ByteSync.Common.Business.Profiles; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Business.Sessions; +using ByteSync.ServerCommon.Commands.Lobbies; using ByteSync.ServerCommon.Entities; +using ByteSync.ServerCommon.Interfaces.Factories; using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Services; +using ByteSync.ServerCommon.Interfaces.Services.Clients; using ByteSync.ServerCommon.Services; +using ByteSync.TestsCommon.TestHelpers; using FakeItEasy; using FluentAssertions; using Microsoft.Extensions.Logging.Abstractions; @@ -14,21 +19,23 @@ namespace ByteSync.ServerCommon.Tests.Security; public class ProfileAuthorizationSecurityTests { - private static Client Client() => new() { Identity = new string('A', 64), ClientId = new string('A', 64), + private static Client Client() => new() { Identity = new string('A', 64), ClientId = "ABCD-EFG-HIJ", AuthenticationEpoch = AuthenticationProtocol.Epoch, ClientInstanceId = new string('A', 64) + "_" + Guid.NewGuid().ToString("D") }; [TestCase("owned")] [TestCase("other-key")] [TestCase("legacy-profile")] + [TestCase("missing-identity")] public async Task ProfileSecretsAndDeletion_RequireCurrentEpochAndFingerprintOwnership(string scenario) { var client = Client(); var profiles = A.Fake(); var profile = new CloudSessionProfileEntity { AuthenticationEpoch = AuthenticationProtocol.Epoch, CloudSessionProfileId = "profile", ProfileDetailsPassword = "local-test-only-value" }; - profile.Slots.Add(new CloudSessionProfileSlot { ClientId = client.Identity!, ProfileClientId = "slot" }); - if (scenario == "other-key") profile.Slots[0].ClientId = new string('B', 64); + profile.Slots.Add(new CloudSessionProfileSlot { ClientId = client.ClientId, Identity = client.Identity, ProfileClientId = "slot" }); + if (scenario == "other-key") profile.Slots[0].Identity = new string('B', 64); if (scenario == "legacy-profile") profile.AuthenticationEpoch = 0; + if (scenario == "missing-identity") profile.Slots[0].Identity = null; A.CallTo(() => profiles.Get("profile")).Returns(profile); var service = new CloudSessionProfileService(profiles, A.Fake(), NullLogger.Instance); @@ -49,11 +56,46 @@ public async Task ProfileSecretsAndDeletion_RequireCurrentEpochAndFingerprintOwn } } + [TestCase("other-key")] + [TestCase("missing-identity")] + [TestCase("legacy-profile")] + public async Task MatchingReadableAlias_CannotReadProfileDataOrJoinItsLobby(string scenario) + { + using var identity = new AuthenticationTestIdentity(); + var client = new Client { ClientId = identity.ClientId, Identity = identity.Identity, + ClientInstanceId = identity.ClientInstanceId, AuthenticationEpoch = AuthenticationProtocol.Epoch }; + var session = new CloudSessionData { AuthenticationEpoch = AuthenticationProtocol.Epoch }; + var member = new SessionMemberData { ClientId = client.ClientId, Identity = client.Identity, + ClientInstanceId = client.ClientInstanceId, CloudSessionData = session, ProfileClientId = "slot" }; + var profile = new CloudSessionProfileEntity { CloudSessionProfileId = "profile", + AuthenticationEpoch = scenario == "legacy-profile" ? 0 : AuthenticationProtocol.Epoch }; + profile.Slots.Add(new CloudSessionProfileSlot { ClientId = client.ClientId, ProfileClientId = "slot", + Identity = scenario == "other-key" ? new string('B', 64) : scenario == "missing-identity" ? null : client.Identity }); + var profiles = A.Fake(); + A.CallTo(() => profiles.Get("profile")).Returns(profile); + var sessions = A.Fake(); + A.CallTo(() => sessions.GetSessionMember("session", client.ClientInstanceId)).Returns(member); + var service = new CloudSessionProfileService(profiles, sessions, NullLogger.Instance); + var redis = A.Fake(); + var lobby = new TryJoinLobbyCommandHandler(profiles, A.Fake(), A.Fake(), + A.Fake(), A.Fake(), redis, NullLogger.Instance); + + var details = await service.GetCloudSessionProfileData(new GetCloudSessionProfileDataParameters + { SessionId = "session", CloudSessionProfileId = "profile" }, client); + var join = () => lobby.Handle(new TryJoinLobbyRequest(new JoinLobbyParameters + { CloudSessionProfileId = "profile", ProfileClientId = "slot", PublicKeyInfo = identity.CreatePublicKeyInfo() }, client), CancellationToken.None); + + details.Should().BeNull(); + await join.Should().ThrowAsync(); + A.CallTo(() => redis.OpenTransaction()).MustNotHaveHappened(); + } + [Test] public async Task TwoInstancesOfOneIdentity_ReceiveDistinctProfileSlots() { var first = Client(); var second = Client(); + second.ClientId = "KLMN-OPQ-RST"; var session = new CloudSessionData { SessionId = "session", AuthenticationEpoch = AuthenticationProtocol.Epoch }; foreach (var client in new[] { first, second }) session.SessionMembers.Add(new SessionMemberData { ClientInstanceId = client.ClientInstanceId, ClientId = client.ClientId, Identity = client.Identity, CloudSessionData = session }); @@ -77,5 +119,8 @@ public async Task TwoInstancesOfOneIdentity_ReceiveDistinctProfileSlots() saved!.Slots.Should().HaveCount(2); saved.Slots.Select(s => s.ProfileClientId).Should().OnlyHaveUniqueItems(); saved.Slots.Select(s => s.OriginalClientInstanceId).Should().BeEquivalentTo(first.ClientInstanceId, second.ClientInstanceId); + saved.Slots.Should().OnlyContain(s => s.Identity == first.Identity); + saved.Slots[0].ClientId.Should().Be(first.ClientId); + saved.Slots[1].ClientId.Should().Be(second.ClientId); } } diff --git a/tests/ByteSync.TestsCommon/TestHelpers/AuthenticationTestIdentity.cs b/tests/ByteSync.TestsCommon/TestHelpers/AuthenticationTestIdentity.cs index 1cb01942e..1afb46b45 100644 --- a/tests/ByteSync.TestsCommon/TestHelpers/AuthenticationTestIdentity.cs +++ b/tests/ByteSync.TestsCommon/TestHelpers/AuthenticationTestIdentity.cs @@ -10,18 +10,20 @@ public sealed class AuthenticationTestIdentity : IDisposable { private readonly RSA _key = RSA.Create(2048); - public AuthenticationTestIdentity() + public AuthenticationTestIdentity(string clientId = "ABCD-EFG-HIJ") { + ClientId = clientId; Identity = AuthenticationProtocol.GetIdentity(_key.ExportRSAPublicKey()); ClientInstanceId = $"{Identity}_{Guid.NewGuid():D}"; } public string Identity { get; } + public string ClientId { get; } public string ClientInstanceId { get; } public LoginData CreateLogin() => new() { - ClientId = Identity, + ClientId = ClientId, Identity = Identity, ClientInstanceId = ClientInstanceId, PublicKey = _key.ExportRSAPublicKey(), @@ -33,7 +35,7 @@ public AuthenticationTestIdentity() public PublicKeyInfo CreatePublicKeyInfo() => new() { - ClientId = Identity, + ClientId = ClientId, PublicKey = _key.ExportRSAPublicKey(), ProtocolVersion = ProtocolVersion.CURRENT }; From 097a36560d39367c0504fae5e5059fe30a34c572 Mon Sep 17 00:00:00 2001 From: Paul Fresquet Date: Sun, 22 Nov 2026 10:16:32 +0100 Subject: [PATCH 7/8] fix: authenticate peer trust confirmations [skip ci] --- docs/security-boundaries.md | 12 ++ .../PeerTrustProcessData.cs | 15 +- .../TrustProcessPublicKeysData.cs | 36 ++-- .../ITrustProcessPublicKeysRepository.cs | 4 +- .../Communications/PublicKeysTruster.cs | 7 +- .../TrustProcessPublicKeysRepository.cs | 13 +- .../PublicKeyValidationParameters.cs | 5 +- ...icKeyValidationIsFinishedCommandHandler.cs | 30 +++- .../Communications/PublicKeysTrusterTests.cs | 32 +++- .../AuthProtocolCompatibilityTests.cs | 100 ++++++++++++ ...ValidationIsFinishedCommandHandlerTests.cs | 154 ++++++++++++------ 11 files changed, 317 insertions(+), 91 deletions(-) diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md index 57604c333..2c2153b6d 100644 --- a/docs/security-boundaries.md +++ b/docs/security-boundaries.md @@ -197,6 +197,18 @@ Offline validation: solution build succeeded with zero errors. **1,816 tests pas Combined client/server coverage covers 20 of the 22 changed executable production lines (90.9%); the two bootstrap wiring lines were not executed. `AuthApiClient`, `AuthenticationChallengeService`, `CloudSessionProfileService` and the shared RSA fixture helper have 100% line coverage in these runs. This local change metric does not establish the PR-wide Sonar coverage gate. Evidence is under `artifacts/clientid-identity/`, including `validation.json`, TRX and coverage files. No Azure endpoint was contacted and Docker was not started. The same PR branch receives the correction with `[skip ci]` to avoid Azure/container workflows. +## Authenticated trust confirmations (2026-11-22) + +Trust completion notifications no longer select a pending exchange by readable ClientId. The relay derives the issuer instance, full fingerprint and display alias from the authenticated client, replacing caller-supplied issuer metadata. It checks the current session epoch/protocol/state, sender membership or an unexpired join attempt, recipient eligibility, the recipient public key and a bounded nonempty exchange identifier before forwarding. + +Both client roles register the expected peer instance, canonical RSA fingerprint and the salt already shared by their public-key check exchange. A received confirmation must match all three values within the current session and target the local instance. Identical readable aliases, including distinct instances of one key, remain independent. The first confirmation consumes the pending response; duplicate registration of the same exchange preserves that state, while a new salt replaces the expected exchange and rejects older confirmations. The readable ClientId and existing saved peer trust remain unchanged. + +This update addresses P1 only. It does not change manual key renewal. The extended notification requires matched builds of this unreleased V3 PR; missing identity/exchange fields cannot use an alias fallback. + +Validation: the solution, including integration fixtures, builds with zero errors. **1,850 offline tests pass, zero failures**: 1,299 client, 431 server (excluding service-dependent repository/integration suites), 66 Functions and 54 Common. These are 34 additional cases compared with the preceding PR head. Twelve existing POSIX-only client cases did not execute on Windows. Coverage reaches 56 of 57 changed executable production lines (98.2%); the trust-confirmation handler has 100% line coverage. This does not establish the PR-wide Sonar gate. Integration/E2E services were not exercised. Restore used the local package cache; no Azure endpoint was contacted and Docker was not started. + +Evidence is retained locally under `artifacts/pr351-p1/` in the original checkout, including TRX, coverage and `validation.json`. The correction uses `[skip ci]` to avoid Azure/container workflows after pushing to the same PR. + ## Future rollout proposal (not executed) 1. Review this patch and approve the breaking protocol, restrictions and enrollment experience. Complete native multi-platform CI, isolated Redis/SignalR/storage end-to-end tests, load/abuse checks and the coverage gate. Confirm the Redis version before rollout. Back up local RSA/settings/trust/profile data through the existing supported process; do not collect private keys centrally. diff --git a/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/PeerTrustProcessData.cs b/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/PeerTrustProcessData.cs index 7af6fe332..de2e77bdd 100644 --- a/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/PeerTrustProcessData.cs +++ b/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/PeerTrustProcessData.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; namespace ByteSync.Business.Communications.PublicKeysTrusting; @@ -19,6 +19,19 @@ public PeerTrustProcessData(string otherPartyClientId) SyncRoot = new object(); } + public PeerTrustProcessData(ByteSync.Common.Business.EndPoints.PublicKeyCheckData peer) : this(peer.IssuerPublicKeyInfo.ClientId) + { + OtherPartyIdentity = ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(peer.IssuerPublicKeyInfo.PublicKey); + OtherPartyClientInstanceId = peer.IssuerClientInstanceId; + ExchangeId = peer.Salt; + if (!ByteSync.Common.Business.Auth.AuthenticationProtocol.IsInstanceOf(OtherPartyClientInstanceId, OtherPartyIdentity) || + string.IsNullOrWhiteSpace(ExchangeId) || ExchangeId.Length > 128) + throw new ArgumentException("Invalid peer trust exchange", nameof(peer)); + } + + public string? OtherPartyClientInstanceId { get; } + public string? OtherPartyIdentity { get; } + public string? ExchangeId { get; } public string OtherPartyClientId { get; } public bool HasOtherPartyValidatedPublicKey diff --git a/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/TrustProcessPublicKeysData.cs b/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/TrustProcessPublicKeysData.cs index 901903bef..2725f3f80 100644 --- a/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/TrustProcessPublicKeysData.cs +++ b/src/ByteSync.Client/Business/Communications/PublicKeysTrusting/TrustProcessPublicKeysData.cs @@ -1,6 +1,4 @@ -using Serilog; - -namespace ByteSync.Business.Communications.PublicKeysTrusting; +namespace ByteSync.Business.Communications.PublicKeysTrusting; public class TrustProcessPublicKeysData { @@ -23,26 +21,22 @@ public TrustProcessPublicKeysData(string sessionId) public SessionMemberTrustProcessData SessionMemberTrustProcessData { get; } - public void AddPeerTrustProcessData(PeerTrustProcessData peerTrustProcessData) + public PeerTrustProcessData AddPeerTrustProcessData(PeerTrustProcessData peer) { - if (PeerTrustProcessDatas.ContainsKey(peerTrustProcessData.OtherPartyClientId)) - { - PeerTrustProcessDatas.Remove(peerTrustProcessData.OtherPartyClientId); - } - - PeerTrustProcessDatas.Add(peerTrustProcessData.OtherPartyClientId, peerTrustProcessData); + var instance = peer.OtherPartyClientInstanceId!; + if (PeerTrustProcessDatas.TryGetValue(instance, out var existing) && + existing.OtherPartyIdentity == peer.OtherPartyIdentity && existing.ExchangeId == peer.ExchangeId) + return existing; + PeerTrustProcessDatas[instance] = peer; + return peer; } - public void SetOtherPartyChecked(string issuerClientId, bool isValidated) + public void SetOtherPartyChecked(ByteSync.Common.Business.Sessions.Cloud.Connections.PublicKeyValidationParameters parameters) { - PeerTrustProcessData? peerTrustProcessData; - if (PeerTrustProcessDatas.TryGetValue(issuerClientId, out peerTrustProcessData)) - { - peerTrustProcessData.SetOtherPartyChecked(isValidated); - } - else - { - Log.Warning("Can not find PeerTrustProcessData with ClientId {issuerClientId}", issuerClientId); - } + if (parameters.IssuerClientInstanceId != null && + PeerTrustProcessDatas.TryGetValue(parameters.IssuerClientInstanceId, out var peer) && + peer.OtherPartyIdentity == parameters.IssuerIdentity && peer.ExchangeId == parameters.ExchangeId && + !peer.OtherPartyHasFinished()) + peer.SetOtherPartyChecked(parameters.IsValidated); } -} \ No newline at end of file +} diff --git a/src/ByteSync.Client/Interfaces/Controls/Communications/ITrustProcessPublicKeysRepository.cs b/src/ByteSync.Client/Interfaces/Controls/Communications/ITrustProcessPublicKeysRepository.cs index 1e18a3992..9dcd4756a 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Communications/ITrustProcessPublicKeysRepository.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Communications/ITrustProcessPublicKeysRepository.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Threading.Tasks; using ByteSync.Business.Communications.PublicKeysTrusting; using ByteSync.Common.Business.EndPoints; @@ -17,7 +17,7 @@ public interface ITrustProcessPublicKeysRepository : IRepository IsFullyTrusted(string sessionId, string memberInstanceId); - Task ResetPeerTrustProcessData(string sessionId, string otherPartyClientId); + Task ResetPeerTrustProcessData(string sessionId, PublicKeyCheckData peer); Task ResetJoinerTrustProcessData(string sessionId); diff --git a/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs b/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs index fd3f601ef..64ccea518 100644 --- a/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs +++ b/src/ByteSync.Client/Services/Communications/PublicKeysTruster.cs @@ -142,7 +142,7 @@ public async Task OnTrustPublicKeyRequestedAsync(RequestTrustProcessParameters r // Reset the peer trust process data var peerTrustProcessData = await _trustProcessPublicKeysRepository.ResetPeerTrustProcessData( - requestTrustProcessParameters.SessionId, myPublicKeyCheckData.OtherPartyPublicKeyInfo!.ClientId); + requestTrustProcessParameters.SessionId, requestTrustProcessParameters.JoinerPublicKeyCheckData); var trustDataParameters = new TrustDataParameters(1, 1, false, requestTrustProcessParameters.SessionId, peerTrustProcessData); var addTrustedClientViewModel = _flyoutElementViewModelFactory.BuilAddTrustedClientViewModel( @@ -152,7 +152,7 @@ public async Task OnTrustPublicKeyRequestedAsync(RequestTrustProcessParameters r public async Task OnPublicKeyValidationIsFinishedAsync(PublicKeyValidationParameters publicKeyValidationParameters) { - if (publicKeyValidationParameters.OtherPartyClientInstanceId.Equals(_environmentService.ClientInstanceId)) + if (publicKeyValidationParameters.OtherPartyClientInstanceId == _environmentService.ClientInstanceId) { await _trustProcessPublicKeysRepository.SetOtherPartyChecked(publicKeyValidationParameters.SessionId, publicKeyValidationParameters); @@ -164,6 +164,7 @@ public async Task OnPublicKeyValidationFinished(PublicKeyCheckData publicKeyChec { var parameters = new PublicKeyValidationParameters(); + parameters.ExchangeId = publicKeyCheckData.Salt; parameters.IsValidated = isValidated; parameters.SessionId = trustDataParameters.SessionId; parameters.IssuerClientId = _publicKeysManager.GetMyPublicKeyInfo().ClientId; @@ -227,7 +228,7 @@ private async Task DoTrustMembersPublicKeys(string sessionId, cpt += 1; var peerTrustProcessData = await _trustProcessPublicKeysRepository - .ResetPeerTrustProcessData(sessionId, publicKeyCheckData.IssuerPublicKeyInfo.ClientId); + .ResetPeerTrustProcessData(sessionId, publicKeyCheckData); var trustDataParameters = new TrustDataParameters(cpt, keysToTrust.Count, true, sessionId, peerTrustProcessData); var addTrustedClientViewModel = _flyoutElementViewModelFactory.BuilAddTrustedClientViewModel( diff --git a/src/ByteSync.Client/Services/Communications/TrustProcessPublicKeysRepository.cs b/src/ByteSync.Client/Services/Communications/TrustProcessPublicKeysRepository.cs index 34aa910e9..c2e2ad63a 100644 --- a/src/ByteSync.Client/Services/Communications/TrustProcessPublicKeysRepository.cs +++ b/src/ByteSync.Client/Services/Communications/TrustProcessPublicKeysRepository.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Threading; using ByteSync.Business.Communications.PublicKeysTrusting; using ByteSync.Common.Business.EndPoints; @@ -39,15 +39,12 @@ public async Task IsFullyTrusted(string sessionId, string memberInstanceId .FullyTrustedPublicKeyCheckDatas.Any(pk => pk.IssuerClientInstanceId.Equals(memberInstanceId))); } - public async Task ResetPeerTrustProcessData(string sessionId, string otherPartyClientId) + public async Task ResetPeerTrustProcessData(string sessionId, PublicKeyCheckData peer) { return await GetAsync(sessionId, data => { - var peerTrustProcessData = new PeerTrustProcessData(otherPartyClientId); - - data.AddPeerTrustProcessData(peerTrustProcessData); - - return peerTrustProcessData; + var peerTrustProcessData = new PeerTrustProcessData(peer); + return data.AddPeerTrustProcessData(peerTrustProcessData); }); } @@ -65,7 +62,7 @@ public async Task SetOtherPartyChecked(string sessionId, PublicKeyValidationPara { await RunAsync(sessionId, data => { - data.SetOtherPartyChecked(publicKeyValidationParameters.IssuerClientId, publicKeyValidationParameters.IsValidated); + data.SetOtherPartyChecked(publicKeyValidationParameters); }); } diff --git a/src/ByteSync.Common/Business/Sessions/Cloud/Connections/PublicKeyValidationParameters.cs b/src/ByteSync.Common/Business/Sessions/Cloud/Connections/PublicKeyValidationParameters.cs index 5820bdb77..21240dc3f 100644 --- a/src/ByteSync.Common/Business/Sessions/Cloud/Connections/PublicKeyValidationParameters.cs +++ b/src/ByteSync.Common/Business/Sessions/Cloud/Connections/PublicKeyValidationParameters.cs @@ -1,4 +1,4 @@ -namespace ByteSync.Common.Business.Sessions.Cloud.Connections; +namespace ByteSync.Common.Business.Sessions.Cloud.Connections; public class PublicKeyValidationParameters { @@ -10,6 +10,9 @@ public PublicKeyValidationParameters() public string SessionId { get; set; } public string IssuerClientId { get; set; } + public string IssuerClientInstanceId { get; set; } + public string IssuerIdentity { get; set; } + public string ExchangeId { get; set; } public string OtherPartyClientInstanceId { get; set; } diff --git a/src/ByteSync.ServerCommon/Commands/Trusts/InformPublicKeyValidationIsFinishedCommandHandler.cs b/src/ByteSync.ServerCommon/Commands/Trusts/InformPublicKeyValidationIsFinishedCommandHandler.cs index 16fe6243d..6470e6410 100644 --- a/src/ByteSync.ServerCommon/Commands/Trusts/InformPublicKeyValidationIsFinishedCommandHandler.cs +++ b/src/ByteSync.ServerCommon/Commands/Trusts/InformPublicKeyValidationIsFinishedCommandHandler.cs @@ -1,4 +1,4 @@ -using ByteSync.ServerCommon.Interfaces.Repositories; +using ByteSync.ServerCommon.Interfaces.Repositories; using ByteSync.ServerCommon.Interfaces.Services.Clients; using MediatR; using Microsoft.Extensions.Logging; @@ -23,6 +23,22 @@ public async Task Handle(InformPublicKeyValidationIsFinishedRequest request, Can var session = await _cloudSessionsRepository.Get(request.Parameters.SessionId); if (session != null) { + ByteSync.ServerCommon.Security.SessionAuthorizationBehavior.RequireIdentity(request.Client); + var recipient = session.FindMemberOrPreMember(request.Parameters.OtherPartyClientInstanceId); + if (session.IsSessionRemoved || session.IsSessionActivated || + session.AuthenticationEpoch != ByteSync.Common.Business.Auth.AuthenticationProtocol.Epoch || + session.ProtocolVersion != ByteSync.Common.Business.Versions.ProtocolVersion.CURRENT || + session.FindMemberOrPreMember(request.Client.ClientInstanceId)?.Identity != request.Client.Identity || + recipient?.Identity == null || + (session.FindMember(request.Client.ClientInstanceId) == null && + session.FindMemberOrPreMember(request.Client.ClientInstanceId)!.JoinExpiresAt <= DateTimeOffset.UtcNow) || + (session.FindMember(recipient.ClientInstanceId) == null && recipient.JoinExpiresAt <= DateTimeOffset.UtcNow) || + !MatchesIdentity(request.Parameters.OtherPartyPublicKey, recipient.Identity) || + string.IsNullOrWhiteSpace(request.Parameters.ExchangeId) || request.Parameters.ExchangeId.Length > 128) + throw new UnauthorizedAccessException("Invalid peer trust confirmation"); + request.Parameters.IssuerClientId = request.Client.ClientId; + request.Parameters.IssuerClientInstanceId = request.Client.ClientInstanceId; + request.Parameters.IssuerIdentity = request.Client.Identity; await _invokeClientsService.Client(request.Parameters.OtherPartyClientInstanceId).InformPublicKeyValidationIsFinished(request.Parameters).ConfigureAwait(false); _logger.LogInformation("InformPublicKeyValidationIsFinished: {Sender} sends PublicKeyValidation to {Recipient}", request.Client.ClientInstanceId, @@ -35,4 +51,16 @@ public async Task Handle(InformPublicKeyValidationIsFinishedRequest request, Can } } + private static bool MatchesIdentity(byte[]? key, string identity) + { + try + { + return key is { Length: > 0 and <= 2048 } && + ByteSync.Common.Business.Auth.AuthenticationProtocol.GetIdentity(key) == identity; + } + catch (System.Security.Cryptography.CryptographicException) + { + return false; + } + } } \ No newline at end of file diff --git a/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysTrusterTests.cs b/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysTrusterTests.cs index 82da58a1b..385ef73d6 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysTrusterTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Communications/PublicKeysTrusterTests.cs @@ -76,6 +76,36 @@ public void SetUp() } + [Test] + public async Task FinishedValidation_SendsTheExpectedExchangeAndRecipient() + { + var peer = new PublicKeyCheckData { IssuerClientInstanceId = "peer-instance", Salt = "exchange-salt", + IssuerPublicKeyInfo = new PublicKeyInfo { ClientId = "ABCD-EFG-HIJ", PublicKey = [1, 2, 3] } }; + _publicKeysManager.Setup(m => m.GetMyPublicKeyInfo()).Returns(new PublicKeyInfo { ClientId = "KLMN-OPQ-RST" }); + var pending = new ByteSync.Business.Communications.PublicKeysTrusting.PeerTrustProcessData("ABCD-EFG-HIJ"); + var context = new ByteSync.Business.TrustDataParameters(1, 1, true, "session", pending); + + await _publicKeysTruster.OnPublicKeyValidationFinished(peer, context, true); + + _trustApiClient.Verify(a => a.InformPublicKeyValidationIsFinished(It.Is(p => + p.SessionId == "session" && p.ExchangeId == peer.Salt && p.OtherPartyClientInstanceId == peer.IssuerClientInstanceId && + p.OtherPartyPublicKey == peer.IssuerPublicKeyInfo.PublicKey && p.IsValidated), It.IsAny()), Times.Once); + pending.HasLocalValidatedPublicKey.Should().BeTrue(); + } + + [TestCase(true)] + [TestCase(false)] + public async Task ReceivedConfirmation_OnlyUpdatesItsIntendedRecipient(bool intended) + { + var parameters = new PublicKeyValidationParameters { SessionId = "session", + OtherPartyClientInstanceId = intended ? "TestClientInstanceId" : "other-instance" }; + + await _publicKeysTruster.OnPublicKeyValidationIsFinishedAsync(parameters); + + _trustProcessPublicKeysRepository.Verify(r => r.SetOtherPartyChecked("session", parameters), + intended ? Times.Once() : Times.Never()); + } + [Test] public async Task TrustCheck_SkipsOnlyInstancesOfTheCryptographicIdentity() { @@ -191,7 +221,7 @@ public async Task OnTrustPublicKeyRequestedAsync_WithCompatibleProtocolVersion_S .ReturnsAsync(myPublicKeyCheckData); _trustProcessPublicKeysRepository - .Setup(r => r.ResetPeerTrustProcessData(sessionId, "JoinerClientId")) + .Setup(r => r.ResetPeerTrustProcessData(sessionId, joinerPublicKeyCheckData)) .ReturnsAsync(peerTrustProcessData); var requestParameters = new RequestTrustProcessParameters(sessionId, joinerPublicKeyCheckData, joinerInstanceId); diff --git a/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs b/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs index 9f84548f2..2dfe94fe4 100644 --- a/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs +++ b/tests/ByteSync.Client.UnitTests/Services/Security/AuthProtocolCompatibilityTests.cs @@ -43,6 +43,106 @@ public void SetUp() [TearDown] public void TearDown() => _settings.PrivateRsa.Dispose(); + private static ByteSync.Common.Business.EndPoints.PublicKeyCheckData Peer(RSA key, string salt = "exchange-salt") + { + var publicKey = key.ExportRSAPublicKey(); + var identity = AuthenticationProtocol.GetIdentity(publicKey); + return new() { IssuerPublicKeyInfo = new() { ClientId = "ABCD-EFG-HIJ", PublicKey = publicKey }, + IssuerClientInstanceId = identity + "_" + Guid.NewGuid().ToString("D"), Salt = salt }; + } + + [TestCase("valid", true)] + [TestCase("alias-metadata", true)] + [TestCase("wrong-identity", false)] + [TestCase("wrong-instance", false)] + [TestCase("old-exchange", false)] + [TestCase("missing-instance", false)] + [TestCase("missing-identity", false)] + [TestCase("missing-exchange", false)] + public async Task TrustConfirmation_RequiresExpectedInstanceIdentityAndExchange(string scenario, bool accepted) + { + using var key = RSA.Create(2048); + var peer = Peer(key); + var repository = new TrustProcessPublicKeysRepository(NullLogger.Instance); + await repository.Start("session"); + var pending = await repository.ResetPeerTrustProcessData("session", peer); + var confirmation = new ByteSync.Common.Business.Sessions.Cloud.Connections.PublicKeyValidationParameters + { + IssuerClientId = peer.IssuerPublicKeyInfo.ClientId, IssuerClientInstanceId = peer.IssuerClientInstanceId, + IssuerIdentity = AuthenticationProtocol.GetIdentity(peer.IssuerPublicKeyInfo.PublicKey), + ExchangeId = peer.Salt, IsValidated = true + }; + switch (scenario) + { + case "alias-metadata": confirmation.IssuerClientId = "different-readable-alias"; break; + case "wrong-identity": confirmation.IssuerIdentity = new string('A', 64); break; + case "wrong-instance": confirmation.IssuerClientInstanceId = confirmation.IssuerIdentity + "_" + Guid.NewGuid().ToString("D"); break; + case "old-exchange": confirmation.ExchangeId = "old-salt"; break; + case "missing-instance": confirmation.IssuerClientInstanceId = null!; break; + case "missing-identity": confirmation.IssuerIdentity = null!; break; + case "missing-exchange": confirmation.ExchangeId = null!; break; + } + + await repository.SetOtherPartyChecked("session", confirmation); + + pending.HasOtherPartyValidatedPublicKey.Should().Be(accepted); + pending.OtherPartyHasFinished().Should().Be(accepted); + } + + [TestCase(false)] + [TestCase(true)] + public async Task CollidingAliases_AndReplayedConfirmations_CannotCompleteAnotherExchange(bool sameKey) + { + using var firstKey = RSA.Create(2048); + using var secondKey = RSA.Create(2048); + var first = Peer(firstKey); + var second = Peer(sameKey ? firstKey : secondKey); + var repository = new TrustProcessPublicKeysRepository(NullLogger.Instance); + await repository.Start("session"); + var firstPending = await repository.ResetPeerTrustProcessData("session", first); + var secondPending = await repository.ResetPeerTrustProcessData("session", second); + var message = new ByteSync.Common.Business.Sessions.Cloud.Connections.PublicKeyValidationParameters + { + IssuerClientId = first.IssuerPublicKeyInfo.ClientId, IssuerClientInstanceId = first.IssuerClientInstanceId, + IssuerIdentity = AuthenticationProtocol.GetIdentity(first.IssuerPublicKeyInfo.PublicKey), ExchangeId = first.Salt, IsValidated = false + }; + + await repository.SetOtherPartyChecked("session", message); + var duplicate = await repository.ResetPeerTrustProcessData("session", first); + message.IsValidated = true; + await repository.SetOtherPartyChecked("session", message); + firstPending.HasOtherPartyValidatedPublicKey.Should().BeFalse(); + firstPending.OtherPartyHasFinished().Should().BeTrue(); + duplicate.Should().BeSameAs(firstPending); + secondPending.OtherPartyHasFinished().Should().BeFalse(); + first.Salt = "new-exchange"; + var replacement = await repository.ResetPeerTrustProcessData("session", first); + await repository.SetOtherPartyChecked("session", message); + replacement.OtherPartyHasFinished().Should().BeFalse(); + message.ExchangeId = first.Salt; + await repository.SetOtherPartyChecked("session", message); + replacement.HasOtherPartyValidatedPublicKey.Should().BeTrue(); + secondPending.HasOtherPartyValidatedPublicKey.Should().BeFalse(); + var wrongSession = () => repository.SetOtherPartyChecked("other-session", message); + await wrongSession.Should().ThrowAsync(); + } + + [TestCase("instance")] + [TestCase("salt")] + public async Task InvalidTrustExchange_CannotBeRegistered(string field) + { + using var key = RSA.Create(2048); + var peer = Peer(key); + if (field == "instance") peer.IssuerClientInstanceId = "ABCD-EFG-HIJ_legacy"; + else peer.Salt = ""; + var repository = new TrustProcessPublicKeysRepository(NullLogger.Instance); + await repository.Start("session"); + + var act = () => repository.ResetPeerTrustProcessData("session", peer); + + await act.Should().ThrowAsync(); + } + [Test] public void EnvironmentInitialization_PreservesTheStoredReadableIdAndExistingKeys() { diff --git a/tests/ByteSync.ServerCommon.Tests/Commands/Trusts/InformPublicKeyValidationIsFinishedCommandHandlerTests.cs b/tests/ByteSync.ServerCommon.Tests/Commands/Trusts/InformPublicKeyValidationIsFinishedCommandHandlerTests.cs index f3e2f0469..7c41d00f7 100644 --- a/tests/ByteSync.ServerCommon.Tests/Commands/Trusts/InformPublicKeyValidationIsFinishedCommandHandlerTests.cs +++ b/tests/ByteSync.ServerCommon.Tests/Commands/Trusts/InformPublicKeyValidationIsFinishedCommandHandlerTests.cs @@ -1,73 +1,121 @@ -using ByteSync.Common.Business.Sessions.Cloud.Connections; +using ByteSync.Common.Business.Auth; +using ByteSync.Common.Business.Sessions.Cloud.Connections; +using ByteSync.Common.Business.Versions; using ByteSync.Common.Interfaces.Hub; using ByteSync.ServerCommon.Business.Auth; using ByteSync.ServerCommon.Business.Sessions; using ByteSync.ServerCommon.Commands.Trusts; using ByteSync.ServerCommon.Interfaces.Repositories; using ByteSync.ServerCommon.Interfaces.Services.Clients; -using Microsoft.Extensions.Logging; -using Moq; +using ByteSync.TestsCommon.TestHelpers; +using FakeItEasy; +using FluentAssertions; +using Microsoft.Extensions.Logging.Abstractions; namespace ByteSync.ServerCommon.Tests.Commands.Trusts; -[TestFixture] public class InformPublicKeyValidationIsFinishedCommandHandlerTests { - [Test] - public async Task Handle_WhenSessionExists_InvokesClientInform() + [TestCase("valid", true)] + [TestCase("alias-collision", true)] + [TestCase("pending-sender", true)] + [TestCase("pending-recipient", true)] + [TestCase("outsider", false)] + [TestCase("wrong-identity", false)] + [TestCase("wrong-instance", false)] + [TestCase("expired-sender", false)] + [TestCase("expired-recipient", false)] + [TestCase("wrong-recipient-key", false)] + [TestCase("malformed-key", false)] + [TestCase("missing-key", false)] + [TestCase("missing-exchange", false)] + [TestCase("oversized-exchange", false)] + [TestCase("missing-recipient", false)] + [TestCase("missing-recipient-identity", false)] + [TestCase("activated", false)] + [TestCase("removed", false)] + [TestCase("legacy-epoch", false)] + [TestCase("legacy-protocol", false)] + public async Task Confirmation_UsesAuthenticatedSenderAndEligibleRecipient(string scenario, bool allowed) { - // Arrange - var sessionId = "session-1"; - var otherPartyInstanceId = "other-instance"; - - var repo = new Mock(); - repo.Setup(r => r.Get(sessionId)).ReturnsAsync(new CloudSessionData { SessionId = sessionId }); - - var hub = new Mock(); - var invoke = new Mock(); - invoke.Setup(s => s.Client(otherPartyInstanceId)).Returns(hub.Object); - - var logger = new Mock>(); - var handler = new InformPublicKeyValidationIsFinishedCommandHandler(repo.Object, invoke.Object, logger.Object); - - var parameters = new PublicKeyValidationParameters { SessionId = sessionId, OtherPartyClientInstanceId = otherPartyInstanceId }; - var client = new Client { ClientInstanceId = "sender", ClientId = "s" }; - var request = new InformPublicKeyValidationIsFinishedRequest(parameters, client); + using var sender = new AuthenticationTestIdentity(); + using var recipient = new AuthenticationTestIdentity(); + var client = new Client { ClientId = scenario == "alias-collision" ? recipient.ClientId : "KLMN-OPQ-RST", + ClientInstanceId = sender.ClientInstanceId, Identity = sender.Identity, AuthenticationEpoch = AuthenticationProtocol.Epoch }; + var session = new CloudSessionData { SessionId = "session", AuthenticationEpoch = AuthenticationProtocol.Epoch, + ProtocolVersion = ProtocolVersion.CURRENT }; + var senderMember = new SessionMemberData { ClientId = client.ClientId, ClientInstanceId = sender.ClientInstanceId, + Identity = sender.Identity, JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(1) }; + var recipientMember = new SessionMemberData { ClientId = recipient.ClientId, ClientInstanceId = recipient.ClientInstanceId, + Identity = recipient.Identity, JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(1) }; + session.SessionMembers.Add(senderMember); + session.SessionMembers.Add(recipientMember); + var parameters = new PublicKeyValidationParameters { SessionId = "session", IssuerClientId = "forged-alias", + IssuerIdentity = recipient.Identity, IssuerClientInstanceId = recipient.ClientInstanceId, + OtherPartyClientInstanceId = recipient.ClientInstanceId, OtherPartyPublicKey = recipient.CreatePublicKeyInfo().PublicKey, + ExchangeId = "exchange-salt", IsValidated = true }; + switch (scenario) + { + case "outsider": session.SessionMembers.Remove(senderMember); break; + case "wrong-identity": senderMember.Identity = recipient.Identity; break; + case "wrong-instance": client.ClientInstanceId = recipient.ClientInstanceId; break; + case "pending-sender": case "expired-sender": + session.SessionMembers.Remove(senderMember); session.PreSessionMembers.Add(senderMember); + if (scenario == "expired-sender") senderMember.JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1); + break; + case "pending-recipient": case "expired-recipient": + session.SessionMembers.Remove(recipientMember); session.PreSessionMembers.Add(recipientMember); + if (scenario == "expired-recipient") recipientMember.JoinExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1); + break; + case "wrong-recipient-key": parameters.OtherPartyPublicKey = sender.CreatePublicKeyInfo().PublicKey; break; + case "malformed-key": parameters.OtherPartyPublicKey = [1, 2, 3]; break; + case "missing-key": parameters.OtherPartyPublicKey = null!; break; + case "missing-exchange": parameters.ExchangeId = ""; break; + case "oversized-exchange": parameters.ExchangeId = new string('A', 129); break; + case "missing-recipient": session.SessionMembers.Remove(recipientMember); break; + case "missing-recipient-identity": recipientMember.Identity = null; break; + case "activated": session.IsSessionActivated = true; break; + case "removed": session.IsSessionRemoved = true; break; + case "legacy-epoch": session.AuthenticationEpoch = 0; break; + case "legacy-protocol": session.ProtocolVersion = 2; break; + } + var repo = A.Fake(); + A.CallTo(() => repo.Get("session")).Returns(session); + var hub = A.Fake(); + var invoke = A.Fake(); + A.CallTo(() => invoke.Client(recipient.ClientInstanceId)).Returns(hub); + var handler = new InformPublicKeyValidationIsFinishedCommandHandler(repo, invoke, + NullLogger.Instance); + var act = () => handler.Handle(new InformPublicKeyValidationIsFinishedRequest(parameters, client), default); - // Act - await handler.Handle(request, default); - - // Assert - invoke.Verify(s => s.Client(otherPartyInstanceId), Times.Once); - hub.Verify(h => h.InformPublicKeyValidationIsFinished(parameters), Times.Once); + if (allowed) + { + await act(); + parameters.IssuerClientId.Should().Be(client.ClientId); + parameters.IssuerClientInstanceId.Should().Be(sender.ClientInstanceId); + parameters.IssuerIdentity.Should().Be(sender.Identity); + parameters.ExchangeId.Should().Be("exchange-salt"); + A.CallTo(() => hub.InformPublicKeyValidationIsFinished(parameters)).MustHaveHappenedOnceExactly(); + } + else + { + await act.Should().ThrowAsync(); + A.CallTo(() => hub.InformPublicKeyValidationIsFinished(A._)).MustNotHaveHappened(); + } } [Test] - public async Task Handle_WhenSessionMissing_DoesNothing() + public async Task MissingSession_DoesNotSendConfirmation() { - // Arrange - var sessionId = "session-1"; - var otherPartyInstanceId = "other-instance"; - - var repo = new Mock(); - repo.Setup(r => r.Get(sessionId)).ReturnsAsync((CloudSessionData?)null); - - var hub = new Mock(); - var invoke = new Mock(); - invoke.Setup(s => s.Client(It.IsAny())).Returns(hub.Object); - - var logger = new Mock>(); - var handler = new InformPublicKeyValidationIsFinishedCommandHandler(repo.Object, invoke.Object, logger.Object); - - var parameters = new PublicKeyValidationParameters { SessionId = sessionId, OtherPartyClientInstanceId = otherPartyInstanceId }; - var client = new Client { ClientInstanceId = "sender", ClientId = "s" }; - var request = new InformPublicKeyValidationIsFinishedRequest(parameters, client); + var repo = A.Fake(); + A.CallTo(() => repo.Get("missing")).Returns((CloudSessionData?)null); + var invoke = A.Fake(); + var handler = new InformPublicKeyValidationIsFinishedCommandHandler(repo, invoke, + NullLogger.Instance); - // Act - await handler.Handle(request, default); + await handler.Handle(new InformPublicKeyValidationIsFinishedRequest(new PublicKeyValidationParameters + { SessionId = "missing" }, new Client()), default); - // Assert - invoke.Verify(s => s.Client(It.IsAny()), Times.Never); - hub.Verify(h => h.InformPublicKeyValidationIsFinished(It.IsAny()), Times.Never); + A.CallTo(invoke).MustNotHaveHappened(); } -} \ No newline at end of file +} From eb4e355eb88401bdc137bc2b0ecd48e18a5e0ddc Mon Sep 17 00:00:00 2001 From: Paul Fresquet Date: Sun, 22 Nov 2026 10:51:01 +0100 Subject: [PATCH 8/8] fix: synchronize runtime identity during key renewal [skip ci] --- docs/security-boundaries.md | 12 ++ .../Assets/Resources/Resources.en.resx | 5 +- .../Assets/Resources/Resources.fr.resx | 3 + .../Assets/Resources/Resources.resx | 3 + .../Communications/IPublicKeysManager.cs | 4 +- .../IAuthenticationTokensRepository.cs | 4 +- .../Communications/IConnectionService.cs | 4 +- .../AuthenticationTokensRepository.cs | 9 +- .../Communications/ConnectionService.cs | 80 +++++++--- .../Communications/PublicKeysManager.cs | 59 ++++++-- .../TrustedNetworkViewModel.cs | 22 ++- .../TrustedNetworks/TrustedNetworkView.axaml | 1 + .../Communications/ConnectionServiceTests.cs | 100 ++++++++++++ .../Communications/PublicKeysManagerTests.cs | 39 ++++- .../AuthProtocolCompatibilityTests.cs | 143 ++++++++++++++++++ 15 files changed, 441 insertions(+), 47 deletions(-) diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md index 2c2153b6d..8036cd3ed 100644 --- a/docs/security-boundaries.md +++ b/docs/security-boundaries.md @@ -209,6 +209,18 @@ Validation: the solution, including integration fixtures, builds with zero error Evidence is retained locally under `artifacts/pr351-p1/` in the original checkout, including TRX, coverage and `validation.json`. The correction uses `[skip ci]` to avoid Azure/container workflows after pushing to the same PR. +## Coherent manual key renewal (2026-11-22) + +Explicit manual renewal now updates the stored RSA pair, readable ClientId, runtime Identity and fingerprint-prefixed ClientInstanceId together. The existing manual-renewal behavior still regenerates the readable code and clears trusted keys after user confirmation; normal startup/login does neither. The readable code keeps its historical format. + +Renewal is serialized and refused while a session exists, while creating/joining a session, or while an authentication attempt/retry is pending. These checks run before stopping the connection and session state is checked again afterwards. The UI disables renewal during sessions/connection setup and supplies English/French guidance. A failed hub stop leaves the keys unchanged. + +Before key replacement, the client cancels token refresh, waits for any in-flight refresh request to finish, stops the old hub, clears its endpoint and removes the old JWT/refresh tokens. The settings update installs the matching environment identity and a fresh instance. A previously connected client starts an observed fresh-login reconnection in the background, allowing the new identity to appear immediately even if the relay is unavailable. Reconnection failure preserves coherent new key/identity state for another attempt. No legacy login fallback is introduced. + +Automatic restarts and explicit stops share a lifecycle gate; canceled refresh work cannot restart the old connection. Ordinary same-key reconnections keep the existing instance identity so local source grants and current sessions are not invalidated by transient connectivity. Only explicit key renewal clears/replaces the endpoint and key identity. Existing session membership and local permissions are not promoted to the new key. + +Validation: the solution and integration fixtures compile with zero errors. The full client unit suite passes **1,317 tests**, zero failures, including 18 additional cases for renewal, real RSA-PSS login after renewal, token removal, refusal/failure paths, refresh draining, automatic restart, recipient/session UI guards and nonblocking reconnection. Twelve existing POSIX-only cases do not execute on Windows. Coverage reaches 88 of 93 changed executable/instrumented lines (94.6%), including the XAML tooltip sequence point; this does not establish the PR-wide Sonar gate. Backend production code is unchanged; the server/Functions/Common suites were not rerun for this client-only follow-up. The previous P1 validation remains recorded above. Integration/E2E services were not exercised. No Azure endpoint was contacted and Docker was not started. Evidence is under `artifacts/p2/validated/`; the correction uses `[skip ci]` when pushed to the same PR. + ## Future rollout proposal (not executed) 1. Review this patch and approve the breaking protocol, restrictions and enrollment experience. Complete native multi-platform CI, isolated Redis/SignalR/storage end-to-end tests, load/abuse checks and the coverage gate. Confirm the Redis version before rollout. Back up local RSA/settings/trust/profile data through the existing supported process; do not collect private keys centrally. diff --git a/src/ByteSync.Client/Assets/Resources/Resources.en.resx b/src/ByteSync.Client/Assets/Resources/Resources.en.resx index 398dd826e..e2e25b058 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.en.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.en.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -45,4 +45,7 @@ You must select at least 2 data nodes. The relay server does not provide the secure authentication required by this client. Check the relay address or update the relay server. Automatic reconnection has stopped. + + Renew your key outside a session, after connection attempts have finished. + diff --git a/src/ByteSync.Client/Assets/Resources/Resources.fr.resx b/src/ByteSync.Client/Assets/Resources/Resources.fr.resx index 7d9f43063..87822c752 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.fr.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.fr.resx @@ -1837,5 +1837,8 @@ Voulez-vous enregistrer ce nouveau Profil de Session avec ce nom ? Le serveur relais ne fournit pas l’authentification sécurisée requise par ce client. Vérifiez l’adresse du relais ou mettez à jour le serveur. La reconnexion automatique est arrêtée. + + Renouvelez votre clé hors session, une fois les tentatives de connexion terminées. + diff --git a/src/ByteSync.Client/Assets/Resources/Resources.resx b/src/ByteSync.Client/Assets/Resources/Resources.resx index 56fec3338..9f0d76f5f 100644 --- a/src/ByteSync.Client/Assets/Resources/Resources.resx +++ b/src/ByteSync.Client/Assets/Resources/Resources.resx @@ -1862,4 +1862,7 @@ Do you want to save this new Session Profile with this name? The relay server does not provide the secure authentication required by this client. Check the relay address or update the relay server. Automatic reconnection has stopped. + + Renew your key outside a session, after connection attempts have finished. + diff --git a/src/ByteSync.Client/Interfaces/Controls/Communications/IPublicKeysManager.cs b/src/ByteSync.Client/Interfaces/Controls/Communications/IPublicKeysManager.cs index df3abbee8..48e205e7b 100644 --- a/src/ByteSync.Client/Interfaces/Controls/Communications/IPublicKeysManager.cs +++ b/src/ByteSync.Client/Interfaces/Controls/Communications/IPublicKeysManager.cs @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using ByteSync.Business.Communications; using ByteSync.Common.Business.EndPoints; @@ -24,7 +24,7 @@ public interface IPublicKeysManager void Delete(TrustedPublicKey trustedPublicKey); - void InitializeRsaAndTrustedPublicKeys(); + Task InitializeRsaAndTrustedPublicKeys(); byte[] DecryptBytes(byte[] messageToEncrypt); diff --git a/src/ByteSync.Client/Interfaces/Services/Communications/IAuthenticationTokensRepository.cs b/src/ByteSync.Client/Interfaces/Services/Communications/IAuthenticationTokensRepository.cs index daac9eff4..01fc31d25 100644 --- a/src/ByteSync.Client/Interfaces/Services/Communications/IAuthenticationTokensRepository.cs +++ b/src/ByteSync.Client/Interfaces/Services/Communications/IAuthenticationTokensRepository.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using ByteSync.Common.Business.Auth; namespace ByteSync.Interfaces.Services.Communications; @@ -8,4 +8,6 @@ public interface IAuthenticationTokensRepository Task GetTokens(); Task Store(AuthenticationTokens authenticationTokens); + + Task Clear(); } \ No newline at end of file diff --git a/src/ByteSync.Client/Interfaces/Services/Communications/IConnectionService.cs b/src/ByteSync.Client/Interfaces/Services/Communications/IConnectionService.cs index 6b54b17d0..e1ee40a5d 100644 --- a/src/ByteSync.Client/Interfaces/Services/Communications/IConnectionService.cs +++ b/src/ByteSync.Client/Interfaces/Services/Communications/IConnectionService.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using ByteSync.Business.Communications; using ByteSync.Common.Business.EndPoints; using Microsoft.AspNetCore.SignalR.Client; @@ -17,6 +17,8 @@ public interface IConnectionService string? ClientInstanceId { get; } + bool IsStarting { get; } + Task StartConnectionAsync(); Task StopConnection(); diff --git a/src/ByteSync.Client/Services/Communications/AuthenticationTokensRepository.cs b/src/ByteSync.Client/Services/Communications/AuthenticationTokensRepository.cs index af2ad67f5..3d51a09fe 100644 --- a/src/ByteSync.Client/Services/Communications/AuthenticationTokensRepository.cs +++ b/src/ByteSync.Client/Services/Communications/AuthenticationTokensRepository.cs @@ -1,4 +1,4 @@ -using System.Threading; +using System.Threading; using System.Threading.Tasks; using ByteSync.Common.Business.Auth; using ByteSync.Interfaces.Services.Communications; @@ -24,6 +24,13 @@ public class AuthenticationTokensRepository : IAuthenticationTokensRepository } } + public async Task Clear() + { + await _semaphore.WaitAsync(); + try { _tokens = null; } + finally { _semaphore.Release(); } + } + public async Task Store(AuthenticationTokens authenticationTokens) { var clone = authenticationTokens.Clone() as AuthenticationTokens; diff --git a/src/ByteSync.Client/Services/Communications/ConnectionService.cs b/src/ByteSync.Client/Services/Communications/ConnectionService.cs index 04b8ee08f..ea239f6ff 100644 --- a/src/ByteSync.Client/Services/Communications/ConnectionService.cs +++ b/src/ByteSync.Client/Services/Communications/ConnectionService.cs @@ -21,6 +21,10 @@ public class ConnectionService : IConnectionService, IDisposable private readonly IDisposable? _connectionSubscription; private CancellationTokenSource? _refreshCancellationTokenSource; + private readonly object _refreshGate = new(); + private readonly SemaphoreSlim _lifecycleGate = new(1, 1); + private Task? _refreshOperation; + public bool IsStarting { get; private set; } public ConnectionService(IConnectionFactory connectionFactory, IAuthenticationTokensRepository authenticationTokensRepository, ILogger logger) @@ -68,7 +72,9 @@ public ConnectionService(IConnectionFactory connectionFactory, IAuthenticationTo public Func? RetryDelaySleepDurationProvider { get; set; } - public async Task StartConnectionAsync() + public Task StartConnectionAsync() => StartConnectionCore(false); + + private async Task StartConnectionCore(bool lifecycleHeld) { var retryDelaySleepDurationProvider = RetryDelaySleepDurationProvider; @@ -85,6 +91,8 @@ public async Task StartConnectionAsync() _logger.LogError(exception, "An error occurred while starting the connection"); }); + if (IsStarting) throw new InvalidOperationException("Connection is already starting"); + IsStarting = true; try { await retryPolicy.ExecuteAsync(async () => @@ -101,6 +109,7 @@ await retryPolicy.ExecuteAsync(async () => { CurrentEndPoint = result.EndPoint!; + IsStarting = false; ConnectionStatusSubject.OnNext(ConnectionStatuses.Connected); } else @@ -116,12 +125,14 @@ await retryPolicy.ExecuteAsync(async () => } catch (RelayIncompatibleException ex) { - await StopConnection(); + if (lifecycleHeld) await StopConnectionCore(); + else await StopConnection(); CurrentEndPoint = null; ConnectionStatusSubject.OnNext(ConnectionStatuses.RelayIncompatible); _logger.LogError(ex, "{RelayCompatibilityError}", ex.Message); throw; } + finally { IsStarting = false; } } private async Task StartOrRestartJwtTokensRefreshTimer() @@ -145,12 +156,13 @@ private async Task StartOrRestartJwtTokensRefreshTimer() try { - await RefreshJwtTokens(); + await RefreshJwtTokens(cancellationToken); } catch (Exception ex) { + if (cancellationToken.IsCancellationRequested) break; _logger.LogError(ex, "An error occurred while refreshing JWT tokens"); - await RestartConnection(); + await RestartConnection(cancellationToken); } } } @@ -169,10 +181,10 @@ private async Task StartOrRestartJwtTokensRefreshTimer() } } - private async Task RefreshJwtTokens() + private async Task RefreshJwtTokens(CancellationToken cancellationToken) { var retryPolicy = Policy - .Handle(ex => !(ex is HttpRequestException httpRequestException && httpRequestException.Message.Contains("401"))) + .Handle(ex => ex is not OperationCanceledException && !(ex is HttpRequestException httpRequestException && httpRequestException.Message.Contains("401"))) .Or(ex => !ex.Message.Contains("401")) .WaitAndRetryAsync(5, _ => TimeSpan.FromSeconds(10), @@ -181,11 +193,19 @@ private async Task RefreshJwtTokens() _logger.LogError(exception, "Attempt {CurrentAttempt}: An error occurred while refreshing jwt tokens", currentAttempt); }); - await retryPolicy.ExecuteAsync(async () => + await retryPolicy.ExecuteAsync(async _ => { + cancellationToken.ThrowIfCancellationRequested(); _logger.LogInformation("Start refreshing jwt tokens"); - var refreshTokens = await _connectionFactory.RefreshAuthenticationTokens(); + Task operation; + lock (_refreshGate) + { + cancellationToken.ThrowIfCancellationRequested(); + operation = _refreshOperation = _connectionFactory.RefreshAuthenticationTokens(); + } + var refreshTokens = await operation; + cancellationToken.ThrowIfCancellationRequested(); if (refreshTokens) { _logger.LogInformation("successfully refreshed jwt tokens"); @@ -194,12 +214,19 @@ await retryPolicy.ExecuteAsync(async () => { _logger.LogWarning("failed to refresh jwt tokens"); - _ = RestartConnection(); + await RestartConnection(cancellationToken); } - }); + }, cancellationToken); } public async Task StopConnection() + { + await _lifecycleGate.WaitAsync(); + try { await StopConnectionCore(); } + finally { _lifecycleGate.Release(); } + } + + private async Task StopConnectionCore() { await CancelCurrentRefreshCancellationTokenSource(); @@ -213,6 +240,7 @@ public async Task StopConnection() catch (Exception e) { _logger.LogError(e, "An error occurred while stopping the connection"); + throw; } } @@ -226,25 +254,31 @@ public void Dispose() _refreshCancellationTokenSource?.Dispose(); } - private async Task RestartConnection() + private async Task RestartConnection(CancellationToken cancellationToken) { - if (CurrentConnectionStatus == ConnectionStatuses.RelayIncompatible) + await _lifecycleGate.WaitAsync(); + try { - return; + if (cancellationToken.IsCancellationRequested || CurrentConnectionStatus == ConnectionStatuses.RelayIncompatible) + return; + await StopConnectionCore(); + await StartConnectionCore(true); } - - await StopConnection(); - await StartConnectionAsync(); + finally { _lifecycleGate.Release(); } } - - private Task CancelCurrentRefreshCancellationTokenSource() + + private async Task CancelCurrentRefreshCancellationTokenSource() { - var currentRefreshCancellationTokenSource = _refreshCancellationTokenSource; - if (currentRefreshCancellationTokenSource != null) + Task? operation; + lock (_refreshGate) { - _ = currentRefreshCancellationTokenSource.CancelAsync(); + _refreshCancellationTokenSource?.Cancel(); + operation = _refreshOperation; + } + if (operation != null) + { + try { await operation; } + catch (Exception ex) { _logger.LogDebug(ex, "Previous token refresh ended while stopping the connection"); } } - - return Task.CompletedTask; } } diff --git a/src/ByteSync.Client/Services/Communications/PublicKeysManager.cs b/src/ByteSync.Client/Services/Communications/PublicKeysManager.cs index 0875b6d70..1b288722e 100644 --- a/src/ByteSync.Client/Services/Communications/PublicKeysManager.cs +++ b/src/ByteSync.Client/Services/Communications/PublicKeysManager.cs @@ -1,4 +1,10 @@ -using System.Collections.ObjectModel; +using System.Threading; +using ByteSync.Common.Business.Auth; +using ByteSync.Business.Sessions; +using ByteSync.Interfaces.Controls.Applications; +using ByteSync.Interfaces.Repositories; +using ByteSync.Interfaces.Services.Sessions; +using System.Collections.ObjectModel; using System.Security.Cryptography; using System.Text; using ByteSync.Business.Communications; @@ -16,13 +22,23 @@ public class PublicKeysManager : IPublicKeysManager private readonly IApplicationSettingsRepository _applicationSettingsRepository; private readonly IConnectionService _connectionService; private readonly ILogger _logger; + private readonly IEnvironmentService _environment; + private readonly IAuthenticationTokensRepository _tokens; + private readonly Lazy _session; + private readonly ICloudSessionConnectionRepository _sessionConnection; + private readonly SemaphoreSlim _renewalGate = new(1, 1); public PublicKeysManager(IApplicationSettingsRepository applicationSettingsManager, IConnectionService connectionService, - ILogger logger) + ILogger logger, IEnvironmentService environment, + IAuthenticationTokensRepository tokens, Lazy session, ICloudSessionConnectionRepository sessionConnection) { _applicationSettingsRepository = applicationSettingsManager; _connectionService = connectionService; _logger = logger; + _environment = environment; + _tokens = tokens; + _session = session; + _sessionConnection = sessionConnection; } public PublicKeyInfo GetMyPublicKeyInfo() @@ -161,18 +177,39 @@ public void Delete(TrustedPublicKey trustedPublicKey) _logger.LogInformation("Removed Trusted Public Key {@publicKey}", trustedPublicKey); } - public void InitializeRsaAndTrustedPublicKeys() + public async Task InitializeRsaAndTrustedPublicKeys() { - var updatedSettings = _applicationSettingsRepository.UpdateCurrentApplicationSettings(settings => + await _renewalGate.WaitAsync(); + try { - settings.InitializeRsa(); - settings.InitializeTrustedPublicKeys(); - }); - - _logger.LogInformation("Initialized Local RSA Keys and removed all Trusted Public Keys"); - _logger.LogInformation("ClientId is now {@clientId}", updatedSettings.ClientId); + if (_session.Value.CurrentSession != null || _sessionConnection.CurrentConnectionStatus != SessionConnectionStatus.NoSession || + _connectionService.IsStarting || _connectionService.CurrentConnectionStatus == ByteSync.Business.Communications.ConnectionStatuses.Connecting) + throw new InvalidOperationException("Leave the current session and wait for the connection to finish before renewing the key"); + var reconnect = _connectionService.CurrentConnectionStatus == ConnectionStatuses.Connected; + await _connectionService.StopConnection(); + if (_session.Value.CurrentSession != null || _sessionConnection.CurrentConnectionStatus != SessionConnectionStatus.NoSession) + throw new InvalidOperationException("A session started while stopping the connection; the key was not renewed"); + _connectionService.CurrentEndPoint = null; + await _tokens.Clear(); + var updatedSettings = _applicationSettingsRepository.UpdateCurrentApplicationSettings(settings => + { + settings.InitializeRsa(); + settings.InitializeTrustedPublicKeys(); + _environment.SetClientIdentity(settings.ClientId, AuthenticationProtocol.GetIdentity(settings.DecodedRsaPublicKey!)); + }); + _logger.LogInformation("Initialized Local RSA Keys and removed all Trusted Public Keys"); + _logger.LogInformation("ClientId is now {@clientId}", updatedSettings.ClientId); + if (reconnect) _ = ReconnectAfterRenewal(); + } + finally { _renewalGate.Release(); } } - + + private async Task ReconnectAfterRenewal() + { + try { await _connectionService.StartConnectionAsync(); } + catch (Exception ex) { _logger.LogError(ex, "The key was renewed but reconnection failed"); } + } + public byte[] DecryptBytes(byte[] messageToDecrypt) { // On décrypte avec la clé privée diff --git a/src/ByteSync.Client/ViewModels/TrustedNetworks/TrustedNetworkViewModel.cs b/src/ByteSync.Client/ViewModels/TrustedNetworks/TrustedNetworkViewModel.cs index d911a897d..160ac8111 100644 --- a/src/ByteSync.Client/ViewModels/TrustedNetworks/TrustedNetworkViewModel.cs +++ b/src/ByteSync.Client/ViewModels/TrustedNetworks/TrustedNetworkViewModel.cs @@ -1,4 +1,9 @@ -using System.Reactive; +using ByteSync.Interfaces.Services.Sessions; +using ByteSync.Interfaces.Services.Communications; +using ByteSync.Interfaces.Repositories; +using ByteSync.Business.Sessions; +using ByteSync.Business.Communications; +using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Runtime.CompilerServices; @@ -40,7 +45,8 @@ public TrustedNetworkViewModel() public TrustedNetworkViewModel(IPublicKeysManager publicKeysManager, IApplicationSettingsRepository applicationSettingsManager, TrustedPublicKeysViewModel trustedPublicKeysViewModel, - IMessageBoxViewModelFactory messageBoxViewModelFactory) + IMessageBoxViewModelFactory messageBoxViewModelFactory, ISessionService session, + ICloudSessionConnectionRepository sessionConnection, IConnectionService connection) { #if DEBUG if (Design.IsDesignMode) @@ -56,7 +62,11 @@ public TrustedNetworkViewModel(IPublicKeysManager publicKeysManager, _messageBoxViewModelFactory = messageBoxViewModelFactory; var canRun = new BehaviorSubject(true); - RenewPublicKeyCommand = ReactiveCommand.CreateFromTask(RenewPublicKey, canRun); + var canRenew = Observable.CombineLatest(canRun, session.SessionObservable, + sessionConnection.ConnectionStatusObservable, connection.ConnectionStatus, + (idle, currentSession, sessionStatus, connectionStatus) => idle && currentSession == null && + sessionStatus == SessionConnectionStatus.NoSession && connectionStatus != ConnectionStatuses.Connecting); + RenewPublicKeyCommand = ReactiveCommand.CreateFromTask(RenewPublicKey, canRenew); DeleteTrustedPublicKeyCommand = ReactiveCommand.CreateFromTask(DeleteTrustedPublicKey, canRun); Observable.Merge(RenewPublicKeyCommand.IsExecuting, DeleteTrustedPublicKeyCommand.IsExecuting) .Select(executing => !executing).Subscribe(canRun); @@ -95,12 +105,12 @@ private async Task DeleteTrustedPublicKey(TrustedPublicKeyViewModel trustedPubli await AskAndDo(nameof(Resources.TrustedPublicKeyView_DeleteTrustedPublicKey_Title), nameof(Resources.TrustedPublicKeyView_DeleteTrustedPublicKey_Message), new string[] {trustedPublicKeyViewModel.ClientId, trustedPublicKeyViewModel.TrustedPublicKey.PublicKeyHash}, - () => _publicKeysManager.Delete(trustedPublicKeyViewModel.TrustedPublicKey)); + () => { _publicKeysManager.Delete(trustedPublicKeyViewModel.TrustedPublicKey); return Task.CompletedTask; }); TrustedPublicKeys.Refresh(); } - private async Task AskAndDo(string title, string message, string[]? messageArguments, Action action, + private async Task AskAndDo(string title, string message, string[]? messageArguments, Func action, [CallerMemberName] string caller = "") { try @@ -112,7 +122,7 @@ private async Task AskAndDo(string title, string message, string[]? messageArgum if (result == MessageBoxResult.Yes) { - action.Invoke(); + await action(); } } catch (Exception ex) diff --git a/src/ByteSync.Client/Views/TrustedNetworks/TrustedNetworkView.axaml b/src/ByteSync.Client/Views/TrustedNetworks/TrustedNetworkView.axaml index 9847e098e..a0b00540f 100644 --- a/src/ByteSync.Client/Views/TrustedNetworks/TrustedNetworkView.axaml +++ b/src/ByteSync.Client/Views/TrustedNetworks/TrustedNetworkView.axaml @@ -16,6 +16,7 @@