Skip to content

V- Modal AI: Visual Video / Image Search - Flutter Video SDK

Release Flutter SDK from c57d6e2a61491ae49eaba8345677fd0d08ef2dec

vmodal-release-app3c950dc58860
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4548748..84263c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,16 @@
+----------------------------------------------------------
+date: 2026-10-02
+commit_hash: e02e2e15a2d2eb6af43125e89dc4e5bef904ce20
+title: Isolate app-user sessions under shared tenant credentials
+summary:
+ - Added immutable app-user contexts, guarded session operations, and synchronous account-switch invalidation.
+ - Coordinated tenant credential rotation independently from app-user identity.
+ - Partitioned checkpoints and Framebase archives by service, tenant, user, and scope.
+
+## 1.3.0
+
+Opt-in app-user sessions with guarded operations and tenant credential rotation.
+
----------------------------------------------------------
----------------------------------------------------------
date: 2026-09-30
diff --git a/README.md b/README.md
index b6bd470..f61a378 100644
--- a/README.md
+++ b/README.md
@@ -107,6 +107,11 @@ release, replace the `ref` above with the full 40-character commit SHA from the
public repository. The `main` branch is suitable for evaluation and development
only; it is not a production pin.
+The opt-in user-session API below is part of the **1.3.0 source release**.
+Use that released public source revision for it; the `1.2.3` package and tag
+shown above do not contain these additions. A source-only GitHub Actions export
+does not publish `1.3.0` to pub.dev or create a version tag.
+
Then run:
```bash
@@ -136,7 +141,89 @@ collection names cannot contain the reserved `__` separator, and their encoded
backend value is also limited to 80 characters. The SDK performs that encoding
internally.
-> The SDK never owns your login screen or persists your API key. Authentication identity is separate from project, collection, and stream organization.
+> The SDK never owns your login screen or persists your API key. Authentication identity is separate from project, collection, and stream organization. `VModalProject` and `VmodalClient` provide tenant-scoped access; use `UserSessionManager` below for app-user isolation.
+
+## Isolate signed-in app users sharing one tenant key
+
+Your authenticated host app resolves a stable user ID and its allowed content
+mapping. VModal's API key and `auth.me()` identify the tenant principal; A and B
+may use exactly the same key and principal. Neither value identifies the app
+user. Keep app-user identity out of `SdkConfig.userId` and `X-User-Id`.
+
+```dart
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+
+Future<void> openLibrary({
+ required String runtimeTenantKey,
+ required String tenantId,
+ required String tenantPrincipal,
+ required String authenticatedAppUserId,
+ required String issuedCollectionId,
+}) async {
+ final config = SdkConfig(); // gateway mode, existing connection defaults
+ final credentials = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: tenantId,
+ expectedPrincipal: tenantPrincipal,
+ initialKey: runtimeTenantKey,
+ );
+ final manager = UserSessionManager(
+ config: config,
+ credentialSource: credentials,
+ );
+ final mapping = ContentMapping.opaque(
+ collectionId: issuedCollectionId, // trusted host mapping, unchanged on wire
+ streamName: 'favorites',
+ actions: {UserAction.discover, UserAction.search, UserAction.media},
+ );
+ try {
+ final session = await manager.openUserSession(
+ tenantId: tenantId,
+ appUserId: authenticatedAppUserId,
+ allowedContentMapping: [mapping],
+ );
+ await session.verifyPrincipal(tenantPrincipal); // optional tenant check
+ final collections = await session.listCollections();
+ if (!collections.contains(mapping)) return;
+ final scope = session.scope(mapping);
+ final results = await scope.search('cyclist crossing a bridge');
+ for (final hit in results.videoHits) {
+ print('${hit.fileName}: ${hit.playbackOffsetMs} ms');
+ }
+ if (results.assets.isNotEmpty) {
+ final frame = await scope.imageBytes(results.assets.first);
+ print('${frame.length} image bytes');
+ }
+ } finally {
+ await manager.close();
+ credentials.close();
+ }
+}
+```
+
+Retain one manager for the app's identity flow. Starting another activation or
+calling `manager.logout()` invalidates the outgoing session synchronously.
+Every activation receives a new runtime `sessionId`, private provider/client,
+and owned transports. Old scopes cannot dispatch, deliver late search data,
+or forward upload progress after invalidation; cancellation settles even when
+an underlying custom transport ignores it. Host code must also check the view
+generation and clear already displayed images, players, routes, and histories.
+
+`ContentMapping.logical(projectId: ..., collectionName: ..., streamName: ...)`
+uses the existing `project__collection` encoding. `ContentMapping.opaque(...)`
+preserves the backend collection ID. Actions and collection-wide access come
+from trusted host policy. Collection/index deletion requires both
+`UserAction.delete` and `collectionWide: true`.
+
+This is a guarantee for operations through `UserSession` and `UserScope`.
+`VmodalClient`, `VModalProject`, arbitrary HTTP, and raw media/storage helpers
+bypass it. A modified client holding the shared tenant key can make arbitrary
+tenant-authorized requests; server protection requires separately verified
+app-user authorization. The SDK cannot recall data returned while A was active
+or stop work already accepted by the server. Read the
+[session contract](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/sdk_contract.md)
+and [tenant-key rotation guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/manage_api_key.md)
+before integration.
## Search video with natural language
@@ -166,15 +253,19 @@ for (final hit in results.videoHits) {
`VideoSearchHit.distance` is the raw lower-is-better distance; it is not a
similarity or confidence score. `assetId` remains `null` when an older server
does not return `asset_id`—the SDK never invents stable identity from a
-filename, path, frame identifier, or timestamp. The original entries remain
-available through `results.data` and each hit's `raw` map for compatibility.
+filename, path, frame identifier, or timestamp. The original entries from the
+tenant-scoped facade remain available through `results.data` and each hit's
+`raw` map for compatibility. Session-bound search instead exposes allowlisted
+fields, recomputed returned-row counts, and live `SessionAsset` handles; signed
+URLs and nested tenant metadata stay private.
Collection access is key-scoped. A logical name copied from another account or
environment can return HTTP 404 even when the search route is healthy. Use
`ScopedSearchOptions(versionLancedb: version)` when your application tracks a
specific index version.
-The response stays typed where the contract is stable and preserves the raw JSON so new server fields remain available immediately.
+The tenant-scoped response stays typed where the contract is stable and
+preserves the raw JSON so new server fields remain available immediately.
## Upload with progress and cancellation
@@ -266,10 +357,17 @@ for limits, timeout behavior, and the benchmark command.
- Keep file picking, secure storage, background scheduling, and lifecycle UI in the parent app.
- Close network resources deterministically with `await project.close()`.
-For logout or account switching, cancel active work, clear upload persistence,
-call `keys.clear()`, close the project, and create a new project and scopes for
-the next identity. Key rotation alone is not an identity, project, collection,
-or stream switch.
+For applications using the session API, call `manager.logout()` or activate
+the next authenticated policy through the manager, and clear host UI state.
+Owner-partitioned archives and checkpoints remain available for a validated
+return to that user. Install tenant key replacements through
+`TenantCredentialSource.install(...)`; rotation preserves the active session,
+owner namespace, and policy. A policy or tenant change requires fresh sessions.
+
+With the older tenant-scoped API, the host owns all isolation: cancel work,
+close its private provider and project, partition checkpoints, and create fresh
+state for the next identity. Closing a client alone does not isolate the default
+process-global multipart checkpoint store.
## Common organization flows
diff --git a/RELEASE_METADATA b/RELEASE_METADATA
index 094287c..3e79474 100644
--- a/RELEASE_METADATA
+++ b/RELEASE_METADATA
@@ -1 +1 @@
-Source-vmx-api: 1e4c9d590661782c733b6119a1acf76cb6b79670
+Source-vmx-api: c57d6e2a61491ae49eaba8345677fd0d08ef2dec
diff --git a/SOURCE_MANIFEST.sha256 b/SOURCE_MANIFEST.sha256
index 6b1c8c1..6de7cee 100644
--- a/SOURCE_MANIFEST.sha256
+++ b/SOURCE_MANIFEST.sha256
@@ -2,20 +2,21 @@ e789cd4d1bed8a78ec8014c5c5913e300f81b63ea56a56aacb0dfec3b5e7ce2b ./.flutter-ver
a3e3ce18f80b46587bcd529d13e456d10d97dd5e4a3f15e8e1a18894961120b1 ./.github/workflows/publish.yml
992d54be0fbdaf0ef52be1bb80a3985af67defed270f4343aa9ee27465f6a49e ./.gitleaks.toml
efaab625b09d5b5bb80352b0586e4f81764914a1aff24164e338b6a95fee5973 ./.pubignore
-5b29f2e6863615d3ed18f9a464c06ce1e4832b9b2103b159573edcf31caff090 ./CHANGELOG.md
+abdc15ffd2312caa935bd8eeb30485b42654c146ded001997cfa240e9a77c7b2 ./CHANGELOG.md
37b7148216ac6090e36adfb699d642b8dd1e1b8ba99870e65e88733947a59fa6 ./LICENSE
-24f8ccbc0f0ffaf43dff1c74c4712fbe3141bf3fc834f092646d39ca3402fd22 ./README.md
-08ebe9e7d7841b3a238e386a1f85230dc6cfbf1a9efcbf1f8ef0fa44a36e08b8 ./RELEASE_METADATA
+4399569e64f4d4b73efcbcfc7e2a53e2feb175374999445819933931e38796bc ./README.md
+cd94cbe58cf0c3674081d65766343d61ba9239ec51386a6b24b5aa28f1c947bd ./RELEASE_METADATA
def7e4f643adff5b01b877b6a7fa5b2381612b693c0bf06bd232ee0f7197d342 ./analysis_options.yaml
5aeee476843e07c110c4525685fb6b875fa28824e26eae514f345d593126df48 ./build.sh
4f18642680fb433554a5523d00bd99e0d650af340bcaebe628f59f63ac84e458 ./dartdoc_options.yaml
-75461620cf3a062f4dad10e034952b82cca461b483788de1f46c539aca8b0f0f ./doc/manage_api_key.md
+e5120a94a88f2260b1d0264af7820d95a87cca8727c698f9047e1feae4d1d288 ./doc/manage_api_key.md
a66d39da0983a994474fa516f81fd41bbb131efbd69c955891a41781a76daf24 ./doc/performance.md
c59892e1edadebe19a9bc5211f6d6a2f38ad0aece15d6505f8237405f152896e ./doc/release.md
-97c81876aa73762589a794c6d89592dd5500f9b196bf3d8a8b0e5171425a5b48 ./doc/sdk_contract.md
+97e9a1dcc98b831c5b72bfa80bd1f595fbff17266b6d42a2dd77ee75430cef20 ./doc/sdk_contract.md
98db54c31211074fa4176208662dd5b9e09e6d724a6dab2b22fc90b138a9f9e6 ./doc/sdk_doc.md
4aad6c643677dbefdd7fd7ac1aef865dd8c1640a6d98292facb28bcdcc8904a0 ./doc/search_app.md
7b0acfc01cfa4c8bf3af8aeb19741e65b8e9406935d9ab8e0f4cb84547483e55 ./doc/transcode_360.md
+b7048ea33737815eeb8227a705a3629b13364ed0be0b1c74b284998d5821d372 ./doc/user_session_implementation.md
e246ed229511a24a1ee7e98529c203ef90d1d352290ce8486caebe05683db3a0 ./env.sh
c5ce516b547327aab5b6fa27a523d4c76e66294ada3248b293c54b9595cd3a87 ./example/01_full_app/.metadata
7b50a141c330c810a229422ca37d5ca28d34b9a9ec2ac701ec38d7bb1f49c8fb ./example/01_full_app/README.md
@@ -79,7 +80,7 @@ fd367b6c43006d61b730f674970dd48b9f662c8f2264e52ffc1558102a2c9f2d ./example/01_f
add68b905971dedfcc0d0b5b7118030de5925ba8c081ad9815463699e3a444ad ./example/01_full_app/ios/Runner/SceneDelegate.swift
5e8f4908dacea6f29b2a790e4d38bf5fded69096063f9a27a2f21584d62b30c0 ./example/01_full_app/ios/RunnerTests/RunnerTests.swift
f008f1671accf86a236929d5163da59f7e53015a53ef1578a5e8c31699077311 ./example/01_full_app/lib/main.dart
-cf99105e6be45075064ea9282274d1d54f336ebcabccb85c679dd56c665b9140 ./example/01_full_app/pubspec.lock
+ae444b771922a4bee02c478f71bb96f1dcfa9589903703d42a6bfa90ccead94f ./example/01_full_app/pubspec.lock
875af508f7c6d9654985b402c26364d4ca6b1c06b3846a71a77997b905e2ad6e ./example/01_full_app/pubspec.yaml
90a79c18d158515dab7616e273e9effd9cc0726c56fe6ce3cc123b5a8a8337cc ./example/01_full_app/test/widget_test.dart
3c54909945bc3d6fe78d70a0f673377b6ab6b0c6c4b86c02291f5fbefdc9736f ./example/02_users/README.md
@@ -90,14 +91,14 @@ a15f6dfd128db08dff98caa715b2c5041812f794fbfe283098bb98b94b345841 ./example/02_u
b373342c889d099d99a3209cb01cea188b53eb5b43ae26cad952abf5fda833bd ./example/02_users/lib/src/example_session.dart
94fc4c3cfb6774eee9f39c1d97447abab52105ce6be85457d8f9d25bff3014ab ./example/02_users/lib/user_examples.dart
4d7075d4d50457aa65b2a91d4bcdf9778ae95e86c6c276a91172dcc5cd60017c ./example/02_users/lib/user_streams.dart
-383d8d017d19c0b7ec23614a4764490d747cd5e6614efc551e76311bad9db940 ./example/02_users/pubspec.lock
+373c85e75f5d8dfbe47563bf0faa4da6090aa96c136e94b0c022083a1b129ee4 ./example/02_users/pubspec.lock
fa541e11cb4b9b791630b658c6856743ec4c31d957deb285ed031e7d4c2d48c6 ./example/02_users/pubspec.yaml
31f28ca22dfb931fe963d2f766d8b5cba3c2722bca839787a506f1a692393a8c ./example/02_users/test/user_examples_test.dart
07f4acf99d24207114fa46b36147cbaebfa1c98f91d580bb2b1d499d3aeb91ed ./example/03_cctv/README.md
bf7d17dfdbc3aa4dcba00ef52506c50fd798bbcf3d0f907e875fa38bdfa9846f ./example/03_cctv/analysis_options.yaml
09ae9ca601d1c8c20db6251a99321b28ec84ed0ba1cac471eb6bafecefadb058 ./example/03_cctv/bin/main.dart
ea733b67f97cf5a32bf2b8ea1ee0d10460ac881690d6bc04ec15126ca166291c ./example/03_cctv/lib/cctv_example.dart
-1d42fb123cb7b01094b725c57992170000b45e266f0455cc245ea79c3774e053 ./example/03_cctv/pubspec.lock
+4d852e199f68d2b88ddba19e18f797b7a63d809ac78adb059709670c2ab7e774 ./example/03_cctv/pubspec.lock
6cc52ddfa3d5b698f245b23cf4565367dafe232a8831daeb5fb3f5d25728cb07 ./example/03_cctv/pubspec.yaml
dd42921f5d6ee8fa50765aee06d59df7329d8bd27139eac02b716d14062e1c0c ./example/03_cctv/test/cctv_example_test.dart
c5ce516b547327aab5b6fa27a523d4c76e66294ada3248b293c54b9595cd3a87 ./example/04_example/.metadata
@@ -182,7 +183,7 @@ cb0d6fd845a0ffea43094b027b339e777d217524b33ade5c8b21f426477061a6 ./example/04_e
fb12dfa3d0aefe97df64955243a9a7d126e76e789644ac433dad431e53912ff8 ./example/04_example/lib/settings.dart
cbe9e32f3338270ff53b3a33f84e9b062bcf860a927f4b227afe846df82a4f0b ./example/04_example/lib/theme.dart
9c7fa46ef347188b0b6782d87c8e4d4f15503899b99ad408dc969ce1691ad96a ./example/04_example/lib/widgets.dart
-0e7795efff711d84403d1f4c9a9c6584ba96f0b4439aa81b2d44a59641d95f4c ./example/04_example/pubspec.lock
+efefef22748245697f7a23a41f9e7ab003c4d5528d4f190c420cc9af38a260af ./example/04_example/pubspec.lock
cd5b582104b7f453d7f1e628f633d3f89a199f52cc6cec0b4c083e5526e8a967 ./example/04_example/pubspec.yaml
00988c2faa386c1c100b4713c51bb298c06a21d01395760f63ce3f58ebc606cf ./example/04_example/test/widget_test.dart
cb335a6997ddec7208a31edea88cbf7df3a5af67d891116a54ff74fab4bf37b4 ./example/04_example/test_driver/integration_test.dart
@@ -269,7 +270,7 @@ c783830af58111d94c3e78a705865468fa3ba8f59cc5bef833404d7ac3567119 ./example/05_f
4ecc92b82356d3fc31b7573caa8b9608dafb3af44dfe6f99b9f3ab93b4693500 ./example/05_framebase_userlogin/.metadata
bc001543e1418412ce7879a5c46d40ef1b3c485d8ba2b9a343bf7104b17e360c ./example/05_framebase_userlogin/LICENSE
559a8b6846e28399e68511e778cb7ea4b0390cf38fd87a9936414711bca72947 ./example/05_framebase_userlogin/MEDIA_SOURCES.md
-581c40688b944e039a33899303faf8fd7344663c5118773c722bbf899716a082 ./example/05_framebase_userlogin/README.md
+61048efeb84d8df2a309039a14a3d735ba6f39f112d601d4097d7ebd79a4b281 ./example/05_framebase_userlogin/README.md
e0ea485cfdbc3e12b93efb8679a5ea73ebfe20ea4ca0c473dc594fc2fb274ed5 ./example/05_framebase_userlogin/analysis_options.yaml
6939878d0e417b29be6738e9c57772fc8a22a9aab5db39ae7fa867848d09d089 ./example/05_framebase_userlogin/android/app/build.gradle.kts
4e4a0e0726baf45d2d878ea5d0e0666e08ea6e9dbdc33ecd2a74a3525cf5ba51 ./example/05_framebase_userlogin/android/app/src/debug/AndroidManifest.xml
@@ -337,77 +338,88 @@ fd367b6c43006d61b730f674970dd48b9f662c8f2264e52ffc1558102a2c9f2d ./example/05_f
1a8d11d01d1cc92c650c9c9ed35299240052d4683a15a719a2315ef44185e074 ./example/05_framebase_userlogin/ios/Runner/Runner-Bridging-Header.h
add68b905971dedfcc0d0b5b7118030de5925ba8c081ad9815463699e3a444ad ./example/05_framebase_userlogin/ios/Runner/SceneDelegate.swift
5e8f4908dacea6f29b2a790e4d38bf5fded69096063f9a27a2f21584d62b30c0 ./example/05_framebase_userlogin/ios/RunnerTests/RunnerTests.swift
-33ac5f6b1c52ca80d0e7a53539881a565cf8cc7a3f69ce945bfcf832bf706607 ./example/05_framebase_userlogin/lib/data/archive_controller.dart
-996a045adfd44031d6e1a6ba5a962525791e0e6bfa0ad0232f2c223e902fc90b ./example/05_framebase_userlogin/lib/data/search_gateway.dart
-b1771f392ee3f7b13f2d50c03a7f5533f66eb83c019c1e376cdb94e9673285b3 ./example/05_framebase_userlogin/lib/main.dart
+ee3a2066d3746ff08ad0322d65b0ed548251b91b77328ed7a561e68f1b197fd2 ./example/05_framebase_userlogin/lib/data/archive_controller.dart
+db2d3fa4e577426833efdcf92c7434aa26b1fe715167078c1ebd6d0524457d23 ./example/05_framebase_userlogin/lib/data/search_gateway.dart
+b461335537586cf15f63deeb451c0d3e89b3970e2d18a9e41cf6a026d088b666 ./example/05_framebase_userlogin/lib/main.dart
79223e647a2f81538c58b21856ee5a231a3bd4e45dfcd3ba784405d4f0fd0ac9 ./example/05_framebase_userlogin/lib/user/auth_adapter.dart
c2ec078652813b9c8a875e436e29cc92c64f564aac1e96d7ed215e24ed43c006 ./example/05_framebase_userlogin/lib/user/library_scope.dart
-2ac441b32baf95eeaba9f53afc297016af9a3389cbc26b4a3c702a0c602d817c ./example/05_framebase_userlogin/lib/user/login_page.dart
+76e0c7e53ec567c9d0e54419819e30b43861dde5562995df531119620f1747d7 ./example/05_framebase_userlogin/lib/user/login_page.dart
d34a3e5ea1783adcaeac1bb3abb9c0760b7d2355279b9e442e78d93c70c0c728 ./example/05_framebase_userlogin/lib/user/mock_firebase_auth.dart
-c39791c305e72ea92656df28f490f613330b79e8ccce46e14e6b5858dd4b9f7c ./example/05_framebase_userlogin/lib/user/user_session_controller.dart
-94f19c14a447d8a6840173b7d2bd518c1456972883893ef4c3f65c153b5017b3 ./example/05_framebase_userlogin/lib/user/vmodal_credential.dart
-38915e998b313d617db841f46ae5bf293a06bc813791ec3adb7dfd245ec549c1 ./example/05_framebase_userlogin/pubspec.lock
-d127d3f4cd96b63ab036c263e488f8af91a5140be12768b0e3cd0904193676d5 ./example/05_framebase_userlogin/pubspec.yaml
+2d1006c592f1584b282e59032dce15eee1cb8a30e3880683f0142a7ba652316f ./example/05_framebase_userlogin/lib/user/user_session_controller.dart
+549f8cd7efc204ff7fedbeb4c0da8753396215d6371511c0cf0be3a493913238 ./example/05_framebase_userlogin/lib/user/vmodal_credential.dart
+1599466e4f82a4fb17e9666786c86bd9b6d79fffa449ff83bdebcbb31c81006f ./example/05_framebase_userlogin/pubspec.lock
+755c985897825a0c711e9b8d0defc1e4570b68898d02513bb9b6fc9d78704775 ./example/05_framebase_userlogin/pubspec.yaml
5ac0550b52416cec8dd4f01d0cf8622dc696a235502aedbb7a291a13594eac02 ./example/05_framebase_userlogin/readme_assets/library.png
1af691525fbc6b8c558690bdc651d0bfc76b09116caa59835f27d552b456239e ./example/05_framebase_userlogin/readme_assets/playback.png
1fc9b69f52a19ed05d741b4cf71bea35daac8b684977fb73909c97a65b0f9d24 ./example/05_framebase_userlogin/readme_assets/search.png
-89b8437232d2fcdef45c8b658fba2785541528e705bc6d88ce567b1b0e86137d ./example/05_framebase_userlogin/test/archive_controller_test.dart
+f27c08866a0838395127a94e53f7d16e02d1c33afa0feeb2322d0a13227435d4 ./example/05_framebase_userlogin/test/archive_controller_test.dart
6a12566076d8e0493fc73589445f256739d6fcd882fc62dd0aae2aa6de51ed94 ./example/05_framebase_userlogin/test/library_scope_test.dart
-7d4e31013658ad77d3392a169c1038e99d0229bb0ed3213706559a7510964171 ./example/05_framebase_userlogin/test/search_gateway_test.dart
-417dac72f4059de5a71a1cdec4daf62c5f2f047eb006512b3f1d140cf4e63da8 ./example/05_framebase_userlogin/test/user_session_controller_test.dart
-1faebf8598db4d0ea84a98439fa06fcf59b6841d1f7dc49d724e70f7816430a5 ./example/05_framebase_userlogin/test/widget_test.dart
+5aff9ef4ed7a7f4846a50ee1e019f4ccda6bcdc8c0809324dd9ec36813a0664d ./example/05_framebase_userlogin/test/search_gateway_test.dart
+a51475dbc546a45bb5cbc6d85bbd39a5e84a4ca1c8c27402f4d1d7ab8c4e8e29 ./example/05_framebase_userlogin/test/session_fixture.dart
+b3f31425c264023e88a1f9ce82efdf619bb1ed80c69bcd454b11125a29f97977 ./example/05_framebase_userlogin/test/user_session_controller_test.dart
+8a1cd1f781e0c217df5c6676557e87ff1ebdb480b6b73e5db64a407164d661b8 ./example/05_framebase_userlogin/test/user_session_failures_test.dart
+5e3939495af84efeb41a736e11e3d8a9e55954da304dc16d6f646b04baa0399f ./example/05_framebase_userlogin/test/widget_test.dart
bb2e66ce21a066b5331a8c6ee665f1a4d2fcb3451cde5ce2ba0e6fe492344ac0 ./example/readme.md
23756b83470b1f25f6a7e6b5a6270f123a5224e49fd8e2eda36001358951b688 ./install.sh
7becacd31a8d134fa435b39cd819798d5fbf58f89b9f30c50362e2dcf757aaed ./lib/src/adaptive_upload.dart
-9464fff0c519a1ce70cddefb3e3eaa95d07b97ccdaf5b8381c01d7c88767ae83 ./lib/src/api_key_provider.dart
-9c8a5a834352d6c417fb1fd9793f427252fced588ff3e126493ea6f9c80cf474 ./lib/src/client.dart
+3266fb275cbf5634bc9122b27e30cc86f36a8c606eca2d1efd0ad34effe37ce6 ./lib/src/api_key_provider.dart
+23bfe683fe220a98ef960e89bf4a024b57d472d3da652c46a5e39697dba6251f ./lib/src/client.dart
56854450130793060945446c9d4f812dab1ef80de83c51db5f9f4fdc13851c9d ./lib/src/collection_uploads.dart
3591a3bfd33164aadcd65b5d5b02bafc5f36b577a304a0e87bec8fb7ac34bb8b ./lib/src/config.dart
d3e03d9a72a499659c70f2296115d1d3138b9370a017e027d8255f85f7fb1c5c ./lib/src/content_scope.dart
-873d969cfed5c725d34df0fd0c8769462b56992cf523710fcf741a81fa1bbcad ./lib/src/errors.dart
-027174edd680e69e067453695f62680fd90b16c78f74a6999ab926cd2fd257dc ./lib/src/http.dart
+f5f0f63de2c13aca3813acf91fe8031ae388494db345450a14e4515086ddb176 ./lib/src/errors.dart
+0801d536afa98f714a4df66a661c5c5de87a750b2db7e49a0238678d39cc1f83 ./lib/src/http.dart
edd4993e3f56b492b19430a6eb52646d52052a8b8b9a98d7bce784da41195ef9 ./lib/src/models.dart
1612baa4be9d9f1489673ea1368698209fbca9199e9f927a114d696a413deb09 ./lib/src/resources.dart
43770c621bffccf69eacebd1e3b297503ca288093c848f0e8ccbd118d7f0d88a ./lib/src/routes.dart
27056230065682f3ea3aa747c39c08950dcdca87387f4733adfad18f4b345b06 ./lib/src/routes.g.dart
+d8bb946941c49cd18cc11190b909a3a70411a956ec143ccf2a1caf2e1194e7a6 ./lib/src/session_guard.dart
42331852249c8f99874a5e3889c752fd344ad8a5301ede246d5a4fbccb4191f2 ./lib/src/transcode.dart
-362f472ea7ed5ec09dc0272239865ac12100a8c2fa3f73f45ccfeaedebe77395 ./lib/src/transport.dart
-8a9ab7a18da892c10f4004d0188f71cf60c31d3207b08617d70f0a7e4fde4d0e ./lib/src/upload.dart
+b7f65edb62ce973e55e692a1e20a9f34acb8bf5b82573e4a47551c6d4c32ad45 ./lib/src/transport.dart
+40c6fde33466faad146ca0ffe24c92ab40b0ed356fd41b0e04f864b6d7747fca ./lib/src/upload.dart
+381b448154db5bc7b7969465b7589e0dce1c2018db27281eb96c097f8bec1645 ./lib/src/user_session.dart
655a7627df6b9db8059dadd5a7f61c796e8e8da39b7210ce291ac9189027a7fd ./lib/src/utils.dart
fded09f674653828d4cc95bceacac01018d4783cc584ef8eb816edb25e1f8831 ./lib/src/vmodal.dart
-14f02410389d19abb09ca40ff69c6267f3ad0b8b40ab115aa6e2c76bf43bfeef ./lib/vmodal_sdk_flutter.dart
+7207c5bfb20c0810c9b45b2bc835afeda9ed5ee6bf32b7f9da3a9547eaaaa48d ./lib/vmodal_sdk_flutter.dart
72fff91181fd3e25fd9afd766930a67025205b61096fd35c55cbdd9a3178ecf0 ./pubspec.lock
-b71f6aaaac229ea700bda226ee1dd3cf53e549a1d7ef8f03399b6c75086ad78b ./pubspec.yaml
+c2054b07765ac3d058dc8d1e313516b2e6b9ec8b04db7862b9e2d073346325ce ./pubspec.yaml
387ec75b8a58410c403abd622bc6627d194a2fa4b839c549600cc0ea28b50f67 ./readme_assets/app1.png
ecf9d38677ac502250e93353ce7784aa8685c725e73e5dcfc744a1f9d4eb0651 ./readme_assets/app2.png
93db32456ccda95d5b5bfea658e6e1b8088dc65f0166517e5b1a46bf54028405 ./readme_assets/app3.png
5ecf57fdb27bab2ba7966384beefe5c4641a257e4bfd3c9cbeb2c7f3d18fb08d ./readme_assets/app5.png
a80b38547f5d9ca1874f60e71c648e3fc12ab5f7cb88d1bead6d5b863d3c0245 ./readme_assets/dev_homepage.jpg
c56419d129059b64551e06f074e88ef62676f25938dc2a1fe28a6ab3f2ba8547 ./readme_assets/logo_vmodal_owl.jpeg
-efec1544082870ed0079302d6ed6d266b5ce543bb42fa44042c385a343e894d2 ./release_note.md
+87cfc21f3c3539fc539c68a534eb84760d3c297cd8989576acd55ecf035e6012 ./release_note.md
3198051c448338c5331baef7e17ff32bfbaf1265b59543a8aca2baf57513feed ./run.sh
bb5948fd73afd0adfbc1fa34addb946ae688fc8e03f4c54a17c4b067f0679b3d ./security_check.sh
75d9810c9d50fd1224462aba8d2d1669cbfa094bd9cc0e5275f3a6a9f1364cb5 ./test.sh
be59599b9ba77d031e9b4bad7f8d5c59efd2687888c5b73be4fbea115902106b ./test/adaptive_upload_test.dart
-002abcc5d95c0cf20375adefe4ee2472581a615e64f5726bf361dd5c679cdea7 ./test/auth_http_test.dart
+8d138ac9ba874307aa11cbd873eded2c913167475db550f79a697f696df1287c ./test/auth_http_test.dart
51001c445940a527271418f3eded8af669dd1eb6c450504e9dd1f12ec16d66a0 ./test/cctv_contract_test.dart
3cb772c473b1657f2aaeebd8281e4d9cfee1aaa10b70badb70a1df8d5d7bc389 ./test/client_test.dart
56eb465d0c149368f68dce9d54e48ad8f61476b912525d5783fac7de7b7c2943 ./test/config_routes_test.dart
-4d65cc6e6f2bcfb1d0fc42bc38e0106daf46c0de8e5c4c53c7a997df3f9a7bab ./test/docs_reference_test.dart
+e1f8d5e754fc698b827cb6974c9830c9620e0f905216f3d81d26c29bb3462780 ./test/docs_reference_test.dart
b45470d8e7674bcb87828a8dcf231ac29afb4418774972c66e60cea9788270db ./test/errors_leak_test.dart
d132b6dceb89804a47418245845547a25fcf8f89f56b292ee70a404d63364865 ./test/fakes.dart
0a1394c90829b91541aa01e9786e3195aae04fc49a7b92775dbf404bf2802107 ./test/fakes_test.dart
14368b598ece0ce9b2e249148a10a92f2c80e38427c077013a1515826f4365bd ./test/fixtures/routes_contract.json
593b356ac3431de80e03e7a0e2f1df0d29589140f44746468213c1cac1c35bbe ./test/multipart_upload_test.dart
1247019fcd0549fab4bb48fa9aeee438ea288cc1e73561c46ca7dd6598170d14 ./test/new_api_surface_test.dart
-ee8fbc92ad32387a834cb9f1fd082487e765409337e381c8f87fbaa8f6ac6249 ./test/readme_pin_test.dart
-24526adae4d56282d2780d5653727a62ebca6fcfdf1be89486ac374bf9d0e6ba ./test/regression_manifest_test.dart
+97593b7d76911b80a27a7f2ea2bcf283986e881d2bbb1347478ef5241c6a67f9 ./test/readme_pin_test.dart
+4819fd5a6d02c97c0c47b137ef0a9860034929e8695325a2c6de8ad72cb41e67 ./test/regression_manifest_test.dart
5f049dd64b419a6afa46b548cdaba8d1101dd66501cede4425f02ed956b9a669 ./test/resources_models_test.dart
+701017ce3056f071f324d8fc94ccf2b6a147a3f0abd540eda634fac450fe53e3 ./test/session_guard_test.dart
+113ee0888fb78edf96476ee9d2c15fba2eecedfa6ff8529a9b86d0feb44a1563 ./test/session_lifecycle_test.dart
+9b0eb2ce870652644e7b0e73781a1c15ccbdb60b9cb7e25bc08e9004332f587d ./test/session_storage_test.dart
8619ce113bb8669612f9a2a16b1b334ac68435c5972e84828a789511467fcb77 ./test/shell_scripts_test.dart
+fd3d42374ae441045c4947152dc312020c331fbe07f197030e834e1aa7d06eb5 ./test/tenant_credentials_test.dart
efe4f1158e7d4b9ca8e57f3538ce296279817292a4356c1399cf5f2cbae4c52d ./test/transcode_upload_test.dart
b94c0fef25560e387c4de5de0e4032fce73aa22b23a4bf38594ea6ff241d914c ./test/transport_test.dart
c4aa3c091992668ee531412a7fc783106769df7d75147eb06271492027b0c100 ./test/upload_test.dart
-a5b7f52cd2560df794b75574180134a2ccf1c1b814c7b5eb495a29150c892f89 ./test/workflow_layout_test.dart
+0bf2e2c2f1476140b3bc18f978e31a5563c1d713f2b7897cab769323bcfa9155 ./test/user_provenance_test.dart
+a379f7dc013b39e8de00fd487d979c998069c13a461a2e621ac25d18facbc5d6 ./test/user_session_acceptance_test.dart
+3e211aca3928fed8f0dce62a97bd08fc873c2313493d986304dfcead25c0690b ./test/user_session_test.dart
+312c69e2854675a23f1849cb1d9e3f25afbcc5874795666f2bcc52bf9cb852cf ./test/workflow_layout_test.dart
406de1350b79662fcaf007cb0cacd7a6b71b83815dc7cd3c7b561fcfba5600a3 ./tool/check_route_sync.dart
d5f5f9246656a5c275c5ab5863dbf3945d8ef6b1c9042c9d1912cfafce93646f ./tool/flutter_checksums.txt
24ea8e3013e0ed3531ff2aa3c86ad5332bf315d3d26f6a0814d2d6c84c5dade2 ./tool/live_cctv_test.dart
diff --git a/doc/manage_api_key.md b/doc/manage_api_key.md
index 599a729..cfefe46 100644
--- a/doc/manage_api_key.md
+++ b/doc/manage_api_key.md
@@ -1,26 +1,128 @@
-# Manage API keys
+# Manage tenant API keys and app-user sessions
-Retrieve credentials in the parent application's authenticated service, load
-them into memory, then inject `MutableApiKeyProvider`. The SDK never stores a key.
+Retrieve credentials through the host's authenticated, trusted service and
+keep them in memory. VModal credentials identify the tenant principal; Firebase,
+Clerk, or another host identity system supplies the stable app-user ID. A and B
+may share one tenant key and `auth.me()` response. That response never selects
+their local owner namespace or proves their content permissions.
+
+## Session-bound configuration
+
+```dart
+final config = SdkConfig(); // gateway mode
+final namespace = SessionContext.serviceNamespaceFor(config);
+final credentials = TenantCredentialSource(
+ serviceNamespace: namespace,
+ tenantId: tenantId,
+ expectedPrincipal: tenantPrincipal,
+ initialKey: runtimeTenantKey,
+ renew: () async => TenantCredential(
+ serviceNamespace: namespace,
+ tenantId: tenantId,
+ principal: tenantPrincipal,
+ apiKey: await trustedIssuer.currentTenantKey(),
+ ),
+);
+final manager = UserSessionManager(
+ config: config,
+ credentialSource: credentials,
+);
+```
+
+The host's issuer/resolver must authenticate and validate the credential's
+service/tenant/principal binding. These fields are compared locally; self-reported
+labels on an arbitrary key are not proof. `session.verifyPrincipal(...)` can
+add an `auth.me()` tenant-principal check. It does not identify the app user or
+validate that user's mapping. Prefer authoritative integer `issuerVersion`
+values when the issuer supports them; when absent, the trusted resolver must
+return its currently valid key. `auth.me()` cannot order opaque keys by age.
+
+## Coordinate tenant rotation
+
+`credentials.renewCredential()` shares one normal renewal Future across active
+matching providers. `install(TenantCredential(...))` installs a trusted external
+replacement. `renewCredential(supersede: true)` deliberately fences earlier
+renewal tickets. Accepted revision and request ticket checks reject late results;
+authoritative issuer versions reject rollback. Commit is atomic within the
+isolate, updates only live matching providers, and new sessions attach/read the
+latest revision without an asynchronous gap. Closing A unsubscribes its provider
+without canceling shared renewal needed by B.
+
+```dart
+credentials.install(TenantCredential(
+ serviceNamespace: namespace,
+ tenantId: tenantId,
+ principal: tenantPrincipal,
+ apiKey: replacementTenantKey,
+));
+```
+
+A credential-only replacement preserves `sessionId`, stable owner/scope keys,
+app user, mapping, policy, and multipart checkpoint namespace. Tenant, endpoint,
+or principal changes are rejected in place: build a correctly bound source and
+fresh sessions. Grant/mapping changes also require invalidation and fresh policy
+resolution, even when the key or app-user ID stays equal.
+
+By default renewal failure blocks tenant calls, retains no fallback authority,
+and returns a classified `TenantAuthException`. It does not log out the host
+app user or change the active owner. `retainOnRenewalFailure: true` is available
+only when the host's authoritative validity policy permits using the prior key.
+`revoke()` is an authoritative current-credential revocation and blocks gateway
+calls; a stale request's `401` cannot revoke a newer accepted revision. Recover
+the tenant connection through the trusted source rather than falling back to a
+broader credential. `credentials.close()` retires the shared coordinator;
+closing one user session leaves the coordinator available to another.
+
+## Request snapshots and recovery
+
+The HTTP layer captures a binding/revision and header snapshot at request
+construction. Ordinary retries retain that snapshot. Rotation does not rewrite
+an existing request. New requests read the latest committed credential. Existing
+calls can finish with the prior key while the service still accepts it; every
+attempt and delivery remains guarded by its original app-user lease.
+
+An eligible active GET/HEAD read can recover from `401` at most once per logical
+request by consulting the coordinator and reconstructing fresh headers. It
+shares a bounded attempt budget with ordinary retries. A second denial returns
+a tenant-auth error while preserving app-user identity. `403` is never a general
+refresh trigger. Uploads, index submissions, deletions, and other mutations are
+never automatically replayed through auth recovery; ambiguous completion remains
+unknown and requires deliberate reconciliation. Multipart continuation uses only
+its existing explicit status/part/resume protocol and validated owner checkpoints.
+
+Signed URLs have independent validity and expiry. Rotating or revoking the
+tenant key does not promise to revoke an already issued storage/media capability.
+Never attach a replacement bearer to a signed storage request. The session guard
+still blocks later local signed-upload dispatch and media delivery after logout.
+
+## Account changes and the host boundary
+
+Call `manager.logout()` or `manager.openResolvedSession(...)` at the start of
+an identity transition. Invalidation happens before asynchronous resolution or
+cleanup. Clear old displayed images, playback, navigation/restoration, and
+histories; check the current view generation before applying asynchronous host
+state updates. Persisted owner data may remain for a later verified activation,
+but old runtime handles never become valid again. Local cache reuse requires
+current policy validation.
+
+The compatible tenant-scoped API still accepts `MutableApiKeyProvider`:
```dart
-final provider = MutableApiKeyProvider(await authService.currentApiKey());
+final provider = MutableApiKeyProvider(runtimeTenantKey);
final project = VModal.configure(
projectId: 'food_app',
apiKeyProvider: provider,
);
+provider.rotate(replacementTenantKey); // later requests only
+provider.close(); // permanently disables reads and rotation
+await project.close();
```
-`rotate` validates the complete new key before replacing the old one. A request
-reads one snapshot; rotation affects the next request. `clear` and `close` fail
-closed. Logout/account switch order is: cancel active work, clear upload state,
-clear the provider, close the project, authenticate the next account, then
-create a new provider, project, and immutable scopes. Key rotation is not an
-identity, project, collection, or stream switch.
-
-Keep `projectId` separate from the authenticated end-user ID. If content is
-isolated per user, express the app-owned normalized identifier through a fresh
-`collectionName` scope after account switch.
+`VmodalClient`/`VModalProject` bypass user-session isolation; the host must own
+their complete cancellation, cache/checkpoint partitioning, and account-switch
+contract. Never use `projectId` or tenant identity as proof of app-user identity.
+Never commit keys, put them in assets, log them, persist them in jobs/archives,
+or treat compile-time `--dart-define` values as production credential storage.
-Do not commit keys, put them in assets, log them, add them to presigned requests,
-or use compile-time `--dart-define` values as production mobile credential storage.
+See [the SDK contract](sdk_contract.md) for result provenance, restricted media,
+local storage fencing, and the shared-key modified-client limitation.
diff --git a/doc/sdk_contract.md b/doc/sdk_contract.md
index a82aaf1..edc5c65 100644
--- a/doc/sdk_contract.md
+++ b/doc/sdk_contract.md
@@ -7,7 +7,8 @@ behavior. `test/fixtures/routes_contract.json` is the reviewed normalized mirror
| Resource | Public Flutter operations | Contract status |
|---|---|---|
-| Scoped facade | `VModal.configure`, `VModal.fromClient`, `VModalProject.scope`, `listCollections`, `close` | Preferred additive API |
+| App-user sessions | `UserSessionManager`, `UserSession`, `UserScope`, `ContentMapping` | Opt-in same-tenant app-user isolation; gateway only |
+| Scoped facade | `VModal.configure`, `VModal.fromClient`, `VModalProject.scope`, `listCollections`, `close` | Compatible tenant-scoped API; bypasses session guarantees |
| Scoped operations | `upload`, `uploadMetadata`, `search`, `addAssets`, `updateAsset`, index lifecycle, collection deletion | Immutable organization; delegates to resources |
| Client/auth | `health`, `authCheck`, `auth.me` | Active; gateway bearer only |
| Searches | `searchVideo(SearchRequest)`, `searchBatch(List<SearchRequest>)` | Active; exact single-search contract and bounded client-side batch scheduling |
@@ -48,6 +49,169 @@ or API-key-provider contract. `VmodalClient` remains public and compatible.
`VModal.fromClient` transfers lifecycle ownership, so the project is the object
that must be closed.
+## App-user session contract
+
+This opt-in interface is implemented in the 1.3.0 source release. Existing
+pub.dev `1.2.3` and `v1.2.3` installs retain their earlier API. Source publication
+through GitHub Actions does not create a pub.dev release or version tag.
+
+VModal credentials authenticate a tenant principal. A and B can have identical
+tenant IDs, API keys, and `auth.me()` responses while remaining different local
+app users. The authenticated host resolves each stable `appUserId` and allowed
+mapping; `auth.me()` does not supply them. Do not use app-user identity as
+`SdkConfig.userId`, a direct-mode header, an API-key-derived cache name, or a
+collection typed by the user. No new environment variable represents the user.
+
+`UserSessionManager(config: ..., credentialSource: ...)` owns one active
+identity flow. `openUserSession(tenantId: ..., appUserId: ...,
+allowedContentMapping: ..., policyRevision: ...)` captures immutable policy.
+Use `openResolvedSession(() async => UserSessionPolicy(...))` when identity
+and mapping require asynchronous resolution: it invalidates the outgoing
+session before invoking the resolver. `current` is null during resolution or
+after failure. Only the latest activation ticket can publish a session.
+
+Each activation has a fresh `sessionId`, private provider/client, and distinct
+gateway and signed-upload transports. A returned `UserScope` stays attached to
+that instance. Opening B, logout, or closing A invalidates A synchronously,
+closes its provider, cancels registered work, and detaches internal state before
+host invalidation callbacks. Cleanup targets A even if a callback activates B.
+Repeated `close()` calls share one cleanup Future. Cleanup errors cannot restore
+A's lease; both transport cleanup paths are attempted.
+
+Every supported operation captures inputs and ownership before asynchronous
+work. Preparation, retries, gateway sends, signed PUT phases, response chunks,
+Future settlement, and upload progress delivery check the same originating
+lease. After invalidation, calls fail with cancellation and late payloads are
+dropped; the public operation settles even if a custom transport ignores
+cancellation. Caller-owned cancellation tokens are never canceled by the SDK.
+An upload/index/delete already accepted by the server can continue, but remains
+owned by A. Data delivered while A was active cannot be recalled.
+
+These guarantees require all user-data operations to pass through
+`UserSession`/`UserScope`. `VmodalClient`, `VModalProject`, raw HTTP, admin/R2
+resources, arbitrary URLs, sinks, and direct-mode identity overrides bypass
+them. The restricted interface exposes none of those capabilities. A modified
+client can use a shared tenant bearer for arbitrary tenant-authorized requests.
+Preventing intentional cross-user access requires server-side app-user
+authorization independent of tenant authentication and local selector syntax.
+
+### Exact mapping and supported actions
+
+`ContentMapping.logical` reuses the validated `projectId__collectionName`
+encoding. `ContentMapping.opaque` uses the exact backend `collectionId` without
+prefixing it. Both capture `streamName`, `mode`, an immutable `actions` set,
+and `collectionWide` (false by default). `session.scope(mapping)` matches the
+representation and all selectors, then uses the session's frozen permitted
+actions rather than a caller's replacement grants. Duplicate mappings are
+rejected. Local actions are policy guardrails, not server-issued claims.
+
+| API | Required action / ownership |
+| --- | --- |
+| `session.listCollections()` | `discover`; returns mapped selectors, no raw tenant list or count |
+| `scope.collectionInfo()`, `latestVersion()` | `discover`; exact stream row or `collectionWide` required for aggregate versions |
+| `scope.search(...)` | `search`; captured exact collection/stream/mode |
+| `scope.upload(...)` | `upload`; session-owned upload/checkpoint boundary |
+| `scope.addAssets(...)`, `updateAsset(...)`, `uploadMetadata(...)` | `metadata`; every resource must have this live scope's provenance |
+| `scope.createIndex()`, `listIndexJobs()`, `indexStatus(...)`, `rebindJob(...)` | `indexation`; live or freshly revalidated scoped job provenance |
+| `scope.imageBytes(...)` | `media`; live scoped asset, signed URL retained privately |
+| `scope.deleteIndex(...)`, `deleteCollection(...)` | `delete` plus `collectionWide: true`; backend deletion affects the collection |
+
+Stream-only mappings cannot obtain collection-wide index versions from
+aggregate discovery. `collectionInfo`/`latestVersion` return null without an
+exact stream row. Explicit wider host policy is required to use aggregate
+metadata; write permission alone does not imply collection-wide ownership.
+
+### Restricted results and provenance
+
+`SessionSearchResponse` retains typed `videoHits`, allowlisted `data`/`raw`
+fields, and an immutable `assets` list of live `SessionAsset` handles. Returned
+row counts are recomputed from retained rows. Unknown fields, nested records,
+signed URLs, storage credentials, and broader tenant counts are omitted.
+Scoped requests supply ownership for results without echoed selectors;
+conflicting echoed selectors are rejected/filtered. Discovery job rows must
+include exact `group_name`, `stream_name`, and `mode` before minting a handle.
+Restricted errors omit raw response bodies, capabilities, and underlying causes.
+
+`addAssets` accepts handles rather than bare IDs; `updateAsset` and `imageBytes`
+require a validated basename. Every batch member is checked before dispatch.
+`SessionUploadResponse.asset` is nullable when completion provides no usable
+identity. Neither filenames nor frame IDs synthesize a canonical asset ID.
+Handles from A, another scope, or a closed session are rejected even when IDs
+or filenames are equal.
+
+```dart
+final job = await scope.createIndex(); // mapping includes indexation
+final durable = job.toDurableReference();
+final status = await scope.indexStatus(job);
+// Persist only jobId/ownerKey/scopeKey/policyRevision in the owner's manifest.
+// After a new activation for the same authenticated owner and exact policy:
+final rebound = await newScope.rebindJob(durable);
+final resumedStatus = await newScope.indexStatus(rebound);
+```
+
+`DurableJobReference` is ownership metadata, not an ownership proof. Rebinding
+requires exact owner, scope, and policy revision, followed by fresh exact scoped
+job discovery (bounded to 1000 rows); a tenant-wide status response alone is
+insufficient. Missing/unknown jobs fail closed. No durable asset or raw upload
+ID rebinding API is supported. Policy changes require fresh discovery rather
+than accepting references under old grants.
+
+`uploadMetadata` accepts bounded UTF-8 JSONL (at most 8 MiB), snapshots its bytes,
+and validates every nonempty row before sending. Supported fields are
+`filename`, `filename_sanitized`, `asset_id`, `description`, `metadata_text`,
+`tags`, and `tag`. Values must be strings or lists of strings. Each row needs a
+live scoped `asset_id` or filename; if both are supplied, both must match the
+same handle. Both filename aliases must agree. Unknown fields, malformed JSON,
+unproven assets, and arbitrary nested metadata fail locally.
+
+### Stable storage ownership
+
+`SessionContext.serviceNamespaceFor(config)` derives the normalized connection
+namespace. `ownerKey` canonically encodes service namespace, tenant, and stable
+app-user ID. `scopeKey(mapping)` adds representation, exact backend collection,
+stream, and mode. Neither key contains API-key bytes, credential revision, or
+runtime session identity. The default policy revision fingerprints immutable
+selectors/actions/collection-wide grants; the host can supply its trusted
+revision explicitly. Any policy change requires a new session.
+
+Uploads always inject an owner/scope-partitioned checkpoint adapter. Lookup
+keys wrap the existing upload contract key; envelopes validate owner, scope,
+policy, and exact contract before reuse. Credential-only rotation preserves
+checkpoints. A new session can resume only after the older writer is fenced and
+accepted writes have completed. Logout does not clear another owner's store.
+Inject a custom `UploadSessionStore` only through `UserSessionManager`; per-task
+stores and custom transcoders are rejected. Only `PassthroughVideoTranscoder`
+is supported through this restricted interface.
+
+The shared owner commit coordinator serializes load/save/remove and retires
+older writer leases, including A→B→A. Accepted noncancelable store writes finish
+in their captured namespace before a later writer can read it. This barrier is
+within one isolate. Use one storage-owner isolate or a real transactional
+cross-isolate/process lock for shared storage; independent in-memory queues do
+not provide that guarantee. Custom stores must preserve atomic storage behavior
+and must not perform unbound user-visible side effects.
+
+Host archives can use `scope.storageLease`, a supported `SessionStorageLease`
+with `check()`, `run(...)`, `retire()`, and its originating `sessionId`. It
+coordinates the captured owner/collection namespace and expires with the
+session. Capture immutable file paths/payloads before queueing, execute writes
+through `run`, and call `check` immediately before publishing a staged file.
+`retire` ends a host writer even if the SDK session remains active; do not reopen
+a retired writer under that same session. This adapter does not grant arbitrary
+filesystem paths ownership automatically.
+
+Host caches must additionally include current policy and all result-affecting
+parameters (version, pagination, query/date filters, media variant). In-flight
+deduplication must include `sessionId`. Validate owner metadata and paths on
+restore; quarantine legacy data with unknown ownership. Clear or partition
+Flutter image caches, player controllers, navigation/restoration, search
+history, and copied/downloaded files at identity transitions. The SDK exposes
+session invalidation; it cannot manage these host-owned surfaces.
+
+Tenant renewal and bounded read recovery are documented in
+[Manage API keys](manage_api_key.md). Implemented block and verification notes
+are in [User-session implementation](user_session_implementation.md).
+
## Typed video-search results
`SearchResponse.videoHits` is an additive typed view of map-shaped entries in
diff --git a/doc/user_session_implementation.md b/doc/user_session_implementation.md
new file mode 100644
index 0000000..bbe3de4
--- /dev/null
+++ b/doc/user_session_implementation.md
@@ -0,0 +1,71 @@
+# App-user session implementation notes
+
+Date: 2026-10-02
+
+The nine requested specification blocks are implemented as an opt-in gateway
+interface. Existing tenant-scoped wire APIs remain compatible. The specification
+is a design input; this authored note and [SDK contract](sdk_contract.md) describe
+the actual supported interface.
+
+| Block | Implemented boundary | Verification focus |
+| --- | --- | --- |
+| 1. Credential model and guarantee | Shared tenant auth separated from stable host app-user identity; documented modified-client limitation | Same-key A/B tests; same tenant principal |
+| 2. Tenant configuration / context | `TenantCredentialSource`, immutable `SessionContext`, policy fingerprints, revisions and renewal tickets | Coalesced/out-of-order renewal, external installs, rotation without identity change |
+| 3. Session API | `UserSessionManager`, `UserSession`, `UserScope`, logical/opaque `ContentMapping` | Frozen mappings, exact selectors, private clients/providers/transports |
+| 4. Central guard | Session/operation lease checks through preparation, retries, signed phases, response and listener delivery | Prompt cancellation with uncooperative I/O; caller token ownership; paused streams |
+| 5. Resource identifiers / discovery | Live asset/job handles, restricted fields/counts/errors, durable job rebinding, bounded JSONL provenance | Cross-owner batches, unknown IDs, nested data, stream-only aggregate discovery |
+| 6. Account switch / logout | Synchronous invalidation, latest activation ticket, instance-owned idempotent cleanup | A→B→A, late activation, reentrant callbacks, cleanup failure |
+| 7. Cache / storage | Owner/policy multipart envelopes, serialized writer fences, public host storage lease | Identical upload contracts, same-owner reopen, stale save/remove, policy narrowing |
+| 8. Reuse / host integration | Existing resources/transports reused; Framebase session gateway and exact owner archives | Host identity transitions, safe image bytes, no tenant-key-derived archive |
+| 9. Acceptance tests | Focused same-key/session/rotation/storage tests plus existing SDK and example suites | SDK isolation asserted separately from server authorization |
+
+## Docs impact checklist
+
+- Subject changed: tenant credential versus app-user identity; runtime lifecycle,
+ rotation, provenance/discovery, owner storage, host UI handoff, source release.
+- Updated: root README, `sdk_contract.md`, `manage_api_key.md`, Framebase userlogin
+ README, and this implementation note.
+- Neighboring references checked: public API exports, config/provider/session/
+ guard/resource implementations, Framebase credential/controller/gateway/archive
+ contracts, existing package-install and source-publication guidance.
+- Removed stale claims in touched docs: `auth.me()` as app-user owner, guaranteed
+ per-user bearer authorization under a shared tenant key, scope-only archives,
+ write grants implying collection-wide deletion, unrestricted session result
+ URLs, and tenant `401` meaning Firebase logout.
+- Existing low-level examples remain labeled tenant-scoped; they bypass the
+ session guarantees. Published pub.dev `1.2.3`/tag install examples remain
+ distinct from the new 1.3.0 source-only interface.
+
+## Validation and publication
+
+Local gates from the SDK root are `bash build.sh pub_get`, `bash build.sh format`,
+`bash build.sh analyze`, `bash test.sh all`, and the pinned Dart command
+`run tool/check_route_sync.dart`. They cover every SDK/example test suite,
+formatting, analysis, package export, secret checks, simulation, and upstream
+route synchronization. GitHub Actions separately gates Android/iOS builds and
+the production live lifecycle before public publication. Focused session/guard/provider/
+storage and Framebase suites cover deterministic account-switch and rotation
+races. These are offline SDK-flow checks, not evidence of server-side app-user
+authorization.
+
+Final local results: all 207 SDK tests and all five example suites pass, including
+53 Framebase tests. Formatting and analysis pass across the SDK and examples;
+all 42 upstream route operations match. Package validation reports zero warnings,
+secret detection reports zero leaks, simulation passes, and generated reference
+validation verifies 1,011 sanitized source sections. The public revision is
+recorded by the release change and GitHub Actions run. Public source publication uses
+`.github/workflows/sdk_flutter_test_release.yml`; only its successful export
+establishes the released public commit. This task does not publish a pub.dev
+package or create a pub.dev version tag.
+
+Storage coordination is guaranteed within one isolate. Shared files across
+isolates/processes require one storage owner or a transactional lock. Signed
+capabilities have independent revocation/expiry. Host UI caches, navigation,
+players, copied files, and already delivered data require host cleanup; server
+work already accepted remains owned by its originating user.
+
+Framebase clears decoded image caches and replaces its navigation tree using
+the SDK runtime session identity. Recording sheets retire their player on
+invalidation; file selection and confirmation dialogs capture that same
+identity before awaiting so a later activation cannot consume an earlier view's
+decision.
diff --git a/example/01_full_app/pubspec.lock b/example/01_full_app/pubspec.lock
index c0cf225..348e5de 100644
--- a/example/01_full_app/pubspec.lock
+++ b/example/01_full_app/pubspec.lock
@@ -331,7 +331,7 @@ packages:
path: "../.."
relative: true
source: path
- version: "1.2.2"
+ version: "1.3.0"
web:
dependency: transitive
description:
diff --git a/example/02_users/pubspec.lock b/example/02_users/pubspec.lock
index f3fc90c..29c6c65 100644
--- a/example/02_users/pubspec.lock
+++ b/example/02_users/pubspec.lock
@@ -238,7 +238,7 @@ packages:
path: "../.."
relative: true
source: path
- version: "1.2.2"
+ version: "1.3.0"
web:
dependency: transitive
description:
diff --git a/example/03_cctv/pubspec.lock b/example/03_cctv/pubspec.lock
index 95957cc..e3ee252 100644
--- a/example/03_cctv/pubspec.lock
+++ b/example/03_cctv/pubspec.lock
@@ -238,7 +238,7 @@ packages:
path: "../.."
relative: true
source: path
- version: "1.2.2"
+ version: "1.3.0"
web:
dependency: transitive
description:
diff --git a/example/04_example/pubspec.lock b/example/04_example/pubspec.lock
index c5c3e56..6745fe8 100644
--- a/example/04_example/pubspec.lock
+++ b/example/04_example/pubspec.lock
@@ -370,7 +370,7 @@ packages:
path: "../.."
relative: true
source: path
- version: "1.2.2"
+ version: "1.3.0"
web:
dependency: transitive
description:
diff --git a/example/05_framebase_userlogin/README.md b/example/05_framebase_userlogin/README.md
index e038dda..d16aa13 100644
--- a/example/05_framebase_userlogin/README.md
+++ b/example/05_framebase_userlogin/README.md
@@ -1,10 +1,10 @@
# Framebase user library
-This Flutter example opens the one opaque street-video library scope selected by
-a trusted credential issuer for the signed-in user. It shows where app sign-in,
-a VMODAL credential, SDK requests, local video files, and search results meet.
-The video screens come from the original Framebase example; this version adds a
-signed-out entry screen and scope-isolated state.
+This Flutter example connects host sign-in, an exact opaque library mapping,
+and the SDK's opt-in `UserSessionManager`. Two app users can share the same
+tenant API key and VModal principal while keeping separate sessions, archives,
+search results, and pending work. The host's authenticated adapter supplies the
+stable Firebase UID; `auth.me()` verifies only the tenant principal.
## Screenshots
@@ -12,8 +12,7 @@ signed-out entry screen and scope-isolated state.
| --- | --- | --- |
| ![Three street videos in the Framebase library](readme_assets/library.png) | ![Matching frames grouped by source video](readme_assets/search.png) | ![Local video opened at the matching timestamp](readme_assets/playback.png) |
-These are the shared Framebase video screens after access is granted. The
-unconfigured offline app opens on **Sign in to your street library** instead.
+The unconfigured offline app opens on **Sign in to your street library**.
## Run the offline example
@@ -27,63 +26,20 @@ flutter_bin="$(bash ../../install.sh flutter_bin)"
"$flutter_bin" run --device-id DEVICE_ID
```
-The default `MockFirebaseAuth` has no accounts, and the credential source has
-no usable key. You can inspect the sign-in screen without a backend. To exercise
-the signed-in flow, inject a fake account and queued `VmodalCredential` responses
-as the tests do. Fixture keys are placeholders, not live credentials. A real
-Firebase adapter and trusted credential issuer are still required for production.
-
-## 1. Sign-in and library setup
-
-```mermaid
-flowchart TD
- A[App opens] --> B{Auth adapter has a user?}
- B -- No --> C[Show sign-in screen with no VMODAL request]
- B -- Yes --> D[Ask app adapter for Firebase ID token]
- C -->|Configured fake account signs in| D
- D --> E[Trusted issuer verifies Firebase token server-side]
- E --> F[Issuer returns scope-bound VMODAL credential]
- F --> G{Client contract checks pass?}
- G -- No --> H[Show access error or retry]
- G -- Yes --> I[Gateway enforces owner, scope, grants, and expiry]
- I --> J[Open the scope-isolated client session]
-```
+`MockFirebaseAuth` defaults to no accounts, and the mock credential source has
+no usable key. Inject fake accounts and queued `VmodalCredential` responses as
+the tests do to exercise the library. Fixture keys are placeholders. Production
+requires a real Firebase adapter and trusted issuer; this example contains no
+Firebase token verifier or app-user-scoped server authorization service.
-`UserSessionController` validates the credential's Firebase UID, expiry,
-`library:read` permission, stable VMODAL owner, and stable opaque scope.
-`SearchGateway.connect()` calls `auth.me()` to confirm that the VMODAL key
-resolves to the expected VMODAL user. These fail-closed checks control client UI
-and session state; they are not the authorization boundary. Firebase Auth does
-not issue the VMODAL key: a trusted app-owned credential issuer must supply it.
-
-## 2. API access and account changes
-
-```mermaid
-flowchart TD
- A[Read or write action] --> B{Permission allows action?}
- B -- No --> C[Keep action unavailable]
- B -- Yes --> D[Ensure credential is fresh]
- D -->|Expires within 1 minute| E[Retry typed temporary failures with bounded backoff]
- D -->|Still valid| F[SDK request]
- E -->|Refresh succeeds| F
- E -->|Temporary failures exhausted| L[Keep resources but gate operations until manual retry]
- F --> G[Send issuer scope_id unchanged as collection selector]
- G --> H[Gateway authorizes bearer, scope, operation, and resource owner]
- H -->|401 or 403| I[Cancel work and clear key and archive state]
- J[Sign out or switch account] --> I
- I --> K[Close session and hide library]
-```
+## 1. Authenticate the app user
-The issuer returns `scope_id`, an opaque exact backend `group_name`. The app
-does not prepend a project, append a user ID, split it, or infer identity or
-permissions from it. It accepts only a nonempty `[A-Za-z0-9_]+` value of at
-most 80 characters for safe request and directory reuse; this is syntax
-validation, not authorization. Upload, indexing, search, discovery matching,
-jobs, and image lookup reuse that exact immutable value. The stream remains
-`street_study`. The archive controller uses the same value only as
-`accounts/<scope_id>/` in application support.
+The auth adapter resolves the signed-in user and supplies a Firebase ID token.
+The trusted issuer must verify that token server-side, derive its UID, and
+return the user's exact allowed mapping. User-entered collections, email
+addresses, and unverified decoded tokens never establish ownership.
-The version-1 issuer envelope is:
+The version-1 example envelope is:
```json
{
@@ -91,183 +47,174 @@ The version-1 issuer envelope is:
"session_id": "<opaque issuer session identifier>",
"issued_at": "2030-01-01T00:00:00Z",
"expires_at": "2030-01-01T00:05:00Z",
- "api_token": "<short-lived VMODAL bearer>",
+ "api_token": "<tenant VMODAL bearer>",
"firebase_uid": "<verified Firebase subject>",
- "vmodal_user_id": "<auth.me user_id>",
- "scope_id": "<opaque backend collection identifier>",
+ "vmodal_user_id": "<tenant auth.me user_id>",
+ "tenant_id": "<stable tenant identifier>",
+ "scope_id": "<exact opaque backend collection identifier>",
"allowed": true,
- "permissions": ["library:read", "library:write"]
+ "permissions": ["library:read", "library:write"],
+ "collection_wide": true
}
```
-`version` identifies this example-owned envelope contract. `session_id` is an
-opaque issuer value: the app does not derive identity, scope, grants, or
-authorization from it. It may rotate during refresh because no stability
-contract is defined for it. `issued_at` and `expires_at` must be parseable UTC
-times with `issued_at` strictly earlier than `expires_at`.
-
-On refresh, only `vmodal_user_id` and `scope_id` must remain unchanged. A
-change tears down the session instead of rotating the in-memory key. `allowed`
-and `permissions` remain client-visible hints used for fail-closed UI gating.
-The gateway is authoritative.
-
-Credential refresh retries only typed temporary identity or issuer failures,
-with three total attempts and bounded backoff. If those attempts are exhausted,
-the current provider, gateway, credential scope, and archive remain in memory,
-but new read and write operations stay gated until manual retry succeeds.
-Firebase identity expiry, credential denial, final VMODAL `401` or `403`, and
-invalid credential contracts are terminal and clear the key and archive. SDK
-read retries remain governed by `SdkConfig.maxRetries`; writes are not replayed.
-
-When the app becomes `paused`, `hidden`, or `detached`, it cancels the active
-upload or local index wait and invalidates the active search so late progress
-or results cannot repopulate hidden UI. A brief `inactive` interruption does
-not cancel work. Returning to `resumed` never replays an upload, search,
-mutation, or index submission. A submitted server index job may continue; its
-`pendingJob` stays in the manifest and the user explicitly chooses **Resume**
-to poll it again.
-
-### Server requirements: the authorization boundary
-
-The credential issuer must verify the Firebase ID token server-side and derive
-`firebase_uid`; it must not trust a UID or requested scope supplied by the
-mobile app. It must issue a stable, syntax-compatible scope. The VMODAL gateway
-must then:
-
-- Bind the bearer to `(vmodal_user_id, scope_id, permissions, expires_at)` and
- return `403` for any other collection, including requests from a modified
- client.
-- Require `library:read` for read routes and `library:write` (or a narrower
- future grant) for upload, indexing, deletion, and other mutations.
-- Filter collection discovery so a bearer sees only its allowed collections,
- and make `auth.me()` resolve to the envelope's `vmodal_user_id`.
-- Ownership-check selector-less resources. A job ID, asset/image lookup, or
- signed-upload completion owned by another scope or principal must return
- `403` or a non-enumerating `404`.
-
-`MockVmodalCredentialSource` and the offline transports demonstrate client
-behavior only. They do not prove server enforcement. This repository still has
-no production Firebase adapter, Firebase token verifier, credential issuer, or
-collection-scoped token endpoint.
-
-## 3. Video upload, search, and playback
-
-```mermaid
-flowchart LR
- A[Bundled or imported MP4] --> B[Local file in user archive]
- B -->|Write access| C[Stream upload to user collection]
- C --> D[Create image index; poll job]
- D --> E[Discover ready index version]
- E -->|Read access| F[Search video frames]
- F --> G[Fetch matching frame images]
- G --> H[Group moments by source video]
- H --> I[Play local MP4 at match time]
+`tenant_id` is optional for older version-1 responses; its compatibility
+fallback is `vmodal_user_id`. Neither identifies the app user. `session_id` is
+an issuer value and can rotate; the SDK generates its own fresh runtime
+`sessionId` for each activation. `issued_at`/`expires_at` must be valid UTC
+times with issuance before expiry. `collection_wide` defaults to false; a
+write permission alone does not grant collection deletion or aggregate metadata.
+
+`UserSessionController` validates the authenticated UID, expiry, allowed flag,
+and read permission. It constructs `TenantCredentialSource` with the normalized
+service namespace and tenant/principal binding, then opens a SDK session with
+the Firebase UID as `appUserId`. `SearchGateway.connect()` uses
+`session.verifyPrincipal(...)` for the optional tenant-principal check.
+
+## 2. Discover collections and indexing work
+
+`scope_id` stays unchanged as backend `group_name`; the app never prefixes it
+with a project or appends a UID. The example validates a nonempty
+`[A-Za-z0-9_]+` selector of at most 80 characters, then uses
+`ContentMapping.opaque(collectionId: scopeId, streamName: 'street_study', ...)`.
+Syntax is a local contract check, not server authorization.
+
+Read policy maps to `discover`, `search`, and `media`; write policy additionally
+maps to `upload`, `metadata`, and `indexation`. `delete` requires explicit
+collection-wide access and write permission. All requests use the frozen exact
+collection, stream, and mode. Collection and job discovery return restricted
+results. Job handles are minted only from scoped submission or discovery rows
+with exact collection/stream/mode provenance.
+
+Collection-wide index versions can be used only with `collection_wide: true`
+or a discovery row naming the exact stream. A stream-only mapping whose service
+returns only aggregate collection metadata cannot obtain that version; setup
+fails closed instead of widening access. Hosts must supply a legitimately
+collection-wide policy or a supported stream-specific discovery contract.
+
+## 3. Upload, index, search, and playback
+
+Choose **Prepare videos for search** to upload clips not already marked uploaded,
+submit an image-index job, and poll its live `SessionJob`. Existing pending job
+records are rebound only after exact owner/scope/policy validation and fresh
+scoped discovery; a bare tenant-wide job status lookup is insufficient.
+
+Search uses `UserScope.search` and its allowlisted `SessionSearchResponse`.
+Matching frames use live `SessionAsset` handles and `scope.imageBytes(...)`;
+signed URLs and arbitrary media sinks are not exposed. Tapping a result plays
+the owner's local MP4 at the returned offset. The host clears images/player
+controllers and checks view generations during account changes.
+
+Canonical server `asset_id` reconnects a hit to an `ArchiveClip`. Filename
+matching is only a compatibility fallback when either side lacks canonical
+identity; different non-null IDs never match by filename alone. The SDK never
+invents an asset ID from a frame, timestamp, filename, or path.
+
+Skipping uploaded manifest rows avoids ordinary repeats, but is not once-only
+upload behavior. Ambiguous upload failures retain unknown completion. Robust
+retry or cross-device deduplication needs a scope-bound server idempotency
+contract synchronized with the Python reference SDK; filenames, hashes,
+`sourceId`, ETags, and checkpoint keys are not undocumented authorization or
+deduplication contracts.
+
+## 4. Rotation, account changes, and host state
+
+Same-tenant credential-only refresh installs through `TenantCredentialSource`
+and preserves the SDK session, app user, owner namespace, and policy. Shared
+renewal uses accepted revisions/tickets; late results cannot overwrite a newer
+key or reopen a closed A provider. Changed scope, actions, or collection-wide
+policy invalidate and rebuild the app-user session. Changed tenant/principal
+requires a fresh correctly bound source and session.
+
+Typed temporary issuer failures use bounded retries. Exhaustion gates operations
+until manual recovery. A tenant `401` becomes a connection-recovery state while
+retaining the authenticated Firebase UID and owner context; it does not become
+app-user logout. Denied policy, invalid identity, or expired Firebase identity
+deactivate user-data state. No write is replayed merely because a key rotated.
+
+Account switch/logout invalidate the outgoing SDK session before asynchronous
+cleanup. A→B→A creates three distinct runtime identities even with the same
+tenant key. Late A search/progress/errors cannot update B, and delayed A cleanup
+targets only A's resources. Closing the session is idempotent.
+
+When the app is paused/hidden/detached it cancels active upload/local index wait
+and invalidates the search view. A brief inactive interruption does not cancel
+work. Resume does not replay mutations or searches. An already accepted server
+job can continue; explicit **Resume** revalidates its owner-bound reference.
+
+## 5. Owner storage, sign-out, and deletion
+
+Local archives are partitioned under application support:
+
+```text
+accounts/<sha256(serviceNamespace)>/<sha256(tenantId)>/<sha256(appUserId)>/<sha256(scopeId)>/
```
-Choose **Prepare videos for search** to upload clips that are not yet uploaded
-and create the visual index. Search becomes available once the index has a ready
-version. Results use bulk image URL lookup and image download; tapping a result
-opens the local source video at its returned timestamp. Imported MP4s and the
-`archive.json` manifest stay in the active account's local directory. Credentials,
-search responses, signed URLs, and downloaded images are never persisted. The
-app keeps local and cloud retention separate.
-
-Modern upload and search responses reconnect a result to its local
-`ArchiveClip` through the server-issued `assetId`, which is persisted in the
-archive manifest. Filename matching remains only a compatibility fallback when
-either the saved clip or a legacy search response lacks canonical asset
-identity. Two different non-null asset IDs never match merely because their
-filenames are the same.
-
-### Upload identity and deduplication
-
-The example skips manifest rows already marked `uploaded`, persists the
-canonical server `asset_id`, and reconnects search results by that ID. This
-avoids ordinary repeats from the same manifest, but it is not a once-only
-upload guarantee. An ambiguous upload failure remains unknown completion: the
-app does not mark the clip uploaded or reuse an ID unless the server confirms
-it authoritatively.
-
-Robust retry and cross-device deduplication require a backend-supported,
-scope-bound idempotency contract—for example, a stable app asset ID or content
-digest accepted by upload finalization, with a response returning the existing
-or new canonical `asset_id`. The key must be scoped at least to the authorized
-principal and opaque `scope_id`; a digest alone must never authorize or expose
-another user's asset. Filenames, local paths, `UploadSource.sourceId`,
-`versionTag`, multipart checkpoint keys, ETags, and search result IDs are not
-undocumented server dedup keys. Such a contract must first be added to the
-Python reference SDK and then synchronized across SDKs before Flutter uses it.
-
-## 4. Storage, sign-out, and deletion
-
-**Sign out** is session teardown, not deletion. It cancels local work, clears
-the in-memory API key and client, and hides the active library. It does not
-unlink an MP4, remove `archive.json`, or send collection/index deletion calls.
-Signing back into the same issued scope restores that scope's local manifest.
-
-All credential material stays in `UserSessionController` memory only. This
-includes the live credential object, `api_token`, `version`, `session_id`,
-`issued_at`, `expires_at`, identity fields, and grants. `archive.json` is an
-allowlisted media/work manifest containing clips, canonical remote asset IDs,
-the pending index job, and bounded events. It never serializes the credential
-envelope, bearer, signed URLs, or search responses. Sign-out, account switch,
-and terminal auth failure clear the provider and credential from memory.
-
-This example intentionally adds no secure-storage, shared-preferences, or
-refresh-token cache. If background processing is approved later, its platform
-execution, least credential material, expiry and revocation, logout cleanup,
-account isolation, and migration need a separate design; the foreground bearer
-must not be silently persisted.
-
-Local data under `accounts/<scope_id>/` persists until the user explicitly
-removes a device copy, uninstalls the app or triggers platform cleanup, or the
-operating system evicts application storage where applicable. An imported
-local-only clip is removed from the manifest when its MP4 is removed. If the
-clip was uploaded, local removal retains a cloud-only manifest row and its
-server-issued `asset_id`, so search identity remains correct. The cloud copy
-stays searchable. Bundled source media remains packaged with the app.
-
-**Storage & deletion** separates the three retention domains:
+The manifest records exact service/tenant/app-user/scope/representation/stream/
+mode/policy metadata. Restore compares that ownership envelope and validates
+paths remain within the selected directory. Policy mismatch and legacy
+`accounts/<scope_id>/` data are not restored. Before identity resolution, no
+private archive is shown. Tenant key rotation does not change the directory.
+
+Archive commits use the scope's `SessionStorageLease`, shared by owner/scope
+within one isolate. Writer retirement and serialized commits fence old A writes
+before a newer A reads/writes the namespace. Captured immutable destinations
+and atomic replacement prevent partial manifests. Use one storage-owner isolate
+or a real transactional lock when multiple isolates/processes share storage.
+
+`archive.json` contains allowlisted media/work records, remote asset identity,
+pending job metadata, and bounded events. API keys, credential envelopes,
+signed URLs, search responses, and downloaded frame images are not persisted.
+This example adds no secure-storage/shared-preferences credential cache.
+
+**Sign out** clears in-memory session resources and hides the library while
+preserving owner-local files. Returning as the same verified owner with the
+same policy can restore them. Local storage remains until explicit removal,
+uninstall, or platform cleanup. Removing an imported device MP4 keeps a
+cloud-only row if the clip was uploaded; cloud content remains searchable.
| Domain | Explicit action | Result |
| --- | --- | --- |
-| Device MP4 and manifest | Remove device copy | Removes only the imported local MP4; an uploaded cloud copy remains |
-| Cloud raw video and metadata | Delete cloud library | Deletes the complete issued collection; device MP4s remain |
-| Derived search index | Delete cloud library | Deleted with the collection's `scope: all`; no extra index-delete call is made |
-
-Complete cloud deletion first previews, then requires a second confirmation.
-Both requests use the credential-issued opaque `scope_id` unchanged as
-`group_name`, `mode: vid_file`, and `scope: all` through
-`DELETE /api/external/v1/collection/delete`. Preview sends `dry_run: true` and
-`confirm: false`; commit sends `dry_run: false` and `confirm: true`. A successful
-commit clears saved upload/asset identity and the discovered index version, but
-keeps every local MP4 so it can be prepared again.
-
-The public API does not expose an asset-, filename-, or stream-item-scoped
-remote delete route. This example therefore never labels local removal as
-remote video deletion and never misuses collection or index deletion to remove
-one video. Cloud data persists until explicit complete-library deletion or a
-server-side policy outside this example.
-
-Deletion commits are never retried automatically. A `409` asks the user to
-wait for cloud processing. Network or server failures keep local remote-state
-flags conservative because completion is unknown. If the server confirms
-deletion but the local manifest cannot be saved, the UI reports cloud success
-and the local reconciliation problem separately; device videos remain.
-
-## Code map
+| Device MP4 and manifest | Remove device copy | Removes the local copy; uploaded cloud identity remains |
+| Cloud video, metadata, derived indexes | Delete cloud library | Deletes the entire collection; local MP4s remain |
+
+Cloud deletion requires `collection_wide` and write access, previews with
+`dry_run: true`, and commits only after a second confirmation using
+`dry_run: false, confirm: true`. It calls collection deletion with `scope: all`
+and does not issue a second index-delete call. No individual remote-video
+deletion API is available. Commits are never automatically replayed: `409`
+requires waiting, and unknown network outcomes preserve conservative state.
+Cloud success plus a failed local manifest update is reported separately.
+
+## SDK isolation and server authorization
+
+The supported SDK/app flow isolates A and B using stable host identity, exact
+mapping, runtime leases, provenance, and owner storage. Low-level
+`VmodalClient`/`VModalProject` or arbitrary HTTP bypass that guarantee. A
+modified client holding the shared tenant key can access anything that tenant
+bearer authorizes. Local checks and `auth.me()` cannot prevent it.
+
+Server protection requires independent app-user authorization: verify the host
+identity, authorize every collection/stream/action, filter discovery, and check
+selector-less jobs/assets/media/upload resources. Only deployments that actually
+bind an app-user identity to requests can expect A's raw request for B's resource
+to return `403` or a non-enumerating `404`. This same-key example and its offline
+tests demonstrate SDK isolation, not those server authorization guarantees.
+
+See [the SDK contract](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/sdk_contract.md)
+and [tenant key management](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/manage_api_key.md).
+
+## Code map and verification
| File | Responsibility |
| --- | --- |
-| [`lib/user/auth_adapter.dart`](lib/user/auth_adapter.dart), [`lib/user/mock_firebase_auth.dart`](lib/user/mock_firebase_auth.dart) | App-owned auth interface and offline fake |
-| [`lib/user/vmodal_credential.dart`](lib/user/vmodal_credential.dart) | Credential envelope, validation, and source interface |
-| [`lib/user/library_scope.dart`](lib/user/library_scope.dart) | Exact opaque-scope syntax validation |
-| [`lib/user/user_session_controller.dart`](lib/user/user_session_controller.dart) | Session states, refresh, account switch, and teardown |
-| [`lib/data/search_gateway.dart`](lib/data/search_gateway.dart) | Owner check and scoped VMODAL SDK calls |
-| [`lib/data/archive_controller.dart`](lib/data/archive_controller.dart) | Per-scope local files, upload, indexing, and search |
-| [`lib/main.dart`](lib/main.dart) | Signed-out and library screens |
-
-## Verify
+| [`lib/user/auth_adapter.dart`](lib/user/auth_adapter.dart) | Host app-user identity |
+| [`lib/user/vmodal_credential.dart`](lib/user/vmodal_credential.dart) | Trusted envelope contract and mock source |
+| [`lib/user/library_scope.dart`](lib/user/library_scope.dart) | Opaque selector syntax |
+| [`lib/user/user_session_controller.dart`](lib/user/user_session_controller.dart) | Session lifecycle, policy, tenant recovery |
+| [`lib/data/search_gateway.dart`](lib/data/search_gateway.dart) | Session-bound operations and safe media |
+| [`lib/data/archive_controller.dart`](lib/data/archive_controller.dart) | Owner manifests and storage commits |
+| [`lib/main.dart`](lib/main.dart) | Sign-in, library views, and host UI cleanup |
From `example/05_framebase_userlogin`:
@@ -279,25 +226,7 @@ flutter_bin="$(bash ../../install.sh flutter_bin)"
"$flutter_bin" test
```
-The offline tests cover credential parsing and validation, exact selector
-propagation, scope immutability, auth states, refresh, account switching,
-archive separation, local/cloud retention, previewed collection deletion,
-result mapping, and UI gating. They are not an authorization test.
-
-Production readiness requires this live negative authorization test with two
-real issuer-created users A and B:
-
-1. A's bearer can read and write A's issued `scope_id` according to its grants.
-2. A raw request modified to use B's `scope_id` with A's bearer returns `403`
- and performs no mutation.
-3. A's bearer receives `403` or a non-enumerating `404` for B's job ID and
- B-owned asset, image, and signed-upload resources.
-4. A read-only bearer receives `403` for upload, indexing, and mutation against
- its own scope.
-5. Discovery with A's bearer does not return B's scope.
-
-If the deployed issuer and gateway cannot pass all five checks, this example is
-not production-complete. Client-side Flutter validation is not a substitute.
-
-The bundled footage and its license are documented in
-[MEDIA_SOURCES.md](MEDIA_SOURCES.md).
+Run the SDK-wide offline gate with `bash test.sh all` from the SDK root.
+Same-key tests cover account switches, late work, tenant rotation, owner archive
+separation, and storage fencing. Live service authorization is a separate check.
+Bundled footage/license details are in [MEDIA_SOURCES.md](MEDIA_SOURCES.md).
diff --git a/example/05_framebase_userlogin/lib/data/archive_controller.dart b/example/05_framebase_userlogin/lib/data/archive_controller.dart
index e6a1928..029b62c 100644
--- a/example/05_framebase_userlogin/lib/data/archive_controller.dart
+++ b/example/05_framebase_userlogin/lib/data/archive_controller.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
@@ -81,13 +82,6 @@ class LibraryDeletionPreview {
final double executionTimeMs;
}
-class _ArchiveSnapshot {
- _ArchiveSnapshot(this.clips, this.pendingJob, this.events);
- final List<ArchiveClip> clips;
- final String pendingJob;
- final List<ArchiveEvent> events;
-}
-
List<ArchiveClip> streetClips() => [
ArchiveClip(
id: 'neighborhood_crossing',
@@ -137,6 +131,7 @@ class ArchiveController extends ChangeNotifier {
final List<ArchiveEvent> events = [];
bool initialized = false, connecting = false, busy = false, searching = false;
String phase = '', notice = '', activeQuery = '', pendingJob = '';
+ SessionJob? _pendingHandle;
double? progress;
SearchBatch? batch;
int? indexVersion;
@@ -149,8 +144,10 @@ class ArchiveController extends ChangeNotifier {
bool _disposed = false;
String _scopeId = '';
bool canRead = false, canWrite = false;
- Future<void> _saveQueue = Future<void>.value();
- final Map<String, _ArchiveSnapshot> _pendingReconciliation = {};
+ SessionStorageLease? _writer;
+ Map<String, Object?>? _owner;
+ String? get archiveDirectory => _directory?.path;
+ String? get sessionId => _gateway?.session.sessionId;
bool get connected => _gateway != null;
bool get ready => connected && indexVersion != null;
bool get hasPendingUploads => clips.any((c) => !c.uploaded);
@@ -171,9 +168,35 @@ class ArchiveController extends ChangeNotifier {
SearchGateway gateway, {
required bool canRead,
required bool canWrite,
+ required String serviceNamespace,
+ required String tenantId,
+ required String appUserId,
+ required String policyRevision,
}) async {
deactivate();
+ if ([
+ serviceNamespace,
+ tenantId,
+ appUserId,
+ policyRevision,
+ scopeId,
+ ].any((value) => value.trim().isEmpty)) {
+ throw const ValidationException('Resolved archive owner is required');
+ }
final generation = _generation;
+ final owner = <String, Object?>{
+ 'serviceNamespace': serviceNamespace,
+ 'tenantId': tenantId,
+ 'appUserId': appUserId,
+ 'scopeId': scopeId,
+ 'representation': 'opaque',
+ 'streamName': archiveStream,
+ 'mode': 'vid_file',
+ 'policyRevision': policyRevision,
+ };
+ _owner = owner;
+ final writer = gateway.scope.storageLease;
+ _writer = writer;
_scopeId = scopeId;
this.canRead = canRead;
this.canWrite = canWrite;
@@ -182,58 +205,59 @@ class ArchiveController extends ChangeNotifier {
try {
final root = supportDirectory ?? await getApplicationSupportDirectory();
if (generation != _generation) return;
- _directory = Directory('${root.path}/accounts/$scopeId');
+ await root.create(recursive: true);
+ final rootPath = await root.resolveSymbolicLinks();
+ writer.check();
+ String safe(String value) =>
+ sha256.convert(utf8.encode(value)).toString();
+ final directory = Directory(
+ '$rootPath/accounts/'
+ '${safe(serviceNamespace)}/${safe(tenantId)}/${safe(appUserId)}/${safe(scopeId)}',
+ );
+ _directory = directory;
if (persist) {
- final state = File('${_directory!.path}/archive.json');
- if (await state.exists()) {
- final data =
- jsonDecode(await state.readAsString()) as Map<String, dynamic>;
- final saved = (data['clips'] as List)
- .map(
- (r) =>
- ArchiveClip.fromJson(Map<String, dynamic>.from(r as Map)),
- )
- .toList();
- if (generation != _generation) return;
- for (final clip in saved) {
- if (clip.path != null && !File(clip.path!).existsSync()) {
- clip.path = null;
+ await writer.run(() async {
+ final state = File('${directory.path}/archive.json');
+ if (await state.exists()) {
+ final data =
+ jsonDecode(await state.readAsString()) as Map<String, dynamic>;
+ writer.check();
+ if (jsonEncode(data['owner']) != jsonEncode(owner)) return;
+ final saved = (data['clips'] as List)
+ .map(
+ (r) =>
+ ArchiveClip.fromJson(Map<String, dynamic>.from(r as Map)),
+ )
+ .toList();
+ if (generation != _generation) return;
+ for (final clip in saved) {
+ if (clip.path != null &&
+ !await _contained(directory, clip.path!)) {
+ clip.path = null;
+ }
+ }
+ writer.check();
+ clips = saved
+ .where((c) => c.bundled || c.path != null || c.uploaded)
+ .toList();
+ if (clips.isEmpty) clips = streetClips();
+ pendingJob = data['pendingJob'] as String? ?? '';
+ for (final raw in (data['events'] as List? ?? [])) {
+ final r = Map<String, dynamic>.from(raw as Map);
+ events.add(
+ ArchiveEvent(
+ r['title'] as String,
+ r['detail'] as String,
+ error: r['error'] == true,
+ time: DateTime.parse(r['time'] as String),
+ ),
+ );
}
}
- clips = saved
- .where((c) => c.bundled || c.path != null || c.uploaded)
- .toList();
- if (clips.isEmpty) clips = streetClips();
- pendingJob = data['pendingJob'] as String? ?? '';
- for (final raw in (data['events'] as List? ?? [])) {
- final r = Map<String, dynamic>.from(raw as Map);
- events.add(
- ArchiveEvent(
- r['title'] as String,
- r['detail'] as String,
- error: r['error'] == true,
- time: DateTime.parse(r['time'] as String),
- ),
- );
- }
- }
- }
- final reconciliation = _pendingReconciliation[scopeId];
- if (reconciliation != null && generation == _generation) {
- clips = reconciliation.clips.map((c) => c.copy()).toList();
- pendingJob = reconciliation.pendingJob;
- events
- ..clear()
- ..addAll(reconciliation.events);
- try {
- await _saveStrict(_directory!, clips, pendingJob, events);
- _pendingReconciliation.remove(scopeId);
- } on Object {
- notice =
- 'Cloud status is restored in memory but could not be saved locally.';
- }
+ });
}
} on Object {
+ if (generation != _generation) return;
notice =
'Local archive could not be restored. Built-in clips are available.';
}
@@ -244,6 +268,9 @@ class ArchiveController extends ChangeNotifier {
void deactivate() {
_generation++;
+ _writer?.retire();
+ _writer = null;
+ _owner = null;
stopWork();
invalidateSearch();
_gateway = null;
@@ -258,6 +285,7 @@ class ArchiveController extends ChangeNotifier {
busy = false;
searching = false;
phase = notice = activeQuery = pendingJob = '';
+ _pendingHandle = null;
progress = null;
batch = null;
indexVersion = null;
@@ -270,35 +298,41 @@ class ArchiveController extends ChangeNotifier {
}
// Snapshot and serialize writes so progress events cannot truncate each other.
// Never serialize the client, key, response rows or signed URLs.
- final snapshot = _manifestJson(clips, pendingJob, events);
+ final writer = _writer;
+ if (writer == null) return Future<void>.value();
+ final snapshot = _manifestJson(clips, pendingJob, events, _owner!);
final path = '${_directory!.path}/archive.json';
- final write = _saveQueue.catchError((_) {}).then((_) async {
- if (_disposed) return;
- await _writeManifest(path, snapshot);
- });
- _saveQueue = write.catchError((_) {
+ return writer.run(() => _writeManifest(path, snapshot, writer)).catchError((
+ _,
+ ) {
/* Optional history must not cancel network work. */
});
- return _saveQueue;
}
String _manifestJson(
List<ArchiveClip> savedClips,
String savedJob,
List<ArchiveEvent> savedEvents,
+ Map<String, Object?> owner,
) => jsonEncode({
+ 'owner': owner,
'clips': savedClips.map((c) => c.toJson()).toList(),
'pendingJob': savedJob,
'events': savedEvents.take(40).map((e) => e.toJson()).toList(),
});
- Future<void> _writeManifest(String path, String snapshot) async {
+ Future<void> _writeManifest(
+ String path,
+ String snapshot,
+ SessionStorageLease writer,
+ ) async {
final target = File(path);
await target.parent.create(recursive: true);
final temp = File('$path.${DateTime.now().microsecondsSinceEpoch}.tmp');
try {
await temp.writeAsString(snapshot, flush: true);
- await temp.rename(path);
+ writer.check();
+ temp.renameSync(path);
} on Object {
if (await temp.exists()) await temp.delete();
rethrow;
@@ -310,15 +344,23 @@ class ArchiveController extends ChangeNotifier {
List<ArchiveClip> savedClips,
String savedJob,
List<ArchiveEvent> savedEvents,
+ SessionStorageLease writer,
+ Map<String, Object?> owner,
) async {
if (!persist) return;
- final snapshot = _manifestJson(savedClips, savedJob, savedEvents);
+ final snapshot = _manifestJson(savedClips, savedJob, savedEvents, owner);
final path = '${directory.path}/archive.json';
- final write = _saveQueue
- .catchError((_) {})
- .then((_) => _writeManifest(path, snapshot));
- _saveQueue = write.catchError((_) {});
- await write;
+ await writer.run(() => _writeManifest(path, snapshot, writer));
+ }
+
+ Future<bool> _contained(Directory directory, String path) async {
+ try {
+ final root = await directory.resolveSymbolicLinks();
+ final file = await File(path).resolveSymbolicLinks();
+ return file.startsWith('$root${Platform.pathSeparator}');
+ } on FileSystemException {
+ return false;
+ }
}
void record(String title, String detail, {bool error = false}) {
@@ -329,26 +371,42 @@ class ArchiveController extends ChangeNotifier {
}
Future<File> localFile(ArchiveClip clip) async {
- if (clip.path != null && await File(clip.path!).exists()) {
- return File(clip.path!);
- }
- if (!clip.bundled) {
- throw const FileSystemException('Recording no longer available');
- }
- if (_directory == null || _scopeId.isEmpty) {
+ final directory = _directory;
+ final writer = _writer;
+ final path = clip.path;
+ if (directory == null || writer == null || !clips.contains(clip)) {
throw const FileSystemException('No active library');
}
- final file = File('${_directory!.path}/${clip.filename}');
- if (!await file.exists()) {
+ return writer.run(() async {
+ if (path != null && await _contained(directory, path)) {
+ writer.check();
+ return File(path);
+ }
+ if (!clip.bundled ||
+ clip.filename.contains('/') ||
+ clip.filename.contains('\\')) {
+ throw const FileSystemException('Recording no longer available');
+ }
+ final file = File('${directory.path}/${clip.filename}');
await file.parent.create(recursive: true);
- final data = await rootBundle.load(clip.asset);
- await file.writeAsBytes(
- data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),
- flush: true,
- );
- }
- clip.path = file.path;
- return file;
+ if (!await _contained(directory, file.path)) {
+ final data = await rootBundle.load(clip.asset);
+ final temp = File('${file.path}.${writer.sessionId}.tmp');
+ try {
+ await temp.writeAsBytes(
+ data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),
+ flush: true,
+ );
+ writer.check();
+ temp.renameSync(file.path);
+ } finally {
+ if (temp.existsSync()) temp.deleteSync();
+ }
+ }
+ writer.check();
+ clip.path = file.path;
+ return file;
+ });
}
Future<LocalRemovalResult> removeLocalCopy(ArchiveClip clip) async {
@@ -356,7 +414,11 @@ class ArchiveController extends ChangeNotifier {
final scope = _scopeId;
final generation = _generation;
final path = clip.path;
+ final writer = _writer;
+ final owner = _owner;
if (directory == null ||
+ writer == null ||
+ owner == null ||
scope.isEmpty ||
busy ||
pendingJob.isNotEmpty ||
@@ -367,20 +429,15 @@ class ArchiveController extends ChangeNotifier {
}
final target = File(path);
try {
- final rootPath = await directory.resolveSymbolicLinks();
- final targetPath = await target.resolveSymbolicLinks();
- final prefix = rootPath.endsWith(Platform.pathSeparator)
- ? rootPath
- : '$rootPath${Platform.pathSeparator}';
- if (!targetPath.startsWith(prefix) ||
- generation != _generation ||
- scope != _scopeId ||
- directory.path != _directory?.path) {
- notice = 'The video could not be removed from this device.';
- emit();
- return LocalRemovalResult.unavailable;
- }
- await target.delete();
+ await writer.run(() async {
+ if (!await _contained(directory, path)) {
+ throw const FileSystemException(
+ 'Recording is outside selected owner',
+ );
+ }
+ writer.check();
+ target.deleteSync();
+ });
} on Object {
if (generation == _generation && scope == _scopeId) {
notice = 'The video could not be removed from this device.';
@@ -413,7 +470,7 @@ class ArchiveController extends ChangeNotifier {
: 'Video removed from this device.';
emit();
try {
- await _saveStrict(directory, clips, pendingJob, events);
+ await _saveStrict(directory, clips, pendingJob, events, writer, owner);
return LocalRemovalResult.removed;
} on Object {
notice =
@@ -424,13 +481,23 @@ class ArchiveController extends ChangeNotifier {
}
Future<void> importFile(String path, double duration) async {
- if (!canWrite || _directory == null) return;
+ if (!canWrite || _directory == null || _writer == null) return;
final generation = _generation;
final directory = _directory!;
- await directory.create(recursive: true);
- if (generation != _generation) return;
- final id = 'street_${DateTime.now().millisecondsSinceEpoch}';
- final file = await File(path).copy('${directory.path}/$id.mp4');
+ final writer = _writer!;
+ final id = 'street_${DateTime.now().microsecondsSinceEpoch}';
+ final file = File('${directory.path}/$id.mp4');
+ await writer.run(() async {
+ await directory.create(recursive: true);
+ final temp = File('${file.path}.${writer.sessionId}.tmp');
+ try {
+ await File(path).copy(temp.path);
+ writer.check();
+ temp.renameSync(file.path);
+ } finally {
+ if (temp.existsSync()) temp.deleteSync();
+ }
+ });
if (generation != _generation) return;
final sourceName = basename(path);
clips.add(
@@ -513,7 +580,13 @@ class ArchiveController extends ChangeNotifier {
Future<CloudDeletionResult> deleteCloudLibrary() async {
final gateway = _gateway;
final directory = _directory;
- if (gateway == null || directory == null || !canDeleteCloudLibrary) {
+ final writer = _writer;
+ final owner = _owner;
+ if (gateway == null ||
+ directory == null ||
+ writer == null ||
+ owner == null ||
+ !canDeleteCloudLibrary) {
return CloudDeletionResult.failed;
}
final generation = _generation;
@@ -529,6 +602,8 @@ class ArchiveController extends ChangeNotifier {
emit();
try {
final response = await gateway.deleteLibrary(token);
+ writer.check();
+ token.throwIfCanceled();
_validateDeletion(response, 'ok', scope);
for (final clip in savedClips) {
@@ -560,15 +635,16 @@ class ArchiveController extends ChangeNotifier {
emit();
}
try {
- await _saveStrict(directory, savedClips, '', savedEvents);
- _pendingReconciliation.remove(scope);
- return CloudDeletionResult.deleted;
- } on Object {
- _pendingReconciliation[scope] = _ArchiveSnapshot(
- savedClips.map((c) => c.copy()).toList(),
+ await _saveStrict(
+ directory,
+ savedClips,
'',
- List<ArchiveEvent>.from(savedEvents),
+ savedEvents,
+ writer,
+ owner,
);
+ return CloudDeletionResult.deleted;
+ } on Object {
if (current) {
notice =
'Cloud library was deleted, but local status could not be saved. Your device videos were kept.';
@@ -656,6 +732,7 @@ class ArchiveController extends ChangeNotifier {
final job = await gateway.createIndex(token);
token.throwIfCanceled();
pendingJob = job.jobId;
+ _pendingHandle = job;
await save();
if (pendingJob.isEmpty) {
throw const MalformedResponse('No index job identifier');
@@ -720,9 +797,21 @@ class ArchiveController extends ChangeNotifier {
CancellationToken token,
) async {
final watch = Stopwatch()..start();
+ final job =
+ _pendingHandle ??
+ await gateway.rebindJob(
+ DurableJobReference(
+ jobId: pendingJob,
+ ownerKey: gateway.context.ownerKey,
+ scopeKey: gateway.scope.scopeKey,
+ policyRevision: gateway.context.policyRevision,
+ ),
+ );
+ token.throwIfCanceled();
+ _pendingHandle = job;
for (var attempt = 0; attempt < 120; attempt++) {
token.throwIfCanceled();
- final state = await gateway.indexStatus(pendingJob, token);
+ final state = await gateway.indexStatus(job, token);
token.throwIfCanceled();
if (indexDone(state.status)) {
await gateway.refreshVersion();
@@ -813,6 +902,7 @@ class ArchiveController extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
+ _writer?.retire();
_queryToken?.cancel();
stopWork();
super.dispose();
diff --git a/example/05_framebase_userlogin/lib/data/search_gateway.dart b/example/05_framebase_userlogin/lib/data/search_gateway.dart
index 5bbc97d..b1ad000 100644
--- a/example/05_framebase_userlogin/lib/data/search_gateway.dart
+++ b/example/05_framebase_userlogin/lib/data/search_gateway.dart
@@ -1,19 +1,17 @@
import 'dart:io';
-import 'dart:convert';
import 'dart:typed_data';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
import '../user/library_scope.dart';
const archiveStream = 'street_study';
-
String basename(String path) => path.replaceAll('\\', '/').split('/').last;
class FrameMatch {
- const FrameMatch({required this.hit, this.imageUrl, this.imageBytes});
+ const FrameMatch({required this.hit, this.imageBytes});
final VideoSearchHit hit;
- final String? imageUrl;
final Uint8List? imageBytes;
+ String? get imageUrl => null;
String? get assetId => hit.assetId;
String get fileName => hit.fileName ?? '';
String get sourceKey => hit.assetId ?? hit.fileName ?? '';
@@ -22,15 +20,6 @@ class FrameMatch {
double? get distance => hit.distance;
}
-bool trustedPreviewUrl(String value) {
- final uri = Uri.tryParse(value);
- return uri != null &&
- (uri.scheme == 'https' ||
- (!uri.hasScheme &&
- !uri.hasAuthority &&
- uri.path == '/api/external/v1/image/get_image'));
-}
-
class SearchBatch {
const SearchBatch({
required this.matches,
@@ -46,38 +35,46 @@ class SearchBatch {
final int imageMs;
}
-/// One session, one application-owned collection. No credentials or signed URLs
-/// are persisted. The low-level SDK is used consistently for collection selectors.
+/// Every cloud operation uses the same immutable SDK app-user session.
class SearchGateway {
SearchGateway(
- this.keys,
+ this.session,
String scopeId, {
- VmodalTransport? transport,
Future<void> Function()? ensureFresh,
}) : collection = validateLibraryScope(scopeId),
+ // Public constructor keeps the host renewal callback named consistently.
// ignore: prefer_initializing_formals
_ensureFresh = ensureFresh {
- client = VmodalClient(
- config: SdkConfig(
- apiKeyProvider: keys,
- timeout: const Duration(seconds: 60),
+ scope = session.scope(
+ ContentMapping.opaque(
+ collectionId: collection,
+ streamName: archiveStream,
),
- transport: transport,
);
}
- final MutableApiKeyProvider keys;
+ final UserSession session;
+ late final UserScope scope;
final String collection;
final Future<void> Function()? _ensureFresh;
void Function(int status)? onAccessFailure;
- late final VmodalClient client;
- String accountId = '';
+ String get accountId => session.context.appUserId;
+ SessionContext get context => session.context;
int? version;
- Future<void> _fresh() async => await _ensureFresh?.call();
+ void _active() {
+ if (!session.isActive) throw const SessionInvalidated();
+ }
+
+ Future<void> _fresh() async {
+ _active();
+ await _ensureFresh?.call();
+ _active();
+ }
void reportFailure(Object error) {
- if (error is SdkException &&
+ if (session.isActive &&
+ error is SdkException &&
(error.statusCode == 401 || error.statusCode == 403)) {
onAccessFailure?.call(error.statusCode);
}
@@ -86,47 +83,34 @@ class SearchGateway {
Future<T> _call<T>(Future<T> Function() run) async {
await _fresh();
try {
- return await run();
+ final result = await run();
+ _active();
+ return result;
} on SdkException catch (error) {
reportFailure(error);
rethrow;
}
}
- Future<void> connect(String expectedUserId) async {
- final profile = await client.auth.me();
- if (profile.userId != expectedUserId) {
- throw const AuthException('No authenticated identity');
- }
- accountId = profile.userId!;
+ Future<void> connect(String expectedPrincipal) async {
+ await session.verifyPrincipal(expectedPrincipal);
await refreshVersion();
- await listJobs();
+ if (scope.mapping.actions.contains(UserAction.indexation)) await listJobs();
}
Future<void> refreshVersion() async {
- final groups = await _call(
- () => client.collections.listGroups(mode: 'vid_file'),
- );
- version = groups
- .findGroup(collection, mode: 'vid_file')
- ?.latestLancedbVersion;
+ final next = await _call(() => scope.latestVersion());
+ _active();
+ version = next;
}
- Future<void> listJobs() async {
- await _call(
- () => client.indexes.jobsList(mode: 'vid_file', groupName: collection),
- );
- }
+ Future<void> listJobs() async => await _call(() => scope.listIndexJobs());
Future<DeleteCollectionResponse> previewLibraryDeletion(
CancellationToken cancellation,
) => _call(
- () => client.collections.delete(
- groupName: collection,
- mode: 'vid_file',
- scope: 'all',
- dryRun: true,
- confirm: false,
+ () => scope.deleteCollection(
+ options: const ScopedDeleteCollectionOptions(dryRun: true),
cancellation: cancellation,
),
);
@@ -134,51 +118,35 @@ class SearchGateway {
Future<DeleteCollectionResponse> deleteLibrary(
CancellationToken cancellation,
) => _call(
- () => client.collections.delete(
- groupName: collection,
- mode: 'vid_file',
- scope: 'all',
- dryRun: false,
- confirm: true,
+ () => scope.deleteCollection(
+ options: const ScopedDeleteCollectionOptions(confirm: true),
cancellation: cancellation,
),
);
Future<UploadTask<VideoUploadResponse>> upload(File file) async {
await _fresh();
- return client.collections.videoUpload(
- UploadSource.fromFile(file),
- collectionName: collection,
- subCollectionName: archiveStream,
- );
+ return scope.upload(UploadSource.fromFile(file));
}
- Future<IndexationSubmitResponse> createIndex(
- CancellationToken cancellation,
- ) async {
- return _call(
- () => client.indexes.createIndex(
- IndexationSubmitRequest(
- mode: 'vid_file',
- groupName: collection,
- streamName: archiveStream,
- indexType: 'vid_img_emb',
- modality: 'vid_img_emb',
- reProcess: true,
- ),
- cancellation: cancellation,
+ Future<SessionJob> createIndex(CancellationToken cancellation) => _call(
+ () => scope.createIndex(
+ options: const ScopedCreateIndexOptions(
+ indexType: 'vid_img_emb',
+ modality: 'vid_img_emb',
+ reProcess: true,
),
- );
- }
+ cancellation: cancellation,
+ ),
+ );
Future<IndexationStatusResponse> indexStatus(
- String job,
+ SessionJob job,
CancellationToken cancellation,
- ) async {
- return _call(
- () => client.indexes.indexStatus(job, cancellation: cancellation),
- );
- }
+ ) => _call(() => scope.indexStatus(job, cancellation: cancellation));
+
+ Future<SessionJob> rebindJob(DurableJobReference reference) =>
+ _call(() => scope.rebindJob(reference));
Future<SearchBatch> search(
String query, {
@@ -189,14 +157,10 @@ class SearchGateway {
final token = cancellation ?? CancellationToken();
final timer = Stopwatch()..start();
final response = await _call(
- () => client.searches.searchVideo(
- SearchRequest(
- queryText: query,
+ () => scope.search(
+ query,
+ options: ScopedSearchOptions(
imageQuery: imageQuery,
- mode: 'vid_file',
- groupName: collection,
- streamName: archiveStream,
- searchSources: const ['image'],
limit: 30,
imageEmbScoreMin: maxDistance,
versionLancedb: version,
@@ -205,114 +169,42 @@ class SearchGateway {
),
);
final searchMs = timer.elapsedMilliseconds;
- // Enforce the displayed cutoff defensively on returned rows as well.
- // A client-filtered result is distinct from the raw server result count.
- final usable = response.videoHits.where((hit) {
- final distance = hit.distance;
- return (hit.assetId ?? hit.fileName ?? '').trim().isNotEmpty &&
- (distance == null || distance <= maxDistance);
- }).toList();
- final urls = <int, String>{};
- final imageBytes = <int, Uint8List>{};
- for (var i = 0; i < usable.length; i++) {
- final preview = usable[i].previewImageUrl;
- if (preview != null && trustedPreviewUrl(preview)) urls[i] = preview;
- }
- final lookupIndexes = <int>[
- for (var i = 0; i < usable.length; i++)
- if (usable[i].previewImageUrl == null &&
- (usable[i].fileName?.isNotEmpty ?? false))
- i,
- ];
- if (lookupIndexes.isNotEmpty) {
- final resolved = await _call(
- () => client.images.getUrlBulk(
- lookupIndexes
- .map(
- (index) => <String, Object?>{
- 'mode': 'vid_file',
- 'group_name': collection,
- 'modality': 'vid_img',
- 'stream_name': archiveStream,
- 'filename': usable[index].fileName,
- if (usable[index].playbackOffsetMs != null)
- 'ts_unix_13digits': usable[index].playbackOffsetMs
- .toString()
- .padLeft(13, '0'),
- },
- )
- .toList(),
- cancellation: token,
- ),
- );
- for (var i = 0; i < resolved.records.length; i++) {
- final row = resolved.records[i];
- final rawIndex = row['input_index'];
- final parsed = num.tryParse('$rawIndex');
- final recordIndex = rawIndex == null
- ? i
- : parsed != null && parsed.isFinite && parsed == parsed.toInt()
- ? parsed.toInt()
- : null;
- final url = '${row['url_pre_signed'] ?? ''}';
- if (recordIndex != null &&
- recordIndex >= 0 &&
- recordIndex < lookupIndexes.length &&
- row['found'] != false &&
- trustedPreviewUrl(url)) {
- final index = lookupIndexes[recordIndex];
- urls.putIfAbsent(index, () => url);
- }
+ final matches = <FrameMatch>[];
+ for (var i = 0; i < response.videoHits.length; i++) {
+ final hit = response.videoHits[i];
+ if ((hit.assetId ?? hit.fileName ?? '').trim().isEmpty ||
+ (hit.distance != null && hit.distance! > maxDistance)) {
+ continue;
}
- }
- // Relative signed routes are downloaded through the SDK without guessing
- // an absolute origin. A malformed image remains local to its result card.
- if (urls.isNotEmpty) {
- final downloaded = await _call(
- () => client.images.getImageBulkFromUrls(
- urls.values.toList(),
- cancellation: token,
- ),
- );
- final byUrl = <String, Uint8List>{};
- for (final row in downloaded.records) {
- final url = '${row['url_pre_signed'] ?? ''}';
- final encoded = '${row['content_base64'] ?? ''}';
- if (url.isNotEmpty && encoded.isNotEmpty) {
- try {
- byUrl[url] = base64Decode(encoded);
- } on FormatException {
- /* Keep a per-card placeholder. */
- }
- }
- }
- for (final entry in urls.entries) {
- if (byUrl[entry.value] != null) {
- imageBytes[entry.key] = byUrl[entry.value]!;
+ Uint8List? bytes;
+ if (i < response.assets.length) {
+ try {
+ bytes = await _call(
+ () => scope.imageBytes(
+ response.assets[i],
+ maxBytes: 8 * 1024 * 1024,
+ cancellation: token,
+ ),
+ );
+ } on FeatureDisabled {
+ // Unavailable media retains its local result-card placeholder.
}
}
+ _active();
+ matches.add(FrameMatch(hit: hit, imageBytes: bytes));
}
token.throwIfCanceled();
+ _active();
return SearchBatch(
- matches: [
- for (var i = 0; i < usable.length; i++)
- FrameMatch(
- hit: usable[i],
- imageUrl: urls[i]?.startsWith('https://') == true ? urls[i] : null,
- imageBytes: imageBytes[i],
- ),
- ],
- total: response.cntTotal,
+ matches: List<FrameMatch>.unmodifiable(matches),
+ total: matches.length,
serverMs: response.executionTimeMs,
roundTripMs: searchMs,
imageMs: timer.elapsedMilliseconds - searchMs,
);
}
- Future<void> close() async {
- keys.close();
- await client.close();
- }
+ Future<void> close() => session.close();
}
bool indexDone(String state) => const {
diff --git a/example/05_framebase_userlogin/lib/main.dart b/example/05_framebase_userlogin/lib/main.dart
index df01acf..844328b 100644
--- a/example/05_framebase_userlogin/lib/main.dart
+++ b/example/05_framebase_userlogin/lib/main.dart
@@ -42,6 +42,7 @@ class _FramebaseAppState extends State<FramebaseApp>
with WidgetsBindingObserver {
late final ArchiveController archive;
late final UserSessionController session;
+ String? _viewSessionId;
@override
void initState() {
super.initState();
@@ -54,6 +55,16 @@ class _FramebaseAppState extends State<FramebaseApp>
archive: archive,
);
WidgetsBinding.instance.addObserver(this);
+ _viewSessionId = session.gateway?.session.sessionId;
+ session.addListener(_sessionChanged);
+ }
+
+ void _sessionChanged() {
+ final id = session.gateway?.session.sessionId;
+ if (id == _viewSessionId) return;
+ _viewSessionId = id;
+ PaintingBinding.instance.imageCache.clear();
+ PaintingBinding.instance.imageCache.clearLiveImages();
}
@override
@@ -69,6 +80,7 @@ class _FramebaseAppState extends State<FramebaseApp>
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
+ session.removeListener(_sessionChanged);
if (widget.session == null) session.dispose();
if (widget.controller == null) archive.dispose();
super.dispose();
@@ -78,7 +90,9 @@ class _FramebaseAppState extends State<FramebaseApp>
Widget build(BuildContext context) => AnimatedBuilder(
animation: session,
builder: (context, _) => MaterialApp(
- key: ValueKey('${session.state}_${session.user?.uid ?? ''}'),
+ key: ValueKey(
+ '${session.state}_${session.user?.uid ?? ''}_${session.gateway?.session.sessionId ?? ''}',
+ ),
title: 'Framebase',
debugShowCheckedModeBanner: false,
theme: ThemeData(
@@ -190,7 +204,7 @@ class _LibraryPageState extends State<LibraryPage> {
Future<void> importVideo() async {
if (archive.busy || !widget.session.canWrite) return;
- final uid = widget.session.user?.uid;
+ final sessionId = widget.session.gateway?.session.sessionId;
VideoPlayerController? player;
try {
final file = await openFile(
@@ -206,24 +220,27 @@ class _LibraryPageState extends State<LibraryPage> {
if (file == null) return;
if (!mounted ||
!widget.session.canWrite ||
- widget.session.user?.uid != uid) {
+ widget.session.gateway?.session.sessionId != sessionId) {
return;
}
if (await file.length() > 100 * 1024 * 1024) {
throw const FormatException();
}
+ if (!mounted || widget.session.gateway?.session.sessionId != sessionId) {
+ return;
+ }
player = VideoPlayerController.file(File(file.path));
await player.initialize().timeout(const Duration(seconds: 15));
if (!mounted ||
!widget.session.canWrite ||
- widget.session.user?.uid != uid) {
+ widget.session.gateway?.session.sessionId != sessionId) {
return;
}
await archive.importFile(
file.path,
player.value.duration.inMilliseconds / 1000,
);
- if (mounted) {
+ if (mounted && widget.session.gateway?.session.sessionId == sessionId) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
@@ -233,7 +250,7 @@ class _LibraryPageState extends State<LibraryPage> {
);
}
} on Object {
- if (mounted) {
+ if (mounted && widget.session.gateway?.session.sessionId == sessionId) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Choose a playable MP4 smaller than 100 MB.'),
@@ -1000,12 +1017,6 @@ class MomentTile extends StatelessWidget {
fit: BoxFit.cover,
errorBuilder: (_, _, _) => const MissingFrame(),
)
- else if (hit.imageUrl != null)
- Image.network(
- hit.imageUrl!,
- fit: BoxFit.cover,
- errorBuilder: (_, _, _) => const MissingFrame(),
- )
else
const MissingFrame(),
if (hit.seconds != null)
@@ -1063,19 +1074,36 @@ class RecordingSheet extends StatefulWidget {
class _RecordingSheetState extends State<RecordingSheet> {
VideoPlayerController? player;
String? error;
+ String? _sessionId;
+ bool _retired = false;
+ bool get _current =>
+ mounted && !_retired && widget.archive.sessionId == _sessionId;
@override
void initState() {
super.initState();
+ _sessionId = widget.archive.sessionId;
+ widget.archive.addListener(_sessionChanged);
unawaited(load());
}
+ void _sessionChanged() {
+ if (_retired || widget.archive.sessionId == _sessionId) return;
+ _retired = true;
+ final old = player;
+ player = null;
+ old?.removeListener(refresh);
+ unawaited(old?.dispose() ?? Future<void>.value());
+ if (mounted) setState(() {});
+ }
+
Future<void> load() async {
VideoPlayerController? next;
try {
final file = await widget.archive.localFile(widget.clip);
+ if (!_current) return;
next = VideoPlayerController.file(file);
await next.initialize().timeout(const Duration(seconds: 20));
- if (!mounted) {
+ if (!_current) {
await next.dispose();
return;
}
@@ -1084,7 +1112,7 @@ class _RecordingSheetState extends State<RecordingSheet> {
seconds <= next.value.duration.inMilliseconds / 1000) {
await next.seekTo(Duration(milliseconds: (seconds * 1000).round()));
}
- if (!mounted) {
+ if (!_current) {
await next.dispose();
return;
}
@@ -1092,7 +1120,7 @@ class _RecordingSheetState extends State<RecordingSheet> {
setState(() => player = next);
} on Object {
await next?.dispose();
- if (mounted) setState(() => error = 'This video could not be opened.');
+ if (_current) setState(() => error = 'This video could not be opened.');
}
}
@@ -1120,15 +1148,16 @@ class _RecordingSheetState extends State<RecordingSheet> {
],
),
);
- if (confirmed != true || !mounted) return;
+ if (confirmed != true || !mounted || !_current) return;
final messenger = ScaffoldMessenger.of(context);
final old = player;
old?.removeListener(refresh);
await old?.pause();
await old?.dispose();
player = null;
+ if (!mounted || !_current) return;
final result = await widget.archive.removeLocalCopy(widget.clip);
- if (!mounted) return;
+ if (!mounted || !_current) return;
if (result == LocalRemovalResult.unavailable) {
setState(
() => error = 'The video could not be removed from this device.',
@@ -1141,11 +1170,12 @@ class _RecordingSheetState extends State<RecordingSheet> {
}
void refresh() {
- if (mounted) setState(() {});
+ if (_current) setState(() {});
}
@override
void dispose() {
+ widget.archive.removeListener(_sessionChanged);
player?.removeListener(refresh);
unawaited(player?.dispose() ?? Future.value());
super.dispose();
@@ -1153,6 +1183,7 @@ class _RecordingSheetState extends State<RecordingSheet> {
@override
Widget build(BuildContext context) {
+ if (_retired) return const SizedBox.shrink();
final p = player;
final length = p?.value.duration.inMilliseconds.toDouble() ?? 0;
final position = (p?.value.position.inMilliseconds.toDouble() ?? 0).clamp(
@@ -1366,6 +1397,7 @@ Future<void> prepareArchive(
ArchiveController archive,
) async {
if (archive.busy || !archive.connected || !archive.canWrite) return;
+ final sessionId = archive.sessionId;
if (archive.pendingJob.isNotEmpty) {
unawaited(archive.resumeIndex());
return;
@@ -1392,7 +1424,9 @@ Future<void> prepareArchive(
],
),
);
- if (confirmed == true) unawaited(archive.uploadAndIndex());
+ if (confirmed == true && context.mounted && archive.sessionId == sessionId) {
+ unawaited(archive.uploadAndIndex());
+ }
}
class WorkStatus extends StatelessWidget {
@@ -1427,6 +1461,7 @@ class StorageDeletionPage extends StatelessWidget {
final ArchiveController archive;
Future<void> deleteCloudLibrary(BuildContext context) async {
+ final sessionId = archive.sessionId;
final previewApproved = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
@@ -1446,9 +1481,13 @@ class StorageDeletionPage extends StatelessWidget {
],
),
);
- if (previewApproved != true || !context.mounted) return;
+ if (previewApproved != true ||
+ !context.mounted ||
+ archive.sessionId != sessionId) {
+ return;
+ }
final preview = await archive.previewCloudLibraryDeletion();
- if (!context.mounted) return;
+ if (!context.mounted || archive.sessionId != sessionId) return;
if (preview == null) {
ScaffoldMessenger.of(
context,
@@ -1478,9 +1517,13 @@ class StorageDeletionPage extends StatelessWidget {
],
),
);
- if (confirmed != true || !context.mounted) return;
+ if (confirmed != true ||
+ !context.mounted ||
+ archive.sessionId != sessionId) {
+ return;
+ }
await archive.deleteCloudLibrary();
- if (!context.mounted) return;
+ if (!context.mounted || archive.sessionId != sessionId) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(archive.notice)));
diff --git a/example/05_framebase_userlogin/lib/user/login_page.dart b/example/05_framebase_userlogin/lib/user/login_page.dart
index c724a03..abdeb21 100644
--- a/example/05_framebase_userlogin/lib/user/login_page.dart
+++ b/example/05_framebase_userlogin/lib/user/login_page.dart
@@ -46,9 +46,7 @@ class _LoginPageState extends State<LoginPage> {
Text(widget.session.message),
const SizedBox(height: 16),
if (widget.session.failureKind ==
- SessionFailureKind.firebaseIdentityExpired ||
- widget.session.failureKind ==
- SessionFailureKind.vmodalUnauthorized)
+ SessionFailureKind.firebaseIdentityExpired)
FilledButton(
onPressed: widget.session.signOut,
child: const Text('Sign in again'),
diff --git a/example/05_framebase_userlogin/lib/user/user_session_controller.dart b/example/05_framebase_userlogin/lib/user/user_session_controller.dart
index 86821fc..3982817 100644
--- a/example/05_framebase_userlogin/lib/user/user_session_controller.dart
+++ b/example/05_framebase_userlogin/lib/user/user_session_controller.dart
@@ -29,7 +29,7 @@ enum SessionFailureKind {
typedef GatewayFactory =
SearchGateway Function(
- MutableApiKeyProvider provider,
+ UserSession session,
String scopeId,
Future<void> Function() ensureFresh,
);
@@ -42,12 +42,15 @@ class UserSessionController extends ChangeNotifier {
GatewayFactory? gatewayFactory,
DateTime Function()? clock,
Future<void> Function(Duration)? delay,
+ SdkConfig? config,
+ this.transportFactory,
}) : gatewayFactory =
gatewayFactory ??
((provider, id, fresh) =>
SearchGateway(provider, id, ensureFresh: fresh)),
clock = clock ?? DateTime.now,
- delay = delay ?? Future<void>.delayed {
+ delay = delay ?? Future<void>.delayed,
+ config = config ?? SdkConfig(timeout: const Duration(seconds: 60)) {
_subscription = auth.users.listen(_onUser);
}
@@ -56,7 +59,7 @@ class UserSessionController extends ChangeNotifier {
static const _identityMessage = 'Your sign-in expired. Sign in again.';
static const _deniedMessage = 'Access to this library is unavailable.';
static const _unauthorizedMessage =
- 'Your library session expired. Sign in again.';
+ 'The tenant connection needs recovery. Retry to reconnect your library.';
static const _contractMessage =
'The library connection is not configured correctly.';
static const _backoff = [
@@ -70,12 +73,15 @@ class UserSessionController extends ChangeNotifier {
final GatewayFactory gatewayFactory;
final DateTime Function() clock;
final Future<void> Function(Duration) delay;
+ final SdkConfig config;
+ final VmodalTransport Function(SdkConfig)? transportFactory;
late final StreamSubscription<AppUser?> _subscription;
SessionState state = SessionState.loading;
SessionFailureKind? failureKind;
AppUser? user;
VmodalCredential? _credential;
- MutableApiKeyProvider? _provider;
+ TenantCredentialSource? _tenant;
+ UserSessionManager? _manager;
SearchGateway? gateway;
Timer? _timer;
Future<void>? _refreshing;
@@ -84,7 +90,9 @@ class UserSessionController extends ChangeNotifier {
int _generation = 0;
bool _disposed = false;
- bool get canRetry => failureKind == SessionFailureKind.transient;
+ bool get canRetry =>
+ failureKind == SessionFailureKind.transient ||
+ failureKind == SessionFailureKind.vmodalUnauthorized;
bool get canRead =>
state == SessionState.ready &&
(_credential?.permissions.contains('library:read') ?? false);
@@ -96,30 +104,131 @@ class UserSessionController extends ChangeNotifier {
if (!_disposed) notifyListeners();
}
- void _teardown() {
- _generation++;
+ int _teardown() {
+ final generation = ++_generation;
+ final manager = _manager;
+ final old = gateway;
_timer?.cancel();
_timer = null;
- archive.deactivate();
- _provider?.clear();
_refreshing = null;
- final old = gateway;
gateway = null;
- _provider = null;
_credential = null;
- if (old != null) unawaited(old.close());
+ final closing = manager?.logout();
+ if (closing != null) _observeClose(closing);
+ if (old != null) _observeClose(Future<void>.sync(old.close));
+ if (generation == _generation) archive.deactivate();
+ return generation;
+ }
+
+ void _observeClose(Future<void> cleanup) {
+ unawaited(cleanup.catchError((Object _) {}));
+ }
+
+ ContentMapping _mapping(VmodalCredential credential) => ContentMapping.opaque(
+ collectionId: credential.scopeId!,
+ streamName: archiveStream,
+ actions: {
+ UserAction.discover,
+ UserAction.search,
+ UserAction.media,
+ if (credential.permissions.contains('library:write')) ...{
+ UserAction.upload,
+ UserAction.metadata,
+ UserAction.indexation,
+ },
+ if (credential.collectionWide &&
+ credential.permissions.contains('library:write'))
+ UserAction.delete,
+ },
+ collectionWide: credential.collectionWide,
+ );
+
+ TenantCredential _tenantCredential(VmodalCredential credential) =>
+ TenantCredential(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: credential.tenantBinding,
+ principal: credential.vmodalUserId!,
+ apiKey: credential.apiToken!,
+ );
+
+ void _configureTenant(VmodalCredential credential) {
+ final existing = _tenant;
+ if (existing != null &&
+ existing.tenantId == credential.tenantBinding &&
+ existing.expectedPrincipal == credential.vmodalUserId) {
+ existing.install(_tenantCredential(credential));
+ return;
+ }
+ final old = _manager;
+ if (old != null) _observeClose(old.close());
+ existing?.close();
+ final source = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: credential.tenantBinding,
+ expectedPrincipal: credential.vmodalUserId!,
+ initialKey: credential.apiToken!,
+ renew: () async {
+ final account = user;
+ final prior = _credential;
+ final generation = _generation;
+ if (account == null || prior == null) throw const CredentialDenied();
+ VmodalCredential renewed;
+ try {
+ renewed = await _acquire(account, generation, previous: prior);
+ } on FirebaseIdentityTransient {
+ if (_current(account, generation)) _recover();
+ rethrow;
+ } on CredentialTransient {
+ if (_current(account, generation)) _recover();
+ rethrow;
+ } on Object catch (error) {
+ if (_current(account, generation)) _failFor(error);
+ rethrow;
+ }
+ if (!prior.samePolicy(renewed)) {
+ // A policy change cannot be installed as a credential-only rotation.
+ if (_current(account, generation)) {
+ final nextGeneration = _teardown();
+ if (!_current(account, nextGeneration)) {
+ throw const SessionInvalidated();
+ }
+ state = SessionState.resolving;
+ _notify();
+ if (_current(account, nextGeneration)) {
+ unawaited(_resolve(account, nextGeneration));
+ }
+ }
+ throw const CredentialContractError();
+ }
+ if (_current(account, generation)) {
+ _credential = renewed;
+ _schedule();
+ }
+ return _tenantCredential(renewed);
+ },
+ );
+ _tenant = source;
+ _manager = UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: transportFactory,
+ );
}
void _onUser(AppUser? next) {
if (_disposed) return;
if (next?.uid == user?.uid && state != SessionState.loading) return;
- _teardown();
+ final generation = _teardown();
+ if (generation != _generation) return;
user = next;
+ signingIn = false;
failureKind = null;
message = '';
state = next == null ? SessionState.signedOut : SessionState.resolving;
_notify();
- if (next != null) unawaited(_resolve(next, _generation));
+ if (next != null && _current(next, generation)) {
+ unawaited(_resolve(next, generation));
+ }
}
bool _current(AppUser account, int generation) =>
@@ -164,10 +273,21 @@ class UserSessionController extends ChangeNotifier {
try {
final credential = await _acquire(account, generation);
if (!_current(account, generation)) return;
- final provider = MutableApiKeyProvider(credential.apiToken!);
- _provider = provider;
+ _configureTenant(credential);
_credential = credential;
- next = gatewayFactory(provider, credential.scopeId!, ensureFresh);
+ final sdkSession = await _manager!.openUserSession(
+ tenantId: credential.tenantBinding,
+ appUserId: account.uid,
+ allowedContentMapping: [_mapping(credential)],
+ );
+ if (!_current(account, generation)) {
+ _observeClose(sdkSession.close());
+ return;
+ }
+ next = gatewayFactory(sdkSession, credential.scopeId!, () {
+ if (!_current(account, generation)) throw const SessionInvalidated();
+ return ensureFresh();
+ });
next.onAccessFailure = (status) {
if (_current(account, generation)) {
if (status == 403) {
@@ -177,17 +297,16 @@ class UserSessionController extends ChangeNotifier {
_deniedMessage,
);
} else {
- _fail(
- SessionState.error,
- SessionFailureKind.vmodalUnauthorized,
- _unauthorizedMessage,
- );
+ state = SessionState.recoverable;
+ failureKind = SessionFailureKind.vmodalUnauthorized;
+ message = _unauthorizedMessage;
+ _notify();
}
}
};
await next.connect(credential.vmodalUserId!);
if (!_current(account, generation)) {
- await next.close();
+ _observeClose(Future<void>.sync(next.close));
return;
}
gateway = next;
@@ -196,6 +315,10 @@ class UserSessionController extends ChangeNotifier {
next,
canRead: credential.permissions.contains('library:read'),
canWrite: credential.permissions.contains('library:write'),
+ serviceNamespace: sdkSession.context.serviceNamespace,
+ tenantId: sdkSession.context.tenantId,
+ appUserId: sdkSession.context.appUserId,
+ policyRevision: sdkSession.context.policyRevision,
);
if (!_current(account, generation)) return;
state = SessionState.ready;
@@ -205,13 +328,19 @@ class UserSessionController extends ChangeNotifier {
_notify();
} on FirebaseIdentityTransient {
if (_current(account, generation)) _recover();
- if (next != null && next != gateway) await next.close();
+ if (next != null && next != gateway) {
+ _observeClose(Future<void>.sync(next.close));
+ }
} on CredentialTransient {
if (_current(account, generation)) _recover();
- if (next != null && next != gateway) await next.close();
+ if (next != null && next != gateway) {
+ _observeClose(Future<void>.sync(next.close));
+ }
} on Object catch (error) {
if (_current(account, generation)) _failFor(error);
- if (next != null && next != gateway) await next.close();
+ if (next != null && next != gateway) {
+ _observeClose(Future<void>.sync(next.close));
+ }
}
}
@@ -238,7 +367,7 @@ class UserSessionController extends ChangeNotifier {
} else if (error is AuthException ||
error is ApiException && error.statusCode == 401) {
_fail(
- SessionState.error,
+ SessionState.recoverable,
SessionFailureKind.vmodalUnauthorized,
_unauthorizedMessage,
);
@@ -254,7 +383,8 @@ class UserSessionController extends ChangeNotifier {
}
void _fail(SessionState next, SessionFailureKind kind, String safeMessage) {
- _teardown();
+ final generation = _teardown();
+ if (generation != _generation) return;
state = next;
failureKind = kind;
message = safeMessage;
@@ -275,7 +405,7 @@ class UserSessionController extends ChangeNotifier {
Future<void> ensureFresh() {
final account = user;
final credential = _credential;
- if (account == null || credential == null || _provider == null) {
+ if (account == null || credential == null || _manager?.current == null) {
return Future.error(const CredentialDenied());
}
if (credential.expiresAt!.isAfter(
@@ -304,14 +434,8 @@ class UserSessionController extends ChangeNotifier {
Future<void> _refresh(AppUser account, int generation) async {
try {
- final renewed = await _acquire(
- account,
- generation,
- previous: _credential,
- );
+ await _tenant!.renewCredential();
if (!_current(account, generation)) throw const CredentialDenied();
- _provider!.rotate(renewed.apiToken!);
- _credential = renewed;
state = SessionState.ready;
failureKind = null;
message = '';
@@ -323,6 +447,14 @@ class UserSessionController extends ChangeNotifier {
} on CredentialTransient {
if (_current(account, generation)) _recover();
rethrow;
+ } on TenantAuthException {
+ if (_current(account, generation) && failureKind == null) {
+ state = SessionState.recoverable;
+ failureKind = SessionFailureKind.vmodalUnauthorized;
+ message = _unauthorizedMessage;
+ _notify();
+ }
+ rethrow;
} on Object catch (error) {
if (_current(account, generation)) _failFor(error);
rethrow;
@@ -330,30 +462,37 @@ class UserSessionController extends ChangeNotifier {
}
Future<void> signIn(String email, String password) async {
+ final generation = _generation;
signingIn = true;
message = '';
_notify();
+ if (_disposed || generation != _generation) return;
try {
await auth.signIn(email, password);
} on Object {
+ if (_disposed || generation != _generation) return;
message = 'Sign-in failed. Check your details and retry.';
_notify();
} finally {
- signingIn = false;
- _notify();
+ if (!_disposed && generation == _generation) {
+ signingIn = false;
+ _notify();
+ }
}
}
Future<void> retry() async {
+ final generation = _generation;
final account = user;
- if (account == null || failureKind != SessionFailureKind.transient) return;
- final established = _credential != null && _provider != null;
+ if (account == null || !canRetry) return;
+ final established = _credential != null && _manager?.current != null;
state = SessionState.resolving;
failureKind = null;
message = '';
_notify();
+ if (!_current(account, generation)) return;
if (!established) {
- await _resolve(account, _generation);
+ await _resolve(account, generation);
return;
}
try {
@@ -364,12 +503,14 @@ class UserSessionController extends ChangeNotifier {
}
Future<void> signOut() async {
- _teardown();
+ final generation = _teardown();
+ if (generation != _generation) return;
user = null;
state = SessionState.signedOut;
failureKind = null;
message = '';
_notify();
+ if (_disposed || generation != _generation || user != null) return;
await auth.signOut();
}
@@ -377,6 +518,9 @@ class UserSessionController extends ChangeNotifier {
void dispose() {
_disposed = true;
_teardown();
+ final closing = _manager?.close();
+ if (closing != null) _observeClose(closing);
+ _tenant?.close();
unawaited(_subscription.cancel());
unawaited(auth.close());
super.dispose();
diff --git a/example/05_framebase_userlogin/lib/user/vmodal_credential.dart b/example/05_framebase_userlogin/lib/user/vmodal_credential.dart
index 0609947..d340efa 100644
--- a/example/05_framebase_userlogin/lib/user/vmodal_credential.dart
+++ b/example/05_framebase_userlogin/lib/user/vmodal_credential.dart
@@ -13,12 +13,20 @@ class VmodalCredential {
required this.scopeId,
required this.allowed,
required this.permissions,
+ this.tenantId,
+ this.collectionWide = false,
});
final int? contractVersion;
final String? sessionId, apiToken, firebaseUid, vmodalUserId, scopeId;
final DateTime? issuedAt, expiresAt;
final bool allowed;
final Set<String> permissions;
+ final String? tenantId;
+ final bool collectionWide;
+
+ /// Version 1 issuers used their VModal principal as the tenant binding.
+ /// It never identifies the Firebase app user.
+ String get tenantBinding => tenantId ?? vmodalUserId!;
factory VmodalCredential.fromJson(Map<String, Object?> data) {
final issued = data['issued_at'];
@@ -40,6 +48,10 @@ class VmodalCredential {
vmodalUserId: data['vmodal_user_id'] is String
? data['vmodal_user_id'] as String
: null,
+ tenantId: data['tenant_id'] is String
+ ? data['tenant_id'] as String
+ : null,
+ collectionWide: data['collection_wide'] == true,
scopeId: data['scope_id'] is String ? data['scope_id'] as String : null,
allowed: data['allowed'] == true,
permissions: permissions is List
@@ -68,13 +80,20 @@ class VmodalCredential {
vmodalUserId!.trim().isEmpty ||
apiToken == null ||
apiToken!.trim().isEmpty ||
+ (tenantId != null && tenantId!.trim().isEmpty) ||
!expiresAt!.toUtc().isAfter(now.toUtc()) ||
(previous != null &&
(previous.vmodalUserId != vmodalUserId ||
- previous.scopeId != scopeId))) {
+ previous.tenantBinding != tenantBinding))) {
throw const CredentialContractError();
}
}
+
+ bool samePolicy(VmodalCredential other) =>
+ scopeId == other.scopeId &&
+ collectionWide == other.collectionWide &&
+ permissions.length == other.permissions.length &&
+ permissions.containsAll(other.permissions);
}
class CredentialDenied implements Exception {
diff --git a/example/05_framebase_userlogin/pubspec.lock b/example/05_framebase_userlogin/pubspec.lock
index e13653f..959cab9 100644
--- a/example/05_framebase_userlogin/pubspec.lock
+++ b/example/05_framebase_userlogin/pubspec.lock
@@ -66,7 +66,7 @@ packages:
source: hosted
version: "0.3.5+5"
crypto:
- dependency: transitive
+ dependency: "direct main"
description:
name: crypto
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
@@ -578,7 +578,7 @@ packages:
path: "../.."
relative: true
source: path
- version: "1.2.2"
+ version: "1.3.0"
web:
dependency: transitive
description:
diff --git a/example/05_framebase_userlogin/pubspec.yaml b/example/05_framebase_userlogin/pubspec.yaml
index 441f535..7724ebc 100644
--- a/example/05_framebase_userlogin/pubspec.yaml
+++ b/example/05_framebase_userlogin/pubspec.yaml
@@ -28,6 +28,7 @@ environment:
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
+ crypto: ^3.0.7
flutter:
sdk: flutter
diff --git a/example/05_framebase_userlogin/test/archive_controller_test.dart b/example/05_framebase_userlogin/test/archive_controller_test.dart
index 0ebbef4..3732c22 100644
--- a/example/05_framebase_userlogin/test/archive_controller_test.dart
+++ b/example/05_framebase_userlogin/test/archive_controller_test.dart
@@ -1,14 +1,15 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:framebase/data/archive_controller.dart';
import 'package:framebase/data/search_gateway.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+import 'session_fixture.dart';
class UploadGateway extends SearchGateway {
- UploadGateway()
- : super(MutableApiKeyProvider('fixture-upload'), 'scope_upload');
+ UploadGateway(UserSession session) : super(session, 'scope_upload');
@override
Future<UploadTask<VideoUploadResponse>> upload(File file) async =>
@@ -20,17 +21,9 @@ class UploadGateway extends SearchGateway {
});
});
- @override
- Future<IndexationSubmitResponse> createIndex(
- CancellationToken cancellation,
- ) async => IndexationSubmitResponse(const <String, Object?>{
- 'job_id': 'job-ready',
- 'status': 'queued',
- });
-
@override
Future<IndexationStatusResponse> indexStatus(
- String job,
+ SessionJob job,
CancellationToken cancellation,
) async => IndexationStatusResponse(const <String, Object?>{
'job_id': 'job-ready',
@@ -42,8 +35,8 @@ class UploadGateway extends SearchGateway {
}
class DeleteGateway extends SearchGateway {
- DeleteGateway({this.deleteError})
- : super(MutableApiKeyProvider('fixture-delete'), 'scope_delete');
+ DeleteGateway(UserSession session, {this.deleteError})
+ : super(session, 'scope_delete');
final Object? deleteError;
int previews = 0;
int deletes = 0;
@@ -82,6 +75,7 @@ class DeleteGateway extends SearchGateway {
}
class DelayedDeleteGateway extends DeleteGateway {
+ DelayedDeleteGateway(super.session);
final Completer<DeleteCollectionResponse> completion =
Completer<DeleteCollectionResponse>();
@@ -95,8 +89,7 @@ class DelayedDeleteGateway extends DeleteGateway {
}
class BlockingGateway extends SearchGateway {
- BlockingGateway()
- : super(MutableApiKeyProvider('fixture-blocking'), 'scope_blocking') {
+ BlockingGateway(UserSession session) : super(session, 'scope_blocking') {
version = 1;
}
@@ -117,17 +110,9 @@ class BlockingGateway extends SearchGateway {
return task;
}
- @override
- Future<IndexationSubmitResponse> createIndex(
- CancellationToken cancellation,
- ) async => IndexationSubmitResponse(const <String, Object?>{
- 'job_id': 'job-continues-remotely',
- 'status': 'queued',
- });
-
@override
Future<IndexationStatusResponse> indexStatus(
- String job,
+ SessionJob job,
CancellationToken cancellation,
) async {
indexStarted.complete();
@@ -151,6 +136,86 @@ class BlockingGateway extends SearchGateway {
}
void main() {
+ test(
+ 'same scope owners stay separate and narrowed policy refuses cached state',
+ () async {
+ final root = await Directory.systemTemp.createTemp('framebase_owner_');
+ addTearDown(() => root.delete(recursive: true));
+ final gateway = SearchGateway(await testSession(scopeId: 'same'), 'same');
+ addTearDown(gateway.close);
+ final c = ArchiveController(supportDirectory: root);
+ addTearDown(c.dispose);
+ Future<void> activate(String user, {String policy = 'p1'}) => c.activate(
+ 'same',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: 'service',
+ tenantId: 'tenant',
+ appUserId: user,
+ policyRevision: policy,
+ );
+ await activate('a/b');
+ final first = c.archiveDirectory!;
+ c.record('Private A', 'owner A history');
+ await c.save();
+ await activate('a_b');
+ expect(c.archiveDirectory, isNot(first));
+ expect(c.events, isEmpty);
+ await activate('a/b');
+ expect(c.events.single.title, 'Private A');
+ await activate('a/b', policy: 'narrowed');
+ expect(c.events, isEmpty);
+ },
+ );
+
+ test(
+ 'unknown legacy archives and restored outside paths are ignored',
+ () async {
+ final root = await Directory.systemTemp.createTemp('framebase_paths_');
+ addTearDown(() => root.delete(recursive: true));
+ final outside = File('${root.path}/outside.mp4')..writeAsBytesSync([1]);
+ final legacy = File('${root.path}/accounts/same/archive.json');
+ await legacy.parent.create(recursive: true);
+ await legacy.writeAsString(jsonEncode({'pendingJob': 'foreign-job'}));
+ final gateway = SearchGateway(await testSession(scopeId: 'same'), 'same');
+ addTearDown(gateway.close);
+ final c = ArchiveController(supportDirectory: root);
+ addTearDown(c.dispose);
+ Future<void> activate() => c.activate(
+ 'same',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: 'service',
+ tenantId: 'tenant',
+ appUserId: 'resolved-user',
+ policyRevision: 'p1',
+ );
+ await activate();
+ expect(c.pendingJob, isEmpty);
+ await Directory(c.archiveDirectory!).create(recursive: true);
+ c.clips = [
+ ArchiveClip(
+ id: 'foreign',
+ title: 'Foreign',
+ location: 'Test',
+ duration: 1,
+ asset: '',
+ poster: '',
+ path: outside.path,
+ bundled: false,
+ ),
+ ];
+ await c.save();
+ c.deactivate();
+ await activate();
+ expect(c.clips.any((clip) => clip.path == outside.path), isFalse);
+ expect(await outside.exists(), isTrue);
+ expect(await legacy.exists(), isTrue);
+ },
+ );
+
test(
'archive manifests and imported files stay with their account',
() async {
@@ -158,10 +223,20 @@ void main() {
addTearDown(() => root.delete(recursive: true));
const scopeA = 'scope_7K3A';
const scopeB = 'scope_B9Q2';
- final a = SearchGateway(MutableApiKeyProvider('fixture-a'), scopeA);
- final b = SearchGateway(MutableApiKeyProvider('fixture-b'), scopeB);
+ final a = SearchGateway(await testSession(scopeId: scopeA), scopeA);
+ final b = SearchGateway(await testSession(scopeId: scopeB), scopeB);
final c = ArchiveController(supportDirectory: root);
- await c.activate(scopeA, a, canRead: true, canWrite: true);
+ await c.activate(
+ scopeA,
+ a,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
+ final accountA = c.archiveDirectory!;
c.clips.first.uploaded = true;
c.pendingJob = 'alice-job';
c.record('Alice upload', 'done');
@@ -169,23 +244,42 @@ void main() {
await src.writeAsBytes([1, 2, 3]);
await c.importFile(src.path, 3);
await c.save();
- expect(c.clips.last.path, startsWith('${root.path}/accounts/$scopeA/'));
+ expect(c.clips.last.path, startsWith('$accountA/'));
c.deactivate();
expect(c.events, isEmpty);
expect(c.pendingJob, isEmpty);
- await c.activate(scopeB, b, canRead: true, canWrite: true);
+ await c.activate(
+ scopeB,
+ b,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
+ final accountB = c.archiveDirectory!;
expect(c.clips, hasLength(3));
expect(c.clips.first.uploaded, isFalse);
expect(c.pendingJob, isEmpty);
expect(c.events, isEmpty);
await c.importFile(src.path, 4);
- expect(c.clips.last.path, startsWith('${root.path}/accounts/$scopeB/'));
- await c.activate(scopeA, a, canRead: true, canWrite: true);
+ expect(c.clips.last.path, startsWith('$accountB/'));
+ await c.activate(
+ scopeA,
+ a,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
expect(c.clips, hasLength(4));
expect(c.clips.first.uploaded, isTrue);
expect(c.pendingJob, 'alice-job');
expect(c.events.any((e) => e.title == 'Alice upload'), isTrue);
- final manifest = File('${root.path}/accounts/$scopeA/archive.json');
+ final manifest = File('$accountA/archive.json');
final saved = await manifest.readAsString();
for (final forbidden in [
'fixture-a',
@@ -196,7 +290,7 @@ void main() {
]) {
expect(saved, isNot(contains(forbidden)));
}
- expect(await Directory('${root.path}/accounts/$scopeB').exists(), isTrue);
+ expect(await Directory(accountB).exists(), isTrue);
await a.close();
await b.close();
c.dispose();
@@ -210,14 +304,26 @@ void main() {
addTearDown(() => root.delete(recursive: true));
final source = File('${root.path}/camera.mp4')
..writeAsBytesSync([1, 2, 3]);
- final gateway = BlockingGateway();
+ final gateway = BlockingGateway(
+ await testSession(
+ scopeId: 'scope_blocking',
+ transport: QueueTransport([
+ {'job_id': 'job-continues-remotely', 'status': 'queued'},
+ ]),
+ ),
+ );
final c = ArchiveController(supportDirectory: root);
await c.activate(
'scope_blocking',
gateway,
canRead: true,
canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
);
+ await Directory(c.archiveDirectory!).create(recursive: true);
c.clips = [
ArchiveClip(
id: 'camera',
@@ -226,7 +332,7 @@ void main() {
duration: 1,
asset: '',
poster: '',
- path: source.path,
+ path: source.copySync('${c.archiveDirectory}/camera.mp4').path,
bundled: false,
),
];
@@ -266,9 +372,19 @@ void main() {
addTearDown(() => root.delete(recursive: true));
final source = File('${root.path}/camera.mp4');
await source.writeAsBytes([1, 2, 3]);
- final gateway = UploadGateway();
+ final gateway = UploadGateway(await testSession(scopeId: 'scope_upload'));
final controller = ArchiveController(supportDirectory: root);
- await controller.activate('alice', gateway, canRead: true, canWrite: true);
+ await controller.activate(
+ 'alice',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
+ await Directory(controller.archiveDirectory!).create(recursive: true);
controller.clips = <ArchiveClip>[
ArchiveClip(
id: 'camera',
@@ -277,7 +393,7 @@ void main() {
duration: 3,
asset: '',
poster: '',
- path: source.path,
+ path: source.copySync('${controller.archiveDirectory}/camera.mp4').path,
bundled: false,
),
];
@@ -285,7 +401,16 @@ void main() {
await controller.uploadAndIndex();
expect(controller.clips.single.remoteAssetId, 'asset-uploaded');
controller.deactivate();
- await controller.activate('alice', gateway, canRead: true, canWrite: true);
+ await controller.activate(
+ 'alice',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
final clip = controller.clips.single;
expect(clip.remoteAssetId, 'asset-uploaded');
expect(
@@ -332,11 +457,20 @@ void main() {
final root = await Directory.systemTemp.createTemp('framebase_remote_');
addTearDown(() => root.delete(recursive: true));
final gateway = SearchGateway(
- MutableApiKeyProvider('fixture-remote'),
+ await testSession(scopeId: 'scope_remote'),
'scope_remote',
);
final c = ArchiveController(supportDirectory: root);
- await c.activate('scope_remote', gateway, canRead: true, canWrite: true);
+ await c.activate(
+ 'scope_remote',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
c.clips = [
ArchiveClip(
id: 'remote',
@@ -363,7 +497,16 @@ void main() {
];
await c.save();
c.deactivate();
- await c.activate('scope_remote', gateway, canRead: true, canWrite: true);
+ await c.activate(
+ 'scope_remote',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
expect(c.clips, hasLength(1));
expect(c.clips.single.path, isNull);
expect(c.clips.single.remoteOnly, isTrue);
@@ -379,12 +522,21 @@ void main() {
final root = await Directory.systemTemp.createTemp('framebase_remove_');
addTearDown(() => root.delete(recursive: true));
final gateway = SearchGateway(
- MutableApiKeyProvider('fixture-remove'),
+ await testSession(scopeId: 'scope_remove'),
'scope_remove',
);
final c = ArchiveController(supportDirectory: root);
- await c.activate('scope_remove', gateway, canRead: true, canWrite: true);
- final account = Directory('${root.path}/accounts/scope_remove');
+ await c.activate(
+ 'scope_remove',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
+ final account = Directory('${c.archiveDirectory}');
await account.create(recursive: true);
final local = File('${account.path}/local.mp4')..writeAsBytesSync([1]);
final remote = File('${account.path}/remote.mp4')..writeAsBytesSync([2]);
@@ -424,10 +576,20 @@ void main() {
test('preview is non-mutating and commit keeps device videos', () async {
final root = await Directory.systemTemp.createTemp('framebase_delete_');
addTearDown(() => root.delete(recursive: true));
- final gateway = DeleteGateway()..version = 7;
+ final gateway = DeleteGateway(await testSession(scopeId: 'scope_delete'))
+ ..version = 7;
final c = ArchiveController(supportDirectory: root);
- await c.activate('scope_delete', gateway, canRead: true, canWrite: true);
- final account = Directory('${root.path}/accounts/scope_delete');
+ await c.activate(
+ 'scope_delete',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
+ final account = Directory('${c.archiveDirectory}');
await account.create(recursive: true);
final file = File('${account.path}/kept.mp4')..writeAsBytesSync([1, 2]);
ArchiveClip uploaded(String id, {String? path}) => ArchiveClip(
@@ -462,14 +624,23 @@ void main() {
await gateway.close();
});
- test('known late success reconciles only its captured scope', () async {
+ test('late cloud deletion cannot commit a retired archive writer', () async {
final root = await Directory.systemTemp.createTemp('framebase_late_');
addTearDown(() => root.delete(recursive: true));
- final a = DelayedDeleteGateway();
- final b = SearchGateway(MutableApiKeyProvider('fixture-b'), 'scope_b');
+ final a = DelayedDeleteGateway(await testSession(scopeId: 'scope_delete'));
+ final b = SearchGateway(await testSession(scopeId: 'scope_b'), 'scope_b');
final c = ArchiveController(supportDirectory: root);
- await c.activate('scope_delete', a, canRead: true, canWrite: true);
- final account = Directory('${root.path}/accounts/scope_delete');
+ await c.activate(
+ 'scope_delete',
+ a,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
+ final account = Directory('${c.archiveDirectory}');
await account.create(recursive: true);
final file = File('${account.path}/kept.mp4')..writeAsBytesSync([1]);
c.clips = [
@@ -489,7 +660,16 @@ void main() {
await c.save();
final deletion = c.deleteCloudLibrary();
await Future<void>.delayed(Duration.zero);
- await c.activate('scope_b', b, canRead: true, canWrite: true);
+ await c.activate(
+ 'scope_b',
+ b,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
expect(c.clips, hasLength(3));
a.completion.complete(
DeleteCollectionResponse(const {
@@ -499,14 +679,23 @@ void main() {
'scope': 'all',
}),
);
- expect(await deletion, CloudDeletionResult.deleted);
+ expect(await deletion, CloudDeletionResult.failed);
expect(c.clips, hasLength(3));
expect(c.clips.any((item) => item.id == 'kept'), isFalse);
- await c.activate('scope_delete', a, canRead: true, canWrite: true);
+ await c.activate(
+ 'scope_delete',
+ a,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
expect(c.clips.single.id, 'kept');
- expect(c.clips.single.uploaded, isFalse);
- expect(c.clips.single.remoteAssetId, isNull);
+ expect(c.clips.single.uploaded, isTrue);
+ expect(c.clips.single.remoteAssetId, 'asset-kept');
expect(await file.exists(), isTrue);
c.dispose();
await a.close();
@@ -517,10 +706,20 @@ void main() {
final root = await Directory.systemTemp.createTemp('framebase_fail_');
addTearDown(() => root.delete(recursive: true));
final gateway = DeleteGateway(
+ await testSession(scopeId: 'scope_delete'),
deleteError: const ApiException('active', statusCode: 409),
);
final c = ArchiveController(supportDirectory: root);
- await c.activate('scope_delete', gateway, canRead: true, canWrite: true);
+ await c.activate(
+ 'scope_delete',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: "fixture-service",
+ tenantId: "fixture-tenant",
+ appUserId: "fixture-user",
+ policyRevision: "fixture-policy",
+ );
c.clips = [
ArchiveClip(
id: 'remote',
diff --git a/example/05_framebase_userlogin/test/search_gateway_test.dart b/example/05_framebase_userlogin/test/search_gateway_test.dart
index 21b8afd..a2a4891 100644
--- a/example/05_framebase_userlogin/test/search_gateway_test.dart
+++ b/example/05_framebase_userlogin/test/search_gateway_test.dart
@@ -1,425 +1,319 @@
+import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:framebase/data/search_gateway.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+import 'session_fixture.dart';
const accountScope = 'scope_7K3A';
-SearchGateway testGateway(QueueTransport transport) => SearchGateway(
- MutableApiKeyProvider('test-only-placeholder'),
+Future<SearchGateway> testGateway(
+ QueueTransport transport, {
+ bool collectionWide = true,
+}) async => SearchGateway(
+ await testSession(transport: transport, collectionWide: collectionWide),
accountScope,
- transport: transport,
);
-String requestText(VmodalRequest request) =>
- '${request.uri} ${request.jsonBody ?? ''}';
-
-class QueueTransport implements VmodalTransport {
- QueueTransport(this.responses);
- final List<Map<String, Object?>> responses;
- final List<VmodalRequest> requests = [];
- bool closed = false;
+class DelayedTransport extends QueueTransport {
+ final response = Completer<VmodalResponse>();
@override
- Future<VmodalResponse> send(VmodalRequest request) async {
- request.cancellation.throwIfCanceled();
+ Future<VmodalResponse> send(VmodalRequest request) {
requests.add(request);
- final data = responses.removeAt(0);
- return VmodalResponse(
- statusCode: data['__status'] as int? ?? 200,
- body: Stream.value(utf8.encode(jsonEncode(data))),
- );
+ return response.future;
}
+}
+class ByteTransport extends QueueTransport {
+ ByteTransport(super.responses);
@override
- Future<void> close() async {
- closed = true;
+ Future<VmodalResponse> send(VmodalRequest request) {
+ if (request.uri.path.endsWith('/image/get_image')) {
+ requests.add(request);
+ return Future.value(
+ VmodalResponse(statusCode: 200, body: Stream.value([1, 2, 3])),
+ );
+ }
+ return super.send(request);
}
}
void main() {
test(
- 'connect resolves the account and discovers the current index',
+ 'explicit collection-wide grant previews then commits exact opaque collection',
() async {
final transport = QueueTransport([
- {'user_id': 'account-1'},
{
- 'total': 1,
- 'data': [
- {
- 'mode': 'vid_file',
- 'group_name': accountScope,
- 'lancedb_versions': ['v2', 'v4'],
- },
- ],
+ 'status': 'dry_run',
+ 'group_name': accountScope,
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ },
+ {
+ 'status': 'ok',
+ 'group_name': accountScope,
+ 'mode': 'vid_file',
+ 'scope': 'all',
},
- {'data': [], 'total': 0},
]);
- final gateway = testGateway(transport);
+ final gateway = await testGateway(transport);
+ await gateway.previewLibraryDeletion(CancellationToken());
+ await gateway.deleteLibrary(CancellationToken());
+ expect(transport.requests.map((r) => r.method), ['DELETE', 'DELETE']);
+ expect(transport.requests.first.jsonBody, {
+ 'group_name': accountScope,
+ 'mode': 'vid_file',
+ 'scope': 'all',
+ 'dry_run': true,
+ 'confirm': false,
+ });
+ expect((transport.requests.last.jsonBody as Map)['confirm'], isTrue);
+ await gateway.close();
+ },
+ );
- await gateway.connect('account-1');
+ test('forbidden deletion reports host denial once without replay', () async {
+ final transport = QueueTransport([
+ {'__status': 403, 'detail': 'private-body'},
+ ]);
+ final gateway = await testGateway(transport);
+ final failures = <int>[];
+ gateway.onAccessFailure = failures.add;
+ await expectLater(
+ gateway.deleteLibrary(CancellationToken()),
+ throwsA(isA<ApiException>()),
+ );
+ expect(failures, [403]);
+ expect(transport.requests, hasLength(1));
+ await gateway.close();
+ });
- expect(gateway.accountId, 'account-1');
- expect(gateway.collection, accountScope);
- expect(gateway.version, 4);
- expect(transport.requests, hasLength(3));
+ test(
+ 'upload preparation keeps exact scoped selectors and does not expose signed credentials',
+ () async {
+ final root = await Directory.systemTemp.createTemp('scoped_upload_');
+ addTearDown(() => root.delete(recursive: true));
+ final file = File('${root.path}/clip.mp4');
+ await file.writeAsBytes([1, 2, 3]);
+ final transport = QueueTransport([
+ {'url': ''},
+ ]);
+ final gateway = await testGateway(transport);
+ final task = await gateway.upload(file);
+ await expectLater(task.result, throwsA(isA<SdkException>()));
+ expect(transport.requests, hasLength(1));
expect(
- transport.requests.last.uri.queryParameters['group_name'],
+ transport.requests.single.uri.queryParameters['group_name'],
accountScope,
);
expect(
- transport.requests.map(requestText).join(' '),
- isNot(contains('framebase_streets__user_')),
+ transport.requests.single.uri.queryParameters['stream_name'],
+ archiveStream,
);
await gateway.close();
},
);
-
test(
- 'bulk frames retain search order and tolerate partial missing images',
+ 'safe media bytes preserve frame order offsets and placeholders without exposing URLs',
() async {
- const route = '/api/external/v1/image/get_image';
- final transport = QueueTransport([
+ const signed = 'https://images.test/private-capability';
+ final transport = ByteTransport([
{
'data': [
- {'title': 'first', 'ts_unix': '0000000006000', 'score': .71},
- {'title': 'second', 'ts_unix': '0000000008000', 'score': .76},
- {'title': 'missing', 'ts_unix': '0000000010000', 'score': .80},
- ],
- 'cnt_total': 3,
- 'execution_time_ms': 42.5,
- },
- {
- 'records': [
- {
- 'input_index': 1.0,
- 'found': true,
- 'url_pre_signed': '$route?test=second',
- },
- {
- 'input_index': '0',
- 'found': true,
- 'url_pre_signed': '$route?test=first',
- },
- {'input_index': 2, 'found': false},
- {
- 'input_index': -1,
- 'found': true,
- 'url_pre_signed': 'http://invalid.test',
- },
- ],
- },
- {
- 'records': [
{
- 'url_pre_signed': '$route?test=first',
- 'content_base64': base64Encode([1, 2, 3]),
+ 'asset_id': 'asset-first',
+ 'file_name': 'first.mp4',
+ 'distance': .4,
+ 'playback_offset_ms': 35000,
+ 'preview_image_url': signed,
},
{
- 'url_pre_signed': '$route?test=second',
- 'content_base64': base64Encode([4, 5, 6]),
+ 'asset_id': 'asset-missing',
+ 'file_name': 'missing.mp4',
+ 'distance': .5,
+ 'ts_unix': '1788510000000',
},
],
},
+ {'found': true, 'url_pre_signed': signed},
+ {'found': false},
]);
- final gateway = testGateway(transport);
- gateway.version = 2;
- final result = await gateway.search('crosswalk', maxDistance: .85);
- expect(result.matches.map((m) => m.fileName), [
- 'first',
- 'second',
- 'missing',
+ final gateway = await testGateway(transport);
+ final batch = await gateway.search('street');
+ expect(batch.matches.map((m) => m.assetId), [
+ 'asset-first',
+ 'asset-missing',
]);
- expect(result.matches[0].imageBytes, [1, 2, 3]);
- expect(result.matches[1].imageBytes, [4, 5, 6]);
- expect(result.matches[2].imageBytes, isNull);
- expect(result.matches[0].imageUrl, isNull);
- expect(result.matches[0].seconds, 6);
- expect(result.serverMs, 42.5);
- final body = transport.requests.first.jsonBody as Map;
- expect(body['group_name'], accountScope);
- expect(body['stream_name'], archiveStream);
- expect(body['image_emb_score_min'], .85);
- expect(transport.requests[1].jsonBody.toString(), contains(accountScope));
+ expect(batch.matches.first.imageBytes, [1, 2, 3]);
+ expect(batch.matches.first.seconds, 35);
+ expect(batch.matches.last.seconds, isNull);
+ expect(batch.matches.last.imageBytes, isNull);
+ expect(batch.matches.every((m) => m.imageUrl == null), isTrue);
+ expect(batch.matches.first.hit.raw.toString(), isNot(contains(signed)));
+ expect(transport.requests, hasLength(3));
+ expect(
+ (transport.requests[1].jsonBody as Map)['ts_unix_13digits'],
+ '0000000035000',
+ );
expect(
transport.requests[1].jsonBody.toString(),
- contains(archiveStream),
+ isNot(contains('1788510000000')),
);
await gateway.close();
- expect(transport.closed, isTrue);
- expect(() => gateway.keys.current(), throwsA(isA<AuthException>()));
},
);
-
test(
- 'typed previews skip resolution and canonical offsets drive selectors',
+ 'tenant principal verification preserves app-user identity and opaque scope',
() async {
- const route = '/api/external/v1/image/get_image';
- const direct = 'https://images.test/direct.jpg';
final transport = QueueTransport([
+ {'user_id': 'shared-principal'},
{
'data': [
{
- 'asset_id': 'asset-direct',
- 'file_name': 'direct.mp4',
- 'playback_offset_ms': 12000,
- 'distance': .4,
- 'preview_image_url': direct,
- },
- {
- 'asset_id': 'asset-offset',
- 'file_name': 'offset.mp4',
- 'playback_offset_ms': 35000,
- 'distance': .5,
- },
- {
- 'asset_id': 'asset-epoch',
- 'file_name': 'epoch.mp4',
- 'ts_unix': '1788510000000',
- 'distance': .6,
- },
- ],
- 'cnt_total': 3,
- },
- {
- 'records': [
- {
- 'input_index': 0,
- 'found': true,
- 'url_pre_signed': '$route?test=offset',
- },
- {'input_index': 1, 'found': false},
- ],
- },
- {
- 'records': [
- {
- 'url_pre_signed': direct,
- 'content_base64': base64Encode([1]),
- },
- {
- 'url_pre_signed': '$route?test=offset',
- 'content_base64': base64Encode([2]),
+ 'mode': 'vid_file',
+ 'group_name': accountScope,
+ 'lancedb_versions': ['v2', 'v4'],
},
],
},
+ {'data': []},
]);
- final gateway = testGateway(transport);
- final result = await gateway.search('street', maxDistance: .85);
-
- expect(result.matches.map((match) => match.assetId), [
- 'asset-direct',
- 'asset-offset',
- 'asset-epoch',
- ]);
- expect(result.matches[0].imageUrl, direct);
- expect(result.matches[0].imageBytes, [1]);
- expect(result.matches[1].seconds, 35);
- expect(result.matches[1].imageBytes, [2]);
- expect(result.matches[2].seconds, isNull);
- expect(transport.requests, hasLength(3));
- final lookup = transport.requests[1].jsonBody as Map;
- final records = lookup['records'] as List;
- expect(records, hasLength(2));
- expect(records.toString(), isNot(contains('direct.mp4')));
- expect((records[0] as Map)['ts_unix_13digits'], '0000000035000');
- expect(records[1] as Map, isNot(contains('ts_unix_13digits')));
+ final gateway = await testGateway(transport);
+ await gateway.connect('shared-principal');
+ expect(gateway.accountId, 'alice');
+ expect(gateway.context.tenantId, 'shared-tenant');
+ expect(gateway.version, 4);
+ expect(
+ transport.requests.last.uri.queryParameters['group_name'],
+ accountScope,
+ );
+ expect(
+ transport.requests.every((r) => !r.headers.containsKey('X-User-Id')),
+ isTrue,
+ );
await gateway.close();
},
);
- test('empty search does not request invented images', () async {
- final transport = QueueTransport([
- {'data': [], 'cnt_total': 0},
- ]);
- final gateway = testGateway(transport);
- final result = await gateway.search('a dog on a beach');
- expect(result.matches, isEmpty);
- expect(transport.requests, hasLength(1));
- await gateway.close();
- });
-
test(
- 'client cutoff rejects out-of-threshold beta results before downloading',
+ 'safe search rows omit tenant data and signed image capabilities',
() async {
final transport = QueueTransport([
{
'data': [
- {'title': 'street', 'score': .926, 'ts_unix': '0000000006000'},
+ {'file_name': 'first.mp4', 'distance': .4},
+ {
+ 'file_name': 'foreign.mp4',
+ 'group_name': 'scope_bob',
+ 'distance': .4,
+ },
+ {'file_name': 'far.mp4', 'distance': 1.2},
],
- 'cnt_total': 1,
+ 'cnt_total': 900,
+ 'execution_time_ms': 42.5,
},
+ {'records': []},
]);
- final gateway = testGateway(transport);
- final result = await gateway.search('a dog on a beach', maxDistance: .85);
- expect(result.matches, isEmpty);
- expect(result.total, 1); // Raw server count is not rewritten.
- expect(transport.requests, hasLength(1));
- await gateway.close();
- },
- );
-
- test('canceled search never reaches transport', () async {
- final transport = QueueTransport([]);
- final gateway = testGateway(transport);
- final token = CancellationToken()..cancel();
- await expectLater(
- gateway.search('bus', cancellation: token),
- throwsA(isA<OperationCanceled>()),
- );
- expect(transport.requests, isEmpty);
- await gateway.close();
- });
-
- test(
- 'index creation uses the user scope and status uses returned ID',
- () async {
- final transport = QueueTransport([
- {'job_id': 'job-123', 'status': 'queued'},
- {'job_id': 'job-123', 'status': 'success'},
- ]);
- final gateway = testGateway(transport);
- final token = CancellationToken();
- final job = await gateway.createIndex(token);
- final status = await gateway.indexStatus(job.jobId, token);
- expect(job.jobId, 'job-123');
- expect(status.status, 'success');
+ final gateway = await testGateway(transport);
+ final batch = await gateway.search('crosswalk', maxDistance: .85);
+ expect(batch.matches.map((m) => m.fileName), ['first.mp4']);
+ expect(batch.total, 1);
+ expect(batch.matches.single.imageUrl, isNull);
+ // Restricted responses omit timing/count fields for broader tenant work.
+ expect(batch.serverMs, 0);
final body = transport.requests.first.jsonBody as Map;
expect(body['group_name'], accountScope);
expect(body['stream_name'], archiveStream);
- expect(transport.requests.last.uri.path, contains('job-123'));
await gateway.close();
},
);
- test('upload signed request uses the exact immutable scope', () async {
- final root = await Directory.systemTemp.createTemp('scope_upload_');
- addTearDown(() => root.delete(recursive: true));
- final file = File('${root.path}/clip.mp4');
- await file.writeAsBytes([1, 2, 3]);
+ test('empty and canceled searches do not invent media or dispatch', () async {
final transport = QueueTransport([
- {'url': ''},
+ {'data': []},
]);
- final gateway = testGateway(transport);
- final task = await gateway.upload(file);
- await expectLater(task.result, throwsA(isA<ValidationException>()));
- expect(transport.requests, hasLength(1));
- expect(
- transport.requests.single.uri.queryParameters['group_name'],
- accountScope,
- );
- expect(
- requestText(transport.requests.single),
- isNot(contains('framebase_streets__user_')),
+ final gateway = await testGateway(transport);
+ expect((await gateway.search('bus')).matches, isEmpty);
+ await expectLater(
+ gateway.search('bus', cancellation: CancellationToken()..cancel()),
+ throwsA(isA<OperationCanceled>()),
);
- expect(gateway.collection, accountScope);
- await gateway.close();
- });
-
- test('401 reports auth failure without replaying the search', () async {
- final transport = QueueTransport([
- {'__status': 401, 'detail': 'expired'},
- ]);
- final gateway = testGateway(transport);
- var status = 0;
- gateway.onAccessFailure = (value) => status = value;
- await expectLater(gateway.search('bus'), throwsA(isA<AuthException>()));
- expect(status, 401);
- expect(transport.requests, hasLength(1));
- await gateway.close();
- });
-
- test('403 reports forbidden failure without replaying the search', () async {
- final transport = QueueTransport([
- {'__status': 403, 'detail': 'forbidden'},
- ]);
- final gateway = testGateway(transport);
- var status = 0;
- gateway.onAccessFailure = (value) => status = value;
- await expectLater(gateway.search('bus'), throwsA(isA<ApiException>()));
- expect(status, 403);
expect(transport.requests, hasLength(1));
await gateway.close();
+ await expectLater(gateway.search('bus'), throwsA(isA<OperationCanceled>()));
});
test(
- 'cloud deletion preview and commit use the exact issued scope',
+ 'index status accepts minted provenance and rejects another session job',
() async {
- final transport = QueueTransport([
- {
- 'status': 'dry_run',
- 'group_name': accountScope,
- 'mode': 'vid_file',
- 'scope': 'all',
- },
- {
- 'status': 'ok',
- 'group_name': accountScope,
- 'mode': 'vid_file',
- 'scope': 'all',
- },
+ final aTransport = QueueTransport([
+ {'job_id': 'job-a', 'status': 'queued'},
+ {'job_id': 'job-a', 'status': 'success'},
]);
- final gateway = testGateway(transport);
-
- await gateway.previewLibraryDeletion(CancellationToken());
- await gateway.deleteLibrary(CancellationToken());
-
- expect(transport.requests, hasLength(2));
- expect(
- transport.requests.map((request) => request.method),
- everyElement('DELETE'),
- );
- expect(
- transport.requests.map((request) => request.uri.path),
- everyElement(endsWith('/api/external/v1/collection/delete')),
- );
- expect(transport.requests.first.jsonBody, {
- 'group_name': accountScope,
- 'mode': 'vid_file',
- 'scope': 'all',
- 'dry_run': true,
- 'confirm': false,
- });
- expect(transport.requests.last.jsonBody, {
- 'group_name': accountScope,
- 'mode': 'vid_file',
- 'scope': 'all',
- 'dry_run': false,
- 'confirm': true,
- });
- expect(requestText(transport.requests.last), isNot(contains('asset_id')));
- expect(
- requestText(transport.requests.last),
- isNot(contains('stream_name')),
+ final a = await testGateway(aTransport);
+ final bTransport = QueueTransport();
+ final b = await testGateway(bTransport);
+ final job = await a.createIndex(CancellationToken());
+ expect((await a.indexStatus(job, CancellationToken())).status, 'success');
+ await expectLater(
+ b.indexStatus(job, CancellationToken()),
+ throwsA(isA<ValidationException>()),
);
- await gateway.close();
+ expect(bTransport.requests, isEmpty);
+ await a.close();
+ await b.close();
},
);
+ test('one-stream grant cannot delete the whole collection', () async {
+ final transport = QueueTransport();
+ final gateway = await testGateway(transport, collectionWide: false);
+ await expectLater(
+ gateway.deleteLibrary(CancellationToken()),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(transport.requests, isEmpty);
+ await gateway.close();
+ });
+
test(
- 'cloud deletion is not replayed and honors pre-send cancellation',
+ 'account switch closes retained gateway and drops ignored-cancel payload',
() async {
- final canceledTransport = QueueTransport([]);
- final canceledGateway = testGateway(canceledTransport);
- final canceled = CancellationToken()..cancel();
- await expectLater(
- canceledGateway.deleteLibrary(canceled),
+ final transport = DelayedTransport();
+ final gateway = await testGateway(transport);
+ final pending = expectLater(
+ gateway.search('bus'),
throwsA(isA<OperationCanceled>()),
);
- expect(canceledTransport.requests, isEmpty);
- await canceledGateway.close();
-
- for (final status in [409, 500]) {
- final transport = QueueTransport([
- {'__status': status, 'detail': 'failure'},
- ]);
- final gateway = testGateway(transport);
- await expectLater(
- gateway.deleteLibrary(CancellationToken()),
- throwsA(isA<SdkException>()),
- );
- expect(transport.requests, hasLength(1));
- await gateway.close();
- }
+ await Future<void>.delayed(Duration.zero);
+ await gateway.close();
+ await pending;
+ transport.response.complete(
+ VmodalResponse(
+ statusCode: 200,
+ body: Stream.value(
+ utf8.encode(
+ jsonEncode({
+ 'data': [
+ {'file_name': 'private-a'},
+ ],
+ }),
+ ),
+ ),
+ ),
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(transport.closed, isTrue);
},
);
+
+ test('stale errors cannot notify the active host', () async {
+ final gateway = await testGateway(QueueTransport());
+ var reports = 0;
+ gateway.onAccessFailure = (_) => reports++;
+ await gateway.close();
+ gateway.reportFailure(const AuthException('expired'));
+ gateway.reportFailure(const ApiException('forbidden', statusCode: 403));
+ expect(reports, 0);
+ });
}
diff --git a/example/05_framebase_userlogin/test/session_fixture.dart b/example/05_framebase_userlogin/test/session_fixture.dart
new file mode 100644
index 0000000..d709b49
--- /dev/null
+++ b/example/05_framebase_userlogin/test/session_fixture.dart
@@ -0,0 +1,65 @@
+import 'dart:convert';
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+import 'package:framebase/data/search_gateway.dart';
+
+class QueueTransport implements VmodalTransport {
+ QueueTransport([List<Map<String, Object?>>? responses])
+ : responses = responses ?? [];
+ final List<Map<String, Object?>> responses;
+ final List<VmodalRequest> requests = [];
+ bool closed = false;
+ @override
+ Future<VmodalResponse> send(VmodalRequest request) async {
+ request.cancellation.throwIfCanceled();
+ requests.add(request);
+ final data = responses.isNotEmpty
+ ? responses.removeAt(0)
+ : <String, Object?>{
+ 'user_id': 'shared-principal',
+ 'data': <Object?>[],
+ 'job_id': 'job-ready',
+ 'status': 'queued',
+ };
+ return VmodalResponse(
+ statusCode: data['__status'] as int? ?? 200,
+ body: Stream.value(utf8.encode(jsonEncode(data))),
+ );
+ }
+
+ @override
+ Future<void> close() async {
+ closed = true;
+ }
+}
+
+Future<UserSession> testSession({
+ String scopeId = 'scope_7K3A',
+ String appUserId = 'alice',
+ VmodalTransport? transport,
+ bool collectionWide = true,
+}) async {
+ final config = SdkConfig(maxRetries: 0);
+ final source = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'shared-tenant',
+ expectedPrincipal: 'shared-principal',
+ initialKey: 'same-key',
+ );
+ final manager = UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: (_) => transport ?? QueueTransport(),
+ );
+ return manager.openUserSession(
+ tenantId: 'shared-tenant',
+ appUserId: appUserId,
+ allowedContentMapping: [
+ ContentMapping.opaque(
+ collectionId: scopeId,
+ streamName: archiveStream,
+ actions: UserAction.values.toSet(),
+ collectionWide: collectionWide,
+ ),
+ ],
+ );
+}
diff --git a/example/05_framebase_userlogin/test/user_session_controller_test.dart b/example/05_framebase_userlogin/test/user_session_controller_test.dart
index 5fe551d..da6136e 100644
--- a/example/05_framebase_userlogin/test/user_session_controller_test.dart
+++ b/example/05_framebase_userlogin/test/user_session_controller_test.dart
@@ -1,90 +1,20 @@
import 'dart:async';
import 'dart:io';
-
import 'package:flutter_test/flutter_test.dart';
import 'package:framebase/data/archive_controller.dart';
-import 'package:framebase/data/search_gateway.dart';
import 'package:framebase/user/auth_adapter.dart';
import 'package:framebase/user/mock_firebase_auth.dart';
import 'package:framebase/user/user_session_controller.dart';
import 'package:framebase/user/vmodal_credential.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
-
-class SessionGateway extends SearchGateway {
- SessionGateway(super.keys, super.scopeId, this.owner, [this.connectError]);
- final String owner;
- final Object? connectError;
- int destructiveCalls = 0;
- @override
- Future<void> connect(String expectedUserId) async {
- if (connectError case final Object error) throw error;
- if (expectedUserId != owner) throw const AuthException('Wrong owner');
- accountId = owner;
- }
-
- @override
- Future<DeleteCollectionResponse> previewLibraryDeletion(
- CancellationToken cancellation,
- ) async {
- destructiveCalls++;
- return DeleteCollectionResponse(const {'status': 'dry_run'});
- }
-
- @override
- Future<DeleteCollectionResponse> deleteLibrary(
- CancellationToken cancellation,
- ) async {
- destructiveCalls++;
- return DeleteCollectionResponse(const {'status': 'ok'});
- }
-}
-
-class TrackingArchive extends ArchiveController {
- TrackingArchive({required Directory supportDirectory})
- : super(persist: false, supportDirectory: supportDirectory);
- String activatedScope = '';
- int activations = 0;
-
- @override
- Future<void> activate(
- String scopeId,
- SearchGateway gateway, {
- required bool canRead,
- required bool canWrite,
- }) async {
- activatedScope = scopeId;
- activations++;
- await super.activate(
- scopeId,
- gateway,
- canRead: canRead,
- canWrite: canWrite,
- );
- }
-}
-
-class TokenAuth extends MockFirebaseAuth {
- TokenAuth(this.tokens);
- final List<Object> tokens;
-
- @override
- Future<String?> idToken(AppUser user) async {
- final item = tokens.removeAt(0);
- if (item is String) return item;
- if (item is Future<String?>) return item;
- throw item;
- }
-}
+import 'session_fixture.dart';
class QueueCredentials implements VmodalCredentialSource {
QueueCredentials(this.items);
final List<Object> items;
int calls = 0;
@override
- Future<VmodalCredential> acquire(
- AppUser user,
- String? firebaseIdToken,
- ) async {
+ Future<VmodalCredential> acquire(AppUser user, String? token) async {
calls++;
final item = items.removeAt(0);
if (item is VmodalCredential) return item;
@@ -96,849 +26,369 @@ class QueueCredentials implements VmodalCredentialSource {
VmodalCredential credential(
String uid,
DateTime expiry, {
- int? version = 1,
- String? sessionId,
- DateTime? issuedAt,
- String? token,
- String? owner,
+ String token = 'same-key',
String? scope,
- bool allowed = true,
Set<String> grants = const {'library:read', 'library:write'},
+ String? tenantId = 'same-tenant',
+ bool collectionWide = false,
}) => VmodalCredential(
- contractVersion: version,
- sessionId: sessionId ?? 'session-$uid',
- issuedAt: issuedAt ?? expiry.subtract(const Duration(minutes: 5)),
- apiToken: token ?? 'placeholder-$uid',
+ contractVersion: 1,
+ sessionId: 'issuer-$uid',
+ issuedAt: expiry.subtract(const Duration(minutes: 5)),
+ apiToken: token,
expiresAt: expiry,
firebaseUid: uid,
- vmodalUserId: owner ?? 'vm-$uid',
+ vmodalUserId: 'shared-principal',
+ tenantId: tenantId,
scopeId: scope ?? 'scope_$uid',
- allowed: allowed,
+ allowed: true,
permissions: grants,
+ collectionWide: collectionWide,
);
-Future<void> settle() => Future<void>.delayed(const Duration(milliseconds: 20));
+Future<void> settle() =>
+ Future<void>.delayed(const Duration(milliseconds: 100));
void main() {
- test('credential parses scope and rejects invalid contracts or grants', () {
- final now = DateTime.utc(2030);
- const user = AppUser('alice');
- final valid = <String, Object?>{
- 'version': 1,
- 'session_id': 'issuer-session-7K3A',
- 'issued_at': '2030-01-01T00:00:00+00:00',
- 'api_token': 'token',
- 'expires_at': '2030-01-01T01:00:00Z',
- 'firebase_uid': 'alice',
- 'vmodal_user_id': 'vm-alice',
- 'scope_id': 'scope_7K3A',
- 'allowed': true,
- 'permissions': ['library:read'],
- };
- final parsed = VmodalCredential.fromJson(valid);
- expect(parsed.contractVersion, 1);
- expect(parsed.sessionId, 'issuer-session-7K3A');
- expect(parsed.issuedAt, DateTime.utc(2030));
- expect(parsed.expiresAt, DateTime.utc(2030, 1, 1, 1));
- expect(parsed.scopeId, 'scope_7K3A');
- expect(() => parsed.validate(user, now), returnsNormally);
-
- for (final invalid in <Map<String, Object?>>[
- Map<String, Object?>.from(valid)..remove('version'),
- {...valid, 'version': 2},
- {...valid, 'session_id': ' '},
- Map<String, Object?>.from(valid)..remove('issued_at'),
- {...valid, 'issued_at': 'not-a-date'},
- {...valid, 'issued_at': valid['expires_at']},
- {...valid, 'issued_at': '2030-01-01T02:00:00Z'},
- ]) {
- expect(
- () => VmodalCredential.fromJson(invalid).validate(user, now),
- throwsA(isA<CredentialContractError>()),
- );
- }
- expect(
- () => credential('alice', now).validate(user, now),
- throwsA(isA<CredentialContractError>()),
- );
- expect(
- () => credential(
- 'bob',
- now.add(const Duration(hours: 1)),
- ).validate(user, now),
- throwsA(isA<CredentialContractError>()),
- );
- expect(
- () => credential(
- 'alice',
- now.add(const Duration(hours: 1)),
- grants: {'library:write'},
- ).validate(user, now),
- throwsA(isA<CredentialDenied>()),
- );
- expect(
- () => credential(
- 'alice',
- now.add(const Duration(hours: 1)),
- allowed: false,
- ).validate(user, now),
- throwsA(isA<CredentialDenied>()),
- );
- expect(
- () => credential(
- 'alice',
- now.add(const Duration(hours: 1)),
- scope: 'invalid-scope',
- ).validate(user, now),
- throwsA(isA<CredentialContractError>()),
- );
- final prior = credential(
- 'alice',
- now.add(const Duration(hours: 1)),
- scope: 'scope_original',
- );
- expect(
- () => credential(
- 'alice',
- now.add(const Duration(hours: 1)),
- scope: 'scope_changed',
- ).validate(user, now, previous: prior),
- throwsA(isA<CredentialContractError>()),
- );
- expect(
- () => credential(
- 'alice',
- now.add(const Duration(hours: 1)),
- sessionId: 'rotated-session',
- scope: 'scope_original',
- ).validate(user, now, previous: prior),
- returnsNormally,
- );
- });
-
- test('initial resolve passes the issuer scope unchanged', () async {
- final now = DateTime.utc(2030);
- final root = await Directory.systemTemp.createTemp('scope_session_');
- addTearDown(() => root.delete(recursive: true));
- final archive = TrackingArchive(supportDirectory: root);
- final auth = MockFirebaseAuth();
- final source = QueueCredentials([
- Future.value(
- credential(
- 'alice',
- now.add(const Duration(hours: 1)),
- scope: 'scope_7K3A',
- ),
- ),
- ]);
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: archive,
- clock: () => now,
- gatewayFactory: (key, scope, fresh) =>
- SessionGateway(key, scope, 'vm-alice'),
- );
- await settle();
- auth.setUser(const AppUser('alice'));
- await settle();
- expect(session.state, SessionState.ready);
- expect(session.gateway?.collection, 'scope_7K3A');
- expect(archive.activatedScope, 'scope_7K3A');
- session.dispose();
- archive.dispose();
- });
- test('empty default and denied credential issue no gateway calls', () async {
- final archive = ArchiveController(
- persist: false,
- supportDirectory: Directory.systemTemp,
- );
- final auth = MockFirebaseAuth();
- final source = MockVmodalCredentialSource();
- var gateways = 0;
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: archive,
- gatewayFactory: (key, id, fresh) {
- gateways++;
- return SessionGateway(key, id, 'vm-alice');
- },
- );
- expect(session.state, SessionState.loading);
- await settle();
- expect(session.state, SessionState.signedOut);
- expect(source.calls, 0);
- auth.setUser(const AppUser('alice'));
- await settle();
- expect(session.state, SessionState.denied);
- expect(gateways, 0);
- expect(archive.connected, isFalse);
- session.dispose();
- archive.dispose();
- });
-
- test('owner mismatch and missing read grant fail closed', () async {
- final now = DateTime.utc(2030);
- for (final grants in [
- <String>{'library:write'},
- <String>{'library:read'},
- ]) {
+ test(
+ 'read-only issuer grant connects and searches without index write privileges',
+ () async {
+ final now = DateTime.utc(2030);
+ final auth = MockFirebaseAuth();
final archive = ArchiveController(
persist: false,
supportDirectory: Directory.systemTemp,
);
- final auth = MockFirebaseAuth();
- final source = QueueCredentials([
- Future.value(
+ final transport = QueueTransport();
+ final controller = UserSessionController(
+ auth: auth,
+ credentials: QueueCredentials([
credential(
'alice',
now.add(const Duration(hours: 1)),
- grants: grants,
+ grants: {'library:read'},
),
- ),
- ]);
- final session = UserSessionController(
- auth: auth,
- credentials: source,
+ ]),
archive: archive,
clock: () => now,
- gatewayFactory: (key, id, fresh) =>
- SessionGateway(key, id, 'different'),
+ transportFactory: (_) => transport,
);
await settle();
auth.setUser(const AppUser('alice'));
await settle();
- expect(
- session.state,
- grants.contains('library:read')
- ? SessionState.error
- : SessionState.denied,
- );
- expect(archive.connected, isFalse);
- session.dispose();
+ expect(controller.state, SessionState.ready);
+ expect(controller.canRead, isTrue);
+ expect(controller.canWrite, isFalse);
+ expect(transport.requests, hasLength(2));
+ final batch = await controller.gateway!.search('bus');
+ expect(batch.matches, isEmpty);
+ controller.dispose();
archive.dispose();
- }
- });
-
+ },
+ );
test(
- 'refresh is single flight, rotates key, and failure clears it',
+ 'archive teardown listener can activate B without old logout clearing B',
() async {
- var now = DateTime.utc(2030);
- final pending = Completer<VmodalCredential>();
- final failed = Completer<VmodalCredential>();
- final source = QueueCredentials([
- Future.value(credential('alice', now.add(const Duration(minutes: 2)))),
- pending.future,
- failed.future,
- ]);
+ final now = DateTime.utc(2030);
+ final auth = MockFirebaseAuth();
final archive = ArchiveController(
persist: false,
supportDirectory: Directory.systemTemp,
);
- final auth = MockFirebaseAuth();
- final session = UserSessionController(
+ final controller = UserSessionController(
auth: auth,
- credentials: source,
+ credentials: QueueCredentials([
+ credential('alice', now.add(const Duration(hours: 1))),
+ credential('bob', now.add(const Duration(hours: 1))),
+ ]),
archive: archive,
clock: () => now,
- gatewayFactory: (key, id, fresh) => SessionGateway(key, id, 'vm-alice'),
+ transportFactory: (_) => QueueTransport(),
);
await settle();
auth.setUser(const AppUser('alice'));
await settle();
- expect(session.state, SessionState.ready);
- final provider = session.gateway!.keys;
- now = now.add(const Duration(seconds: 70));
- final a = session.ensureFresh();
- final b = session.ensureFresh();
+ final a = controller.gateway!;
+ var entered = false;
+ archive.addListener(() {
+ if (!entered && !archive.connected) {
+ entered = true;
+ expect(a.session.isActive, isFalse);
+ auth.setUser(const AppUser('bob'));
+ }
+ });
+ await controller.signOut();
await settle();
- expect(source.calls, 2);
- pending.complete(
- credential(
- 'alice',
- now.add(const Duration(minutes: 2)),
- token: 'rotated',
- ),
+ expect(controller.state, SessionState.ready);
+ expect(controller.user!.uid, 'bob');
+ expect(controller.gateway!.session.isActive, isTrue);
+ controller.dispose();
+ archive.dispose();
+ },
+ );
+ test(
+ 'version 1 legacy principal is tenant binding and never app identity',
+ () {
+ final now = DateTime.utc(2030);
+ final c = credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ tenantId: null,
);
- await Future.wait([a, b]);
- expect(provider.current(), 'rotated');
- now = now.add(const Duration(seconds: 70));
- final renewal = expectLater(
- session.ensureFresh(),
- throwsA(isA<CredentialDenied>()),
+ c.validate(const AppUser('alice'), now);
+ expect(c.tenantBinding, 'shared-principal');
+ expect(
+ () => c.validate(const AppUser('bob'), now),
+ throwsA(isA<CredentialContractError>()),
);
- failed.completeError(const CredentialDenied());
- await renewal;
- expect(session.state, SessionState.denied);
- expect(session.failureKind, SessionFailureKind.credentialDenied);
- expect(() => provider.current(), throwsA(isA<AuthException>()));
- session.dispose();
- archive.dispose();
+ final changed = credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ scope: 'scope_narrow',
+ tenantId: null,
+ );
+ expect(
+ () => changed.validate(const AppUser('alice'), now, previous: c),
+ returnsNormally,
+ );
+ expect(c.samePolicy(changed), isFalse);
+ expect(c.collectionWide, isFalse);
},
);
- test('refresh rejects a changed scope before key rotation', () async {
- var now = DateTime.utc(2030);
- final source = QueueCredentials([
- Future.value(credential('alice', now.add(const Duration(minutes: 2)))),
- Future.value(
- credential(
- 'alice',
- now.add(const Duration(minutes: 4)),
- token: 'must-not-rotate',
- scope: 'scope_other',
- ),
- ),
- ]);
- final archive = ArchiveController(
- persist: false,
- supportDirectory: Directory.systemTemp,
- );
- final auth = MockFirebaseAuth();
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: archive,
- clock: () => now,
- gatewayFactory: (key, scope, fresh) =>
- SessionGateway(key, scope, 'vm-alice'),
- );
- await settle();
- auth.setUser(const AppUser('alice'));
- await settle();
- final provider = session.gateway!.keys;
- expect(provider.current(), 'placeholder-alice');
- now = now.add(const Duration(seconds: 70));
- await expectLater(
- session.ensureFresh(),
- throwsA(isA<CredentialContractError>()),
- );
- expect(session.state, SessionState.error);
- expect(() => provider.current(), throwsA(isA<AuthException>()));
- session.dispose();
- archive.dispose();
- });
-
- test('late account A response cannot replace account B', () async {
- final now = DateTime.utc(2030);
- final delayed = Completer<VmodalCredential>();
- final source = QueueCredentials([
- delayed.future,
- Future.value(credential('bob', now.add(const Duration(hours: 1)))),
- ]);
- final archive = ArchiveController(
- persist: false,
- supportDirectory: Directory.systemTemp,
- );
- final auth = MockFirebaseAuth();
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: archive,
- clock: () => now,
- gatewayFactory: (key, id, fresh) =>
- SessionGateway(key, id, id == 'scope_bob' ? 'vm-bob' : 'vm-alice'),
- );
- await settle();
- auth.setUser(const AppUser('alice'));
- await settle();
- auth.setUser(const AppUser('bob'));
- await settle();
- expect(session.gateway?.collection, 'scope_bob');
- final bobGateway = session.gateway! as SessionGateway;
- delayed.complete(credential('alice', now.add(const Duration(hours: 1))));
- await settle();
- expect(session.gateway?.collection, 'scope_bob');
- await session.signOut();
- expect(session.state, SessionState.signedOut);
- expect(archive.clips.any((c) => c.uploaded), isFalse);
- expect(bobGateway.destructiveCalls, 0);
- session.dispose();
- archive.dispose();
- });
-
- test('late account A refresh cannot reopen after switching to B', () async {
- var now = DateTime.utc(2030);
- final delayed = Completer<VmodalCredential>();
- final source = QueueCredentials([
- Future.value(credential('alice', now.add(const Duration(minutes: 2)))),
- delayed.future,
- Future.value(credential('bob', now.add(const Duration(hours: 1)))),
- ]);
- final archive = ArchiveController(
- persist: false,
- supportDirectory: Directory.systemTemp,
- );
- final auth = MockFirebaseAuth();
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: archive,
- clock: () => now,
- gatewayFactory: (key, id, fresh) =>
- SessionGateway(key, id, id == 'scope_bob' ? 'vm-bob' : 'vm-alice'),
- );
- await settle();
- auth.setUser(const AppUser('alice'));
- await settle();
- now = now.add(const Duration(seconds: 70));
- final old = expectLater(
- session.ensureFresh(),
- throwsA(isA<CredentialDenied>()),
- );
- await settle();
- auth.setUser(const AppUser('bob'));
- await settle();
- expect(session.gateway?.collection, 'scope_bob');
- delayed.complete(credential('alice', now.add(const Duration(hours: 1))));
- await old;
- expect(session.gateway?.collection, 'scope_bob');
- session.dispose();
- archive.dispose();
- });
-
test(
- 'transient refresh retries twice, stays single flight, and rotates in place',
+ 'same key and auth principal isolate A B A sessions and archives',
() async {
- var now = DateTime.utc(2030);
- final delays = <Duration>[];
- final source = QueueCredentials([
- credential('alice', now.add(const Duration(minutes: 2))),
- const CredentialTransient(),
- const CredentialTransient(),
- credential(
- 'alice',
- now.add(const Duration(minutes: 4)),
- token: 'rotated-after-retry',
- ),
- ]);
- final root = await Directory.systemTemp.createTemp('retry_success_');
+ final now = DateTime.utc(2030);
+ final root = await Directory.systemTemp.createTemp('host_same_key_');
addTearDown(() => root.delete(recursive: true));
- final archive = TrackingArchive(supportDirectory: root);
+ final archive = ArchiveController(persist: false, supportDirectory: root);
final auth = MockFirebaseAuth();
- var gateways = 0;
- final session = UserSessionController(
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(hours: 1))),
+ credential('bob', now.add(const Duration(hours: 1))),
+ credential('alice', now.add(const Duration(hours: 1))),
+ ]);
+ final transports = <QueueTransport>[];
+ final controller = UserSessionController(
auth: auth,
credentials: source,
archive: archive,
clock: () => now,
- delay: (value) async => delays.add(value),
- gatewayFactory: (key, scope, fresh) {
- gateways++;
- return SessionGateway(key, scope, 'vm-alice');
+ transportFactory: (_) {
+ final transport = QueueTransport();
+ transports.add(transport);
+ return transport;
},
);
await settle();
auth.setUser(const AppUser('alice'));
await settle();
- final gateway = session.gateway!;
- final provider = gateway.keys;
- now = now.add(const Duration(seconds: 70));
-
- final first = session.ensureFresh();
- final second = session.ensureFresh();
- await Future.wait([first, second]);
-
- expect(source.calls, 4);
- expect(delays, const [
- Duration(milliseconds: 250),
- Duration(milliseconds: 500),
- ]);
- expect(session.state, SessionState.ready);
- expect(session.failureKind, isNull);
- expect(session.gateway, same(gateway));
- expect(session.gateway!.keys, same(provider));
- expect(provider.current(), 'rotated-after-retry');
- expect(archive.activations, 1);
- expect(archive.connected, isTrue);
- expect(gateways, 1);
- session.dispose();
+ expect(controller.state, SessionState.ready);
+ final a = controller.gateway!;
+ final ownerA = a.context.ownerKey;
+ final pathA = archive.archiveDirectory;
+ auth.setUser(const AppUser('bob'));
+ await settle();
+ final b = controller.gateway!;
+ expect(a.session.isActive, isFalse);
+ expect(b.accountId, 'bob');
+ expect(b.context.tenantId, 'same-tenant');
+ expect(b.context.ownerKey, isNot(ownerA));
+ expect(archive.archiveDirectory, isNot(pathA));
+ await expectLater(a.search('private'), throwsA(isA<OperationCanceled>()));
+ a.reportFailure(const AuthException('old error'));
+ expect(controller.gateway, same(b));
+ expect(controller.state, SessionState.ready);
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ expect(controller.gateway!.context.ownerKey, ownerA);
+ expect(controller.gateway!.session.sessionId, isNot(a.session.sessionId));
+ expect(transports, hasLength(3));
+ for (final t in transports) {
+ expect(t.requests.first.headers['Authorization'], 'Bearer same-key');
+ }
+ controller.dispose();
archive.dispose();
},
);
- test('transient exhaustion preserves resources and manual retry', () async {
- var now = DateTime.utc(2030);
- final delays = <Duration>[];
- final source = QueueCredentials([
- credential('alice', now.add(const Duration(minutes: 2))),
- const CredentialTransient(),
- const CredentialTransient(),
- const CredentialTransient(),
- ]);
- final root = await Directory.systemTemp.createTemp('retry_manual_');
- addTearDown(() => root.delete(recursive: true));
- final archive = TrackingArchive(supportDirectory: root);
- final auth = MockFirebaseAuth();
- var gateways = 0;
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: archive,
- clock: () => now,
- delay: (value) async => delays.add(value),
- gatewayFactory: (key, scope, fresh) {
- gateways++;
- return SessionGateway(key, scope, 'vm-alice');
- },
- );
- await settle();
- auth.setUser(const AppUser('alice'));
- await settle();
- final gateway = session.gateway!;
- final provider = gateway.keys;
- now = now.add(const Duration(seconds: 70));
-
- await expectLater(
- session.ensureFresh(),
- throwsA(isA<CredentialTransient>()),
- );
-
- expect(session.state, SessionState.recoverable);
- expect(session.failureKind, SessionFailureKind.transient);
- expect(session.canRetry, isTrue);
- expect(session.gateway, same(gateway));
- expect(session.gateway!.keys, same(provider));
- expect(provider.current(), 'placeholder-alice');
- expect(gateway.collection, 'scope_alice');
- expect(archive.activatedScope, 'scope_alice');
- expect(archive.connected, isTrue);
- expect(session.canRead, isFalse);
- expect(session.canWrite, isFalse);
- expect(gateways, 1);
- expect(archive.activations, 1);
-
- source.items.add(
- credential(
- 'alice',
- now.add(const Duration(minutes: 4)),
- token: 'manual-retry-key',
- ),
- );
- await session.retry();
-
- expect(session.state, SessionState.ready);
- expect(session.failureKind, isNull);
- expect(session.gateway, same(gateway));
- expect(provider.current(), 'manual-retry-key');
- expect(archive.connected, isTrue);
- expect(gateways, 1);
- expect(archive.activations, 1);
- expect(delays, const [
- Duration(milliseconds: 250),
- Duration(milliseconds: 500),
- ]);
- session.dispose();
- archive.dispose();
- });
-
- test('initial transient exhaustion can resolve on manual retry', () async {
+ test('late issuer result cannot replace B or display A archive', () async {
final now = DateTime.utc(2030);
- final delays = <Duration>[];
- final source = QueueCredentials([
- const CredentialTransient(),
- const CredentialTransient(),
- const CredentialTransient(),
- ]);
+ final pending = Completer<VmodalCredential>();
+ final auth = MockFirebaseAuth();
final archive = ArchiveController(
persist: false,
supportDirectory: Directory.systemTemp,
);
- final auth = MockFirebaseAuth();
- var gateways = 0;
- final session = UserSessionController(
+ final controller = UserSessionController(
auth: auth,
- credentials: source,
+ credentials: QueueCredentials([
+ pending.future,
+ credential('bob', now.add(const Duration(hours: 1))),
+ ]),
archive: archive,
clock: () => now,
- delay: (value) async => delays.add(value),
- gatewayFactory: (key, scope, fresh) {
- gateways++;
- return SessionGateway(key, scope, 'vm-alice');
- },
+ transportFactory: (_) => QueueTransport(),
);
await settle();
auth.setUser(const AppUser('alice'));
await settle();
-
- expect(session.state, SessionState.recoverable);
- expect(session.failureKind, SessionFailureKind.transient);
- expect(session.gateway, isNull);
expect(archive.connected, isFalse);
- expect(gateways, 0);
-
- source.items.add(credential('alice', now.add(const Duration(hours: 1))));
- await session.retry();
-
- expect(session.state, SessionState.ready);
- expect(session.failureKind, isNull);
- expect(session.gateway, isNotNull);
- expect(archive.connected, isTrue);
- expect(gateways, 1);
- expect(delays, const [
- Duration(milliseconds: 250),
- Duration(milliseconds: 500),
- ]);
- session.dispose();
+ auth.setUser(const AppUser('bob'));
+ await settle();
+ final b = controller.gateway;
+ pending.complete(credential('alice', now.add(const Duration(hours: 1))));
+ await settle();
+ expect(controller.gateway, same(b));
+ expect(controller.user!.uid, 'bob');
+ controller.dispose();
archive.dispose();
});
- test('terminal refresh failures do not retry and fail closed', () async {
- Future<void> check(
- Object error,
- SessionState expectedState,
- SessionFailureKind expectedKind,
- ) async {
+ test(
+ 'credential-only renewal coalesces and preserves runtime ownership',
+ () async {
var now = DateTime.utc(2030);
- final delays = <Duration>[];
+ final pending = Completer<VmodalCredential>();
final source = QueueCredentials([
credential('alice', now.add(const Duration(minutes: 2))),
- error,
+ pending.future,
]);
+ final auth = MockFirebaseAuth();
final archive = ArchiveController(
persist: false,
supportDirectory: Directory.systemTemp,
);
- final auth = MockFirebaseAuth();
- final session = UserSessionController(
+ final transport = QueueTransport();
+ final controller = UserSessionController(
auth: auth,
credentials: source,
archive: archive,
clock: () => now,
- delay: (value) async => delays.add(value),
- gatewayFactory: (key, scope, fresh) =>
- SessionGateway(key, scope, 'vm-alice'),
+ transportFactory: (_) => transport,
);
await settle();
auth.setUser(const AppUser('alice'));
await settle();
- final provider = session.gateway!.keys;
+ final gateway = controller.gateway!;
+ final id = gateway.session.sessionId;
+ final owner = gateway.context.ownerKey;
now = now.add(const Duration(seconds: 70));
-
- await expectLater(session.ensureFresh(), throwsA(same(error)));
-
- expect(delays, isEmpty);
- expect(session.state, expectedState);
- expect(session.failureKind, expectedKind);
- expect(session.canRetry, isFalse);
- expect(session.gateway, isNull);
- expect(archive.connected, isFalse);
- expect(() => provider.current(), throwsA(isA<AuthException>()));
- session.dispose();
+ final first = controller.ensureFresh();
+ final second = controller.ensureFresh();
+ await settle();
+ expect(source.calls, 2);
+ pending.complete(
+ credential(
+ 'alice',
+ now.add(const Duration(minutes: 2)),
+ token: 'rotated',
+ ),
+ );
+ await Future.wait([first, second]);
+ expect(controller.gateway, same(gateway));
+ expect(gateway.session.sessionId, id);
+ expect(gateway.context.ownerKey, owner);
+ await gateway.listJobs();
+ expect(
+ transport.requests.last.headers['Authorization'],
+ 'Bearer rotated',
+ );
+ controller.dispose();
archive.dispose();
- }
-
- await check(
- const FirebaseIdentityExpired(),
- SessionState.error,
- SessionFailureKind.firebaseIdentityExpired,
- );
- await check(
- const CredentialDenied(),
- SessionState.denied,
- SessionFailureKind.credentialDenied,
- );
- await check(
- const CredentialContractError(),
- SessionState.error,
- SessionFailureKind.contract,
- );
- });
+ },
+ );
- test('VMODAL 401 and 403 stay distinct at connect and after ready', () async {
- Future<void> checkConnect(
- Object error,
- SessionState expectedState,
- SessionFailureKind expectedKind,
- ) async {
- final now = DateTime.utc(2030);
- final delays = <Duration>[];
+ test(
+ 'grant narrowing rebuilds session before exposing the new policy',
+ () async {
+ var now = DateTime.utc(2030);
+ final renewed = credential(
+ 'alice',
+ now.add(const Duration(minutes: 4)),
+ grants: {'library:read'},
+ );
final source = QueueCredentials([
- credential('alice', now.add(const Duration(hours: 1))),
+ credential('alice', now.add(const Duration(minutes: 2))),
+ renewed,
+ renewed,
]);
+ final auth = MockFirebaseAuth();
final archive = ArchiveController(
persist: false,
supportDirectory: Directory.systemTemp,
);
- final auth = MockFirebaseAuth();
- MutableApiKeyProvider? provider;
- final session = UserSessionController(
+ final controller = UserSessionController(
auth: auth,
credentials: source,
archive: archive,
clock: () => now,
- delay: (value) async => delays.add(value),
- gatewayFactory: (key, scope, fresh) {
- provider = key;
- return SessionGateway(key, scope, 'vm-alice', error);
- },
+ transportFactory: (_) => QueueTransport(),
);
await settle();
auth.setUser(const AppUser('alice'));
await settle();
- expect(delays, isEmpty);
- expect(session.state, expectedState);
- expect(session.failureKind, expectedKind);
- expect(session.gateway, isNull);
- expect(archive.connected, isFalse);
- expect(() => provider!.current(), throwsA(isA<AuthException>()));
- session.dispose();
+ final old = controller.gateway!;
+ now = now.add(const Duration(seconds: 70));
+ await expectLater(
+ controller.ensureFresh(),
+ throwsA(isA<TenantAuthException>()),
+ );
+ await settle();
+ expect(old.session.isActive, isFalse);
+ expect(controller.state, SessionState.ready);
+ expect(controller.canWrite, isFalse);
+ expect(controller.canRead, isTrue);
+ expect(
+ controller.gateway!.session.sessionId,
+ isNot(old.session.sessionId),
+ );
+ controller.dispose();
archive.dispose();
- }
-
- await checkConnect(
- const AuthException('expired'),
- SessionState.error,
- SessionFailureKind.vmodalUnauthorized,
- );
- await checkConnect(
- const ApiException('forbidden', statusCode: 403),
- SessionState.denied,
- SessionFailureKind.vmodalForbidden,
- );
+ },
+ );
- Future<void> checkCallback(
- SdkException error,
- SessionState expectedState,
- SessionFailureKind expectedKind,
- ) async {
+ test(
+ 'tenant 401 recovers without signing Firebase user out; old failures are ignored',
+ () async {
final now = DateTime.utc(2030);
- final source = QueueCredentials([
- credential('alice', now.add(const Duration(hours: 1))),
- ]);
+ final auth = MockFirebaseAuth();
final archive = ArchiveController(
persist: false,
supportDirectory: Directory.systemTemp,
);
- final auth = MockFirebaseAuth();
- final session = UserSessionController(
+ final controller = UserSessionController(
auth: auth,
- credentials: source,
+ credentials: QueueCredentials([
+ credential('alice', now.add(const Duration(hours: 1))),
+ credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ token: 'recovered',
+ ),
+ ]),
archive: archive,
clock: () => now,
- gatewayFactory: (key, scope, fresh) =>
- SessionGateway(key, scope, 'vm-alice'),
+ transportFactory: (_) => QueueTransport(),
);
await settle();
auth.setUser(const AppUser('alice'));
await settle();
- final gateway = session.gateway!;
- final provider = gateway.keys;
- gateway.reportFailure(error);
- expect(session.state, expectedState);
- expect(session.failureKind, expectedKind);
- expect(session.gateway, isNull);
- expect(archive.connected, isFalse);
- expect(() => provider.current(), throwsA(isA<AuthException>()));
- session.dispose();
+ final gateway = controller.gateway!;
+ gateway.reportFailure(const AuthException('expired'));
+ expect(controller.state, SessionState.recoverable);
+ expect(controller.user!.uid, 'alice');
+ expect(controller.gateway, same(gateway));
+ expect(controller.canRetry, isTrue);
+ await controller.retry();
+ expect(controller.state, SessionState.ready);
+ expect(controller.gateway, same(gateway));
+ await controller.signOut();
+ gateway.reportFailure(const AuthException('late'));
+ expect(controller.state, SessionState.signedOut);
+ controller.dispose();
archive.dispose();
- }
-
- await checkCallback(
- const AuthException('expired'),
- SessionState.error,
- SessionFailureKind.vmodalUnauthorized,
- );
- await checkCallback(
- const ApiException('forbidden', statusCode: 403),
- SessionState.denied,
- SessionFailureKind.vmodalForbidden,
- );
- });
-
- test('Firebase identity expiry from the adapter does not back off', () async {
- var now = DateTime.utc(2030);
- final expired = FirebaseIdentityExpired();
- final auth = TokenAuth(['initial', expired]);
- final source = QueueCredentials([
- credential('alice', now.add(const Duration(minutes: 2))),
- ]);
- final archive = ArchiveController(
- persist: false,
- supportDirectory: Directory.systemTemp,
- );
- final delays = <Duration>[];
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: archive,
- clock: () => now,
- delay: (value) async => delays.add(value),
- gatewayFactory: (key, scope, fresh) =>
- SessionGateway(key, scope, 'vm-alice'),
- );
- await settle();
- auth.setUser(const AppUser('alice'));
- await settle();
- final provider = session.gateway!.keys;
- now = now.add(const Duration(seconds: 70));
- await expectLater(session.ensureFresh(), throwsA(same(expired)));
- expect(delays, isEmpty);
- expect(session.state, SessionState.error);
- expect(session.failureKind, SessionFailureKind.firebaseIdentityExpired);
- expect(() => provider.current(), throwsA(isA<AuthException>()));
- expect(archive.connected, isFalse);
- session.dispose();
- archive.dispose();
- });
-
- test('account switch during retry backoff cannot mutate old state', () async {
- var now = DateTime.utc(2030);
- final waiting = Completer<void>();
- final delays = <Duration>[];
- final source = QueueCredentials([
- credential('alice', now.add(const Duration(minutes: 2))),
- const CredentialTransient(),
- credential('bob', now.add(const Duration(hours: 1))),
- ]);
- final root = await Directory.systemTemp.createTemp('retry_switch_');
- addTearDown(() => root.delete(recursive: true));
- final archive = TrackingArchive(supportDirectory: root);
- final auth = MockFirebaseAuth();
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: archive,
- clock: () => now,
- delay: (value) {
- delays.add(value);
- return waiting.future;
- },
- gatewayFactory: (key, scope, fresh) => SessionGateway(
- key,
- scope,
- scope == 'scope_bob' ? 'vm-bob' : 'vm-alice',
- ),
- );
- await settle();
- auth.setUser(const AppUser('alice'));
- await settle();
- final oldGateway = session.gateway!;
- final oldProvider = oldGateway.keys;
- now = now.add(const Duration(seconds: 70));
- final oldRefresh = expectLater(
- session.ensureFresh(),
- throwsA(isA<CredentialTransient>()),
- );
- await settle();
- expect(delays, const [Duration(milliseconds: 250)]);
-
- auth.setUser(const AppUser('bob'));
- await settle();
- expect(session.state, SessionState.ready);
- expect(session.gateway?.collection, 'scope_bob');
- expect(archive.activatedScope, 'scope_bob');
- waiting.complete();
- await oldRefresh;
-
- expect(session.state, SessionState.ready);
- expect(session.failureKind, isNull);
- expect(session.gateway?.collection, 'scope_bob');
- expect(archive.activatedScope, 'scope_bob');
- expect(session.gateway, isNot(same(oldGateway)));
- expect(() => oldProvider.current(), throwsA(isA<AuthException>()));
- session.dispose();
- archive.dispose();
- });
+ },
+ );
}
diff --git a/example/05_framebase_userlogin/test/user_session_failures_test.dart b/example/05_framebase_userlogin/test/user_session_failures_test.dart
new file mode 100644
index 0000000..69ae5e2
--- /dev/null
+++ b/example/05_framebase_userlogin/test/user_session_failures_test.dart
@@ -0,0 +1,295 @@
+import 'dart:async';
+import 'dart:io';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:framebase/data/archive_controller.dart';
+import 'package:framebase/user/auth_adapter.dart';
+import 'package:framebase/user/mock_firebase_auth.dart';
+import 'package:framebase/user/user_session_controller.dart';
+import 'package:framebase/user/vmodal_credential.dart';
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+import 'session_fixture.dart';
+import 'user_session_controller_test.dart'
+ show credential, QueueCredentials, settle;
+
+class ExpiredAuth extends MockFirebaseAuth {
+ @override
+ Future<String?> idToken(AppUser user) async =>
+ throw FirebaseIdentityExpired();
+}
+
+void main() {
+ test(
+ 'initial failures preserve denial identity and contract distinctions without retries',
+ () async {
+ final now = DateTime.utc(2030);
+ for (final entry in [
+ (
+ const CredentialDenied(),
+ SessionFailureKind.credentialDenied,
+ SessionState.denied,
+ ),
+ (
+ const CredentialContractError(),
+ SessionFailureKind.contract,
+ SessionState.error,
+ ),
+ (
+ FirebaseIdentityExpired(),
+ SessionFailureKind.firebaseIdentityExpired,
+ SessionState.error,
+ ),
+ ]) {
+ final auth = MockFirebaseAuth();
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final source = QueueCredentials([entry.$1]);
+ final waits = <Duration>[];
+ var transports = 0;
+ final controller = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (wait) async => waits.add(wait),
+ transportFactory: (_) {
+ transports++;
+ return QueueTransport();
+ },
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ expect(controller.failureKind, entry.$2);
+ expect(controller.state, entry.$3);
+ expect(waits, isEmpty);
+ expect(transports, 0);
+ expect(archive.connected, isFalse);
+ controller.dispose();
+ archive.dispose();
+ }
+ },
+ );
+
+ test(
+ 'missing read grant and malformed scope fail before creating cloud session',
+ () async {
+ final now = DateTime.utc(2030);
+ for (final c in [
+ credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ grants: {'library:write'},
+ ),
+ credential(
+ 'alice',
+ now.add(const Duration(hours: 1)),
+ scope: '../scope',
+ ),
+ ]) {
+ final auth = MockFirebaseAuth();
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ var transports = 0;
+ final controller = UserSessionController(
+ auth: auth,
+ credentials: QueueCredentials([c]),
+ archive: archive,
+ clock: () => now,
+ transportFactory: (_) {
+ transports++;
+ return QueueTransport();
+ },
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ expect(transports, 0);
+ expect(controller.gateway, isNull);
+ expect(
+ controller.failureKind,
+ c.permissions.contains('library:read')
+ ? SessionFailureKind.contract
+ : SessionFailureKind.credentialDenied,
+ );
+ controller.dispose();
+ archive.dispose();
+ }
+ },
+ );
+
+ test(
+ 'transient acquisition uses two bounded backoffs and manual retry restores this user',
+ () async {
+ final now = DateTime.utc(2030);
+ final auth = MockFirebaseAuth();
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final source = QueueCredentials([
+ const CredentialTransient(),
+ const CredentialTransient(),
+ const CredentialTransient(),
+ credential('alice', now.add(const Duration(hours: 1))),
+ ]);
+ final waits = <Duration>[];
+ final controller = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (wait) async => waits.add(wait),
+ transportFactory: (_) => QueueTransport(),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ expect(source.calls, 3);
+ expect(waits, [
+ const Duration(milliseconds: 250),
+ const Duration(milliseconds: 500),
+ ]);
+ expect(controller.state, SessionState.recoverable);
+ expect(controller.canRead, isFalse);
+ await controller.retry();
+ expect(controller.state, SessionState.ready);
+ expect(source.calls, 4);
+ controller.dispose();
+ archive.dispose();
+ },
+ );
+
+ test(
+ 'renewal transient exhaustion blocks calls and retry preserves existing lease',
+ () async {
+ var now = DateTime.utc(2030);
+ final auth = MockFirebaseAuth();
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(minutes: 2))),
+ const CredentialTransient(),
+ const CredentialTransient(),
+ const CredentialTransient(),
+ ]);
+ final waits = <Duration>[];
+ final controller = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (wait) async => waits.add(wait),
+ transportFactory: (_) => QueueTransport(),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final gateway = controller.gateway!;
+ now = now.add(const Duration(seconds: 70));
+ await expectLater(
+ controller.ensureFresh(),
+ throwsA(isA<TenantAuthException>()),
+ );
+ expect(controller.state, SessionState.recoverable);
+ expect(controller.failureKind, SessionFailureKind.transient);
+ expect(waits, hasLength(2));
+ expect(controller.gateway, same(gateway));
+ expect(gateway.session.isActive, isTrue);
+ source.items.add(
+ credential(
+ 'alice',
+ now.add(const Duration(minutes: 3)),
+ token: 'retry-key',
+ ),
+ );
+ await controller.retry();
+ expect(controller.state, SessionState.ready);
+ expect(controller.gateway, same(gateway));
+ controller.dispose();
+ archive.dispose();
+ },
+ );
+
+ test(
+ 'switch during renewal backoff never dispatches another A issuer request',
+ () async {
+ var now = DateTime.utc(2030);
+ final wait = Completer<void>();
+ final source = QueueCredentials([
+ credential('alice', now.add(const Duration(minutes: 2))),
+ const CredentialTransient(),
+ credential('bob', now.add(const Duration(hours: 1))),
+ ]);
+ final auth = MockFirebaseAuth();
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final controller = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ clock: () => now,
+ delay: (_) => wait.future,
+ transportFactory: (_) => QueueTransport(),
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ final a = controller.gateway!;
+ now = now.add(const Duration(seconds: 70));
+ final renewal = expectLater(
+ controller.ensureFresh(),
+ throwsA(isA<CredentialDenied>()),
+ );
+ await settle();
+ auth.setUser(const AppUser('bob'));
+ await settle();
+ final b = controller.gateway!;
+ wait.complete();
+ await renewal;
+ expect(source.calls, 3);
+ expect(controller.gateway, same(b));
+ expect(a.session.isActive, isFalse);
+ expect(controller.state, SessionState.ready);
+ expect(controller.user!.uid, 'bob');
+ controller.dispose();
+ archive.dispose();
+ },
+ );
+
+ test(
+ 'Firebase token expiry fails once before calling credential issuer',
+ () async {
+ final auth = ExpiredAuth();
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final source = QueueCredentials([]);
+ final controller = UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: archive,
+ );
+ await settle();
+ auth.setUser(const AppUser('alice'));
+ await settle();
+ expect(source.calls, 0);
+ expect(
+ controller.failureKind,
+ SessionFailureKind.firebaseIdentityExpired,
+ );
+ expect(controller.gateway, isNull);
+ expect(controller.canRetry, isFalse);
+ controller.dispose();
+ archive.dispose();
+ },
+ );
+}
diff --git a/example/05_framebase_userlogin/test/widget_test.dart b/example/05_framebase_userlogin/test/widget_test.dart
index a1bcd84..f8661cd 100644
--- a/example/05_framebase_userlogin/test/widget_test.dart
+++ b/example/05_framebase_userlogin/test/widget_test.dart
@@ -1,4 +1,6 @@
+import 'dart:async';
import 'dart:io';
+import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:framebase/main.dart';
@@ -10,12 +12,12 @@ import 'package:framebase/user/mock_firebase_auth.dart';
import 'package:framebase/user/user_session_controller.dart';
import 'package:framebase/user/vmodal_credential.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+import 'session_fixture.dart';
class FakeGateway extends SearchGateway {
- FakeGateway(super.keys, super.scopeId);
+ FakeGateway(super.session, super.scopeId);
@override
Future<void> connect(String expectedUserId) async {
- accountId = expectedUserId;
version = 1;
}
@@ -60,19 +62,27 @@ class LifecycleArchive extends ArchiveController {
}
}
-VmodalCredential fixture() => VmodalCredential(
+VmodalCredential fixture([String uid = 'alice']) => VmodalCredential(
contractVersion: 1,
sessionId: 'widget-session',
issuedAt: DateTime.now().toUtc(),
apiToken: 'test-only-placeholder',
expiresAt: DateTime.now().toUtc().add(const Duration(hours: 1)),
- firebaseUid: 'alice',
+ firebaseUid: uid,
vmodalUserId: 'vmodal-alice',
scopeId: 'scope_7K3A',
allowed: true,
permissions: {'library:read', 'library:write'},
);
+class DelayedFileArchive extends ArchiveController {
+ DelayedFileArchive()
+ : super(persist: false, supportDirectory: Directory.systemTemp);
+ final file = Completer<File>();
+ @override
+ Future<File> localFile(ArchiveClip clip) => file.future;
+}
+
FrameMatch frameMatch({
required String name,
required int offsetMs,
@@ -89,6 +99,133 @@ FrameMatch frameMatch({
}
void main() {
+ testWidgets(
+ 'collapsed A B A resets navigation and evicts private memory images',
+ (tester) async {
+ final archive = ArchiveController(
+ persist: false,
+ supportDirectory: Directory.systemTemp,
+ );
+ final auth = MockFirebaseAuth();
+ final session = (await tester.runAsync(
+ () async => UserSessionController(
+ auth: auth,
+ credentials: MockVmodalCredentialSource([
+ fixture('alice'),
+ fixture('bob'),
+ fixture('alice'),
+ ]),
+ archive: archive,
+ transportFactory: (_) => QueueTransport(),
+ gatewayFactory: (session, scope, fresh) =>
+ FakeGateway(session, scope),
+ ),
+ ))!;
+ await tester.pumpWidget(
+ FramebaseApp(controller: archive, session: session),
+ );
+ await tester.pumpAndSettle();
+ await tester.runAsync(() async {
+ auth.setUser(const AppUser('alice'));
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ });
+ await tester.pumpAndSettle();
+ expect(session.state, SessionState.ready);
+ final aSessionId = session.gateway!.session.sessionId;
+ final originalNavigator = tester.state<NavigatorState>(
+ find.byType(Navigator),
+ );
+ unawaited(
+ originalNavigator.push(
+ MaterialPageRoute<void>(
+ builder: (_) => const Scaffold(body: Text('Private A navigation')),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Private A navigation'), findsOneWidget);
+
+ final recorder = ui.PictureRecorder();
+ ui.Canvas(recorder).drawColor(Colors.blue, ui.BlendMode.src);
+ final pixel = (await tester.runAsync(
+ () => recorder.endRecording().toImage(1, 1),
+ ))!;
+ final png = (await tester.runAsync(
+ () => pixel.toByteData(format: ui.ImageByteFormat.png),
+ ))!;
+ final image = MemoryImage(png.buffer.asUint8List());
+ pixel.dispose();
+ final imageContext = tester.element(find.text('Private A navigation'));
+ await tester.runAsync(() => precacheImage(image, imageContext));
+ await tester.pump();
+ final cache = PaintingBinding.instance.imageCache;
+ expect(cache.containsKey(image), isTrue);
+
+ // Resolve both transitions without rendering an intermediate B frame.
+ await tester.runAsync(() async {
+ auth.setUser(const AppUser('bob'));
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ expect(session.state, SessionState.ready);
+ expect(cache.containsKey(image), isFalse);
+ auth.setUser(const AppUser('alice'));
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ });
+ expect(session.state, SessionState.ready);
+ expect(session.user!.uid, 'alice');
+ expect(session.gateway!.session.sessionId, isNot(aSessionId));
+ await tester.pumpAndSettle();
+ expect(find.text('Private A navigation'), findsNothing);
+ expect(
+ tester.state<NavigatorState>(find.byType(Navigator)),
+ isNot(same(originalNavigator)),
+ );
+ expect(cache.containsKey(image), isFalse);
+ await tester.pumpWidget(const SizedBox.shrink());
+ session.dispose();
+ archive.dispose();
+ },
+ );
+
+ testWidgets(
+ 'archive invalidation hides a recording while its file load is still pending',
+ (tester) async {
+ final archive = DelayedFileArchive();
+ final gateway = SearchGateway(await testSession(), 'scope_7K3A');
+ await tester.runAsync(
+ () => archive.activate(
+ 'scope_7K3A',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: gateway.context.serviceNamespace,
+ tenantId: gateway.context.tenantId,
+ appUserId: gateway.context.appUserId,
+ policyRevision: gateway.context.policyRevision,
+ ),
+ );
+ final clip = archive.clips.first;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: RecordingSheet(archive: archive, clip: clip),
+ ),
+ );
+ await tester.pump();
+ expect(find.text(clip.title), findsOneWidget);
+ archive.deactivate();
+ await tester.pump();
+ expect(find.text(clip.title), findsNothing);
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ archive.file.complete(
+ File('${Directory.systemTemp.path}/stale-never-open.mp4'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text(clip.title), findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ archive.dispose();
+ await gateway.close();
+ },
+ );
testWidgets(
'search starts with two moments per video and expands on request',
(tester) async {
@@ -190,20 +327,27 @@ void main() {
},
);
final source = MockVmodalCredentialSource([fixture()]);
- final session = UserSessionController(
- auth: auth,
- credentials: source,
- archive: c,
- gatewayFactory: (provider, id, fresh) => FakeGateway(provider, id),
- );
+ final session = (await tester.runAsync(
+ () async => UserSessionController(
+ auth: auth,
+ credentials: source,
+ archive: c,
+ transportFactory: (_) => QueueTransport(),
+ gatewayFactory: (session, id, fresh) => FakeGateway(session, id),
+ ),
+ ))!;
await tester.pumpWidget(FramebaseApp(controller: c, session: session));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('email')), '[email protected]');
await tester.enterText(find.byKey(const Key('password')), 'password');
- await tester.tap(find.byKey(const Key('sign_in')));
+ await tester.runAsync(() async {
+ await tester.tap(find.byKey(const Key('sign_in')));
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ });
for (var i = 0; i < 200 && session.state == SessionState.resolving; i++) {
await tester.pump(const Duration(milliseconds: 10));
}
+ expect(session.state, SessionState.ready);
await tester.pumpAndSettle();
expect(session.state, SessionState.ready);
expect(find.text('Framebase'), findsOneWidget);
@@ -225,14 +369,14 @@ void main() {
await tester.tap(find.text('Profile'));
await tester.pumpAndSettle();
expect(find.text('VMODAL connected'), findsOneWidget);
- final keys = session.gateway!.keys;
+ final sdkSession = session.gateway!.session;
await tester.tap(find.byKey(const Key('sign_out')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('sign_in')), findsOneWidget);
expect(find.byType(VideoRow), findsNothing);
expect(c.connected, isFalse);
expect(session.gateway, isNull);
- expect(() => keys.current(), throwsA(isA<AuthException>()));
+ expect(sdkSession.isActive, isFalse);
session.dispose();
c.dispose();
});
@@ -296,40 +440,54 @@ void main() {
session.dispose();
c.dispose();
});
- testWidgets('expired identity and VMODAL 401 show sign in again', (
- tester,
- ) async {
- for (final kind in [
- SessionFailureKind.firebaseIdentityExpired,
- SessionFailureKind.vmodalUnauthorized,
- ]) {
- final c = ArchiveController(persist: false);
- final session = UserSessionController(
- auth: MockFirebaseAuth(initial: const AppUser('alice')),
- credentials: MockVmodalCredentialSource(),
- archive: c,
- );
- await tester.pump();
- session.state = SessionState.error;
- session.failureKind = kind;
- session.message = kind == SessionFailureKind.firebaseIdentityExpired
- ? 'Your sign-in expired. Sign in again.'
- : 'Your library session expired. Sign in again.';
+ testWidgets(
+ 'identity expiry signs in again and tenant 401 offers connection retry',
+ (tester) async {
+ for (final kind in [
+ SessionFailureKind.firebaseIdentityExpired,
+ SessionFailureKind.vmodalUnauthorized,
+ ]) {
+ final c = ArchiveController(persist: false);
+ final session = UserSessionController(
+ auth: MockFirebaseAuth(initial: const AppUser('alice')),
+ credentials: MockVmodalCredentialSource(),
+ archive: c,
+ );
+ await tester.pump();
+ final expiredIdentity =
+ kind == SessionFailureKind.firebaseIdentityExpired;
+ session.state = expiredIdentity
+ ? SessionState.error
+ : SessionState.recoverable;
+ session.failureKind = kind;
+ session.message = kind == SessionFailureKind.firebaseIdentityExpired
+ ? 'Your sign-in expired. Sign in again.'
+ : 'The tenant connection needs recovery. Retry to reconnect your library.';
- await tester.pumpWidget(MaterialApp(home: LoginPage(session: session)));
+ await tester.pumpWidget(MaterialApp(home: LoginPage(session: session)));
- expect(find.text(session.message), findsOneWidget);
- expect(find.text('Sign in again'), findsOneWidget);
- expect(find.text('Retry'), findsNothing);
- await tester.tap(find.text('Sign in again'));
- await tester.pumpAndSettle();
- expect(session.state, SessionState.signedOut);
- expect(find.byKey(const Key('sign_in')), findsOneWidget);
- await tester.pumpWidget(const SizedBox.shrink());
- session.dispose();
- c.dispose();
- }
- });
+ expect(find.text(session.message), findsOneWidget);
+ expect(
+ find.text('Sign in again'),
+ expiredIdentity ? findsOneWidget : findsNothing,
+ );
+ expect(
+ find.text('Retry'),
+ expiredIdentity ? findsNothing : findsOneWidget,
+ );
+ if (!expiredIdentity) expect(session.user!.uid, 'alice');
+ await tester.tap(
+ find.text(expiredIdentity ? 'Sign in again' : 'Sign out'),
+ );
+ await tester.pumpAndSettle();
+ expect(session.state, SessionState.signedOut);
+ expect(find.byKey(const Key('sign_in')), findsOneWidget);
+ await tester.pumpWidget(const SizedBox.shrink());
+ session.dispose();
+ c.dispose();
+ }
+ },
+ );
testWidgets('denial, VMODAL 403, and contract failures cannot retry', (
tester,
) async {
@@ -408,11 +566,19 @@ void main() {
persist: false,
supportDirectory: Directory.systemTemp,
);
- final gateway = FakeGateway(
- MutableApiKeyProvider('fixture-delete'),
- 'scope_7K3A',
+ final gateway = FakeGateway(await testSession(), 'scope_7K3A');
+ await tester.runAsync(
+ () => c.activate(
+ 'scope_7K3A',
+ gateway,
+ canRead: true,
+ canWrite: true,
+ serviceNamespace: gateway.context.serviceNamespace,
+ tenantId: gateway.context.tenantId,
+ appUserId: gateway.context.appUserId,
+ policyRevision: gateway.context.policyRevision,
+ ),
);
- await c.activate('scope_7K3A', gateway, canRead: true, canWrite: true);
await tester.pumpWidget(MaterialApp(home: StorageDeletionPage(archive: c)));
expect(
find.text('Signing out keeps videos on this device and in the cloud.'),
diff --git a/lib/src/api_key_provider.dart b/lib/src/api_key_provider.dart
index ac56b88..125eebf 100644
--- a/lib/src/api_key_provider.dart
+++ b/lib/src/api_key_provider.dart
@@ -1,3 +1,6 @@
+import 'dart:async';
+import 'dart:convert';
+
import 'errors.dart';
/// Supplies the API key used immediately before each SDK request.
@@ -20,6 +23,9 @@ class MutableApiKeyProvider implements ApiKeyProvider {
String? _key;
bool _closed = false;
+ /// Whether this provider has been permanently disabled.
+ bool get isClosed => _closed;
+
/// Replaces the active key, or throws [AuthException] after [close].
void rotate(String newKey) {
final valid = strApiKey(newKey);
@@ -51,6 +57,281 @@ class MutableApiKeyProvider implements ApiKeyProvider {
String toString() => 'MutableApiKeyProvider([REDACTED])';
}
+/// A credential returned by the host's trusted tenant issuer/resolver.
+/// The resolver must verify these binding fields; they are not app-user claims.
+class TenantCredential {
+ TenantCredential({
+ required this.serviceNamespace,
+ required this.tenantId,
+ required this.principal,
+ required String apiKey,
+ this.issuerVersion,
+ }) : apiKey = strApiKey(apiKey);
+
+ final String serviceNamespace;
+ final String tenantId;
+ final String principal;
+ final String apiKey;
+ final int? issuerVersion;
+
+ @override
+ String toString() => 'TenantCredential([REDACTED])';
+}
+
+/// Immutable accepted tenant credential, captured before request construction.
+class TenantCredentialSnapshot {
+ TenantCredentialSnapshot._(this.credential, this.binding, this.revision);
+
+ final TenantCredential credential;
+ final String binding;
+ final int revision;
+ String get apiKey => credential.apiKey;
+
+ @override
+ String toString() => 'TenantCredentialSnapshot(revision=$revision)';
+}
+
+/// Shared tenant renewal coordinator, independent of app-user lifetimes.
+///
+/// One normal renewal is shared by all providers. A superseding renewal or
+/// external install fences older results using both ticket and base revision.
+/// No key is persisted, and failures block calls unless the host explicitly
+/// permits retaining the previous credential under its validity policy.
+class TenantCredentialSource {
+ TenantCredentialSource({
+ required this.serviceNamespace,
+ required this.tenantId,
+ required this.expectedPrincipal,
+ required String initialKey,
+ this.renew,
+ int? initialIssuerVersion,
+ this.retainOnRenewalFailure = false,
+ }) {
+ if (<String>[
+ serviceNamespace,
+ tenantId,
+ expectedPrincipal,
+ ].any((String value) => value.trim().isEmpty)) {
+ throw const ValidationException('tenant credential binding is required');
+ }
+ _snapshot = TenantCredentialSnapshot._(
+ TenantCredential(
+ serviceNamespace: serviceNamespace,
+ tenantId: tenantId,
+ principal: expectedPrincipal,
+ apiKey: initialKey,
+ issuerVersion: initialIssuerVersion,
+ ),
+ binding,
+ 0,
+ );
+ }
+
+ final String serviceNamespace;
+ final String tenantId;
+ final String expectedPrincipal;
+ final Future<TenantCredential> Function()? renew;
+ final bool retainOnRenewalFailure;
+ late TenantCredentialSnapshot _snapshot;
+ final Set<TenantSessionApiKeyProvider> _providers =
+ <TenantSessionApiKeyProvider>{};
+ Future<TenantCredentialSnapshot>? _pending;
+ int _ticket = 0;
+ bool _valid = true;
+ bool _closed = false;
+
+ String get binding =>
+ jsonEncode(<String>[serviceNamespace, tenantId, expectedPrincipal]);
+ int get revision => _snapshot.revision;
+ bool get isAvailable => !_closed && _valid;
+
+ TenantCredentialSnapshot get currentSnapshot {
+ if (!isAvailable) throw const TenantAuthException();
+ return _snapshot;
+ }
+
+ /// Attaches and reads the latest committed revision without an await gap.
+ TenantSessionApiKeyProvider createProvider({
+ required bool Function() isActive,
+ }) {
+ if (!isActive()) throw const OperationCanceled();
+ final provider = TenantSessionApiKeyProvider._(
+ this,
+ currentSnapshot,
+ isActive,
+ );
+ _providers.add(provider);
+ provider.current();
+ return provider;
+ }
+
+ /// Installs a trusted replacement. Binding changes require a new source.
+ void install(TenantCredential candidate) {
+ if (_closed) throw const TenantAuthException();
+ _validate(candidate);
+ ++_ticket;
+ _pending = null;
+ _commit(candidate);
+ }
+
+ /// Coalesces normal renewals; [supersede] deliberately fences earlier ones.
+ Future<TenantCredentialSnapshot> renewCredential({bool supersede = false}) {
+ if (_closed) {
+ return Future<TenantCredentialSnapshot>.error(
+ const TenantAuthException(),
+ );
+ }
+ if (!supersede && _pending != null) return _pending!;
+ final resolver = renew;
+ if (resolver == null) {
+ return Future<TenantCredentialSnapshot>.error(
+ const TenantAuthException(),
+ );
+ }
+ final ticket = ++_ticket;
+ final base = revision;
+ final completer = Completer<TenantCredentialSnapshot>();
+ final future = completer.future;
+ _pending = future;
+ unawaited(
+ Future<TenantCredential>.sync(resolver)
+ .then((TenantCredential candidate) {
+ if (ticket == _ticket && base == revision && !_closed) {
+ _validate(candidate);
+ _commit(candidate);
+ }
+ return currentSnapshot;
+ })
+ .then(
+ completer.complete,
+ onError: (Object error, StackTrace stack) {
+ if (ticket == _ticket && base == revision && !_closed) {
+ if (!retainOnRenewalFailure) _valid = false;
+ completer.completeError(const TenantAuthException(), stack);
+ } else if (isAvailable) {
+ completer.complete(currentSnapshot);
+ } else {
+ completer.completeError(const TenantAuthException(), stack);
+ }
+ },
+ )
+ .whenComplete(() {
+ if (identical(_pending, future)) _pending = null;
+ }),
+ );
+ return future;
+ }
+
+ /// A stale request cannot revoke a newer accepted credential.
+ Future<TenantCredentialSnapshot> recover(int failedRevision) {
+ if (isAvailable && failedRevision < revision) {
+ return Future<TenantCredentialSnapshot>.value(currentSnapshot);
+ }
+ return renewCredential();
+ }
+
+ /// Authoritative revocation, unlike an unverified request's 401 response.
+ void revoke() {
+ ++_ticket;
+ _pending = null;
+ _valid = false;
+ for (final provider in _providers) {
+ provider.clear();
+ }
+ }
+
+ void close() {
+ if (_closed) return;
+ _closed = true;
+ revoke();
+ for (final provider in _providers.toList()) {
+ provider.close();
+ }
+ }
+
+ void _validate(TenantCredential candidate) {
+ if (candidate.serviceNamespace != serviceNamespace ||
+ candidate.tenantId != tenantId ||
+ candidate.principal != expectedPrincipal) {
+ throw const TenantAuthException('tenant credential binding changed');
+ }
+ final currentVersion = _snapshot.credential.issuerVersion;
+ final nextVersion = candidate.issuerVersion;
+ if (currentVersion != null &&
+ (nextVersion == null ||
+ nextVersion < currentVersion ||
+ (nextVersion == currentVersion &&
+ candidate.apiKey != _snapshot.apiKey))) {
+ throw const TenantAuthException('tenant credential version is stale');
+ }
+ }
+
+ void _commit(TenantCredential candidate) {
+ _snapshot = TenantCredentialSnapshot._(candidate, binding, revision + 1);
+ _valid = true;
+ for (final provider in _providers.toList()) {
+ provider._install(_snapshot);
+ }
+ }
+
+ @override
+ String toString() => 'TenantCredentialSource(revision=$revision)';
+}
+
+/// A private session provider subscribed to one shared tenant binding.
+class TenantSessionApiKeyProvider extends MutableApiKeyProvider {
+ TenantSessionApiKeyProvider._(
+ this._source,
+ TenantCredentialSnapshot snapshot,
+ this._isActive,
+ ) : _revision = snapshot.revision,
+ super(snapshot.apiKey);
+
+ final TenantCredentialSource _source;
+ final bool Function() _isActive;
+ int _revision;
+ int get installedRevision => _revision;
+ String get binding => _source.binding;
+
+ TenantCredentialSnapshot snapshot() {
+ if (isClosed || !_isActive()) throw const SessionInvalidated();
+ final value = _source.currentSnapshot;
+ _install(value);
+ return value;
+ }
+
+ @override
+ String current() => snapshot().apiKey;
+
+ Future<void> recover(int failedRevision) async {
+ snapshot();
+ await _source.recover(failedRevision);
+ snapshot();
+ }
+
+ void _install(TenantCredentialSnapshot value) {
+ if (isClosed ||
+ !_isActive() ||
+ value.binding != binding ||
+ value.revision <= _revision) {
+ return;
+ }
+ super.rotate(value.apiKey);
+ _revision = value.revision;
+ }
+
+ @override
+ void rotate(String newKey) => throw const TenantAuthException(
+ 'install tenant credentials through the credential source',
+ );
+
+ @override
+ void close() {
+ _source._providers.remove(this);
+ super.close();
+ }
+}
+
/// @nodoc
String strApiKey(String value) {
final key = value.trim();
diff --git a/lib/src/client.dart b/lib/src/client.dart
index 2b3e166..686dcd9 100644
--- a/lib/src/client.dart
+++ b/lib/src/client.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'config.dart';
import 'errors.dart';
import 'http.dart';
@@ -7,7 +9,7 @@ import 'transport.dart';
import 'upload.dart';
/// Version of the Dart SDK contract represented by this package.
-const String vmodalSdkVersion = '1.2.3';
+const String vmodalSdkVersion = '1.3.0';
/// Owns configuration, transports, and feature resources for one app session.
///
@@ -75,7 +77,7 @@ class VmodalClient {
/// Compatibility surface whose methods currently throw [FeatureDisabled].
final SqlResource sql = SqlResource();
- bool _closed = false;
+ Future<void>? _closeFuture;
/// Checks service health and returns version/dependency information.
Future<HealthResponse> health({CancellationToken? cancellation}) =>
@@ -162,11 +164,24 @@ class VmodalClient {
);
}
- /// Closes both owned transports. Repeated calls have no effect.
- Future<void> close() async {
- if (_closed) return;
- _closed = true;
- await transport.close();
- await signedUploadTransport.close();
+ /// Closes both owned transports, even if one fails, sharing cleanup calls.
+ Future<void> close() {
+ final pending = _closeFuture;
+ if (pending != null) return pending;
+ final result = Completer<void>();
+ _closeFuture = result.future;
+ unawaited(
+ _closeTransports().then(result.complete, onError: result.completeError),
+ );
+ return result.future;
+ }
+
+ Future<void> _closeTransports() async {
+ // Start both independently, even if one throws synchronously or waits on
+ // uncooperative I/O. Future.wait observes both failures before settling.
+ await Future.wait<void>(<Future<void>>[
+ Future<void>.sync(transport.close),
+ Future<void>.sync(signedUploadTransport.close),
+ ]);
}
}
diff --git a/lib/src/errors.dart b/lib/src/errors.dart
index 962308e..5f3bf45 100644
--- a/lib/src/errors.dart
+++ b/lib/src/errors.dart
@@ -37,6 +37,14 @@ class AuthException extends SdkException {
});
}
+/// Tenant connection failure. This does not invalidate host app-user identity.
+/// No server body, credential, or issuer error is attached to this failure.
+class TenantAuthException extends AuthException {
+ const TenantAuthException([
+ super.message = 'tenant connection authentication failed',
+ ]);
+}
+
/// Valid service response that represents an unsuccessful operation.
class ApiException extends SdkException {
const ApiException(
@@ -86,3 +94,8 @@ class MalformedResponse extends SdkException {
class OperationCanceled extends SdkException {
const OperationCanceled() : super('operation canceled');
}
+
+/// An operation belongs to a session which is no longer active.
+class SessionInvalidated extends OperationCanceled {
+ const SessionInvalidated();
+}
diff --git a/lib/src/http.dart b/lib/src/http.dart
index 8432613..232091e 100644
--- a/lib/src/http.dart
+++ b/lib/src/http.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
+import 'api_key_provider.dart';
import 'config.dart';
import 'errors.dart';
import 'transport.dart';
@@ -19,6 +20,8 @@ class VmodalHttp {
final SdkConfig config;
final VmodalTransport transport;
final DelayStrategy _delay;
+ final Expando<TenantCredentialSnapshot> _credentialSnapshots =
+ Expando<TenantCredentialSnapshot>();
Map<String, String> headers({
bool forceToken = false,
@@ -43,13 +46,20 @@ class VmodalHttp {
out['X-User-Email'] = strHeaderValue('email', config.normalizedEmail);
}
}
+ TenantCredentialSnapshot? snapshot;
if (forceToken || config.normalizedMode != 'direct') {
- final key = config.currentApiKey();
+ final provider = config.apiKeyProvider;
+ if (provider is TenantSessionApiKeyProvider) {
+ snapshot = provider.snapshot();
+ }
+ final key = snapshot?.apiKey ?? config.currentApiKey();
if (key.isEmpty) throw const AuthException('API key is required');
out['Authorization'] = 'Bearer $key';
}
_assertGatewayHeaders(out);
- return Map<String, String>.unmodifiable(out);
+ final frozen = Map<String, String>.unmodifiable(out);
+ if (snapshot != null) _credentialSnapshots[frozen] = snapshot;
+ return frozen;
}
Future<Map<String, Object?>> request(
@@ -193,7 +203,18 @@ class VmodalHttp {
final normalized = method.toUpperCase();
final canRetry = normalized == 'GET' || normalized == 'HEAD';
final uri = _uri(path, params, usersApi: usersApi);
- for (var attempt = 0; attempt <= config.normalizedMaxRetries; attempt++) {
+ final provider = config.apiKeyProvider;
+ final tenantProvider = provider is TenantSessionApiKeyProvider
+ ? provider
+ : null;
+ var requestHeaders = headers;
+ var snapshot = _credentialSnapshots[requestHeaders];
+ var recovered = false;
+ var retries = 0;
+ final retryBudget =
+ config.normalizedMaxRetries +
+ (canRetry && tenantProvider != null ? 1 : 0);
+ for (var attempt = 0; attempt <= retryBudget; attempt++) {
cancellation.throwIfCanceled();
final attemptCancellation = CancellationToken();
final removeCancel = cancellation.onCancel(attemptCancellation.cancel);
@@ -201,17 +222,45 @@ class VmodalHttp {
final request = VmodalRequest(
method: normalized,
uri: uri,
- headers: headers,
+ headers: requestHeaders,
jsonBody: json,
formFields: data,
files: files,
responseMode: responseMode,
cancellation: attemptCancellation,
);
+ // Retain this request's headers, but never dispatch after authoritative
+ // revocation or after its session lease has expired.
+ tenantProvider?.snapshot();
final response = await transport.send(request);
+ if (tenantProvider != null && response.statusCode == 401) {
+ await _discard(response, attemptCancellation);
+ cancellation.throwIfCanceled();
+ if (!canRetry ||
+ recovered ||
+ attempt >= retryBudget ||
+ snapshot == null) {
+ throw const TenantAuthException();
+ }
+ recovered = true;
+ await tenantProvider.recover(snapshot.revision);
+ cancellation.throwIfCanceled();
+ requestHeaders = this.headers(
+ forceToken: usersApi,
+ requireUserId: !usersApi,
+ );
+ snapshot = _credentialSnapshots[requestHeaders];
+ continue;
+ }
+ if (tenantProvider != null && response.statusCode == 403) {
+ await _discard(response, attemptCancellation);
+ throw const ApiException('tenant request denied', statusCode: 403);
+ }
if (canRetry &&
const <int>{500, 502, 503, 504}.contains(response.statusCode) &&
- attempt < config.normalizedMaxRetries) {
+ retries < config.normalizedMaxRetries &&
+ attempt < retryBudget) {
+ retries++;
await _discard(response, attemptCancellation);
await _delay(Duration(milliseconds: 50 * (attempt + 1)));
continue;
@@ -222,15 +271,23 @@ class VmodalHttp {
final value = await reader(response, attemptCancellation);
cancellation.throwIfCanceled();
return value;
- } on OperationCanceled {
- if (cancellation.isCanceled) rethrow;
- if (!canRetry || attempt >= config.normalizedMaxRetries) {
+ } on OperationCanceled catch (error) {
+ if (cancellation.isCanceled || error is SessionInvalidated) rethrow;
+ if (!canRetry ||
+ retries >= config.normalizedMaxRetries ||
+ attempt >= retryBudget) {
throw const TransportException();
}
+ retries++;
await _delay(Duration(milliseconds: 50 * (attempt + 1)));
} on TransportException {
if (cancellation.isCanceled) throw const OperationCanceled();
- if (!canRetry || attempt >= config.normalizedMaxRetries) rethrow;
+ if (!canRetry ||
+ retries >= config.normalizedMaxRetries ||
+ attempt >= retryBudget) {
+ rethrow;
+ }
+ retries++;
await _delay(Duration(milliseconds: 50 * (attempt + 1)));
} finally {
removeCancel();
diff --git a/lib/src/session_guard.dart b/lib/src/session_guard.dart
new file mode 100644
index 0000000..3a3d44e
--- /dev/null
+++ b/lib/src/session_guard.dart
@@ -0,0 +1,636 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'errors.dart';
+import 'transport.dart';
+import 'upload.dart';
+
+/// One immutable activation lease shared by preparation, I/O and delivery.
+///
+/// This is an internal mechanism; restricted operations expose neither the
+/// guard nor their underlying transports to applications.
+class SessionGuard {
+ SessionGuard(this.sessionId);
+
+ final String sessionId;
+ bool _active = true;
+ final Set<SessionOperation> _operations = <SessionOperation>{};
+ final List<Object> _cleanupErrors = <Object>[];
+
+ bool get isActive => _active;
+ List<Object> get cleanupErrors => List<Object>.unmodifiable(_cleanupErrors);
+
+ void check() {
+ if (!_active) throw const OperationCanceled();
+ }
+
+ /// Detaches all work before invoking cancellation callbacks, synchronously.
+ void invalidate({void Function()? beforeCancel}) {
+ if (!_active) return;
+ _active = false;
+ final operations = List<SessionOperation>.of(_operations);
+ _operations.clear();
+ // Internal ownership is retired before any transport/user cancellation
+ // callback can reenter the manager or inspect a captured provider.
+ try {
+ beforeCancel?.call();
+ } on Object {
+ _cleanupErrors.add(const TransportException());
+ }
+ for (final operation in operations) {
+ try {
+ operation.token.cancel();
+ } on Object {
+ _cleanupErrors.add(const TransportException());
+ } finally {
+ operation.finish();
+ }
+ }
+ }
+
+ SessionOperation register({CancellationToken? cancellation}) {
+ check();
+ final operation = SessionOperation._(this);
+ _operations.add(operation);
+ operation._removeCaller = cancellation?.onCancel(operation.token.cancel);
+ return operation;
+ }
+
+ Future<T> run<T>(
+ Future<T> Function(CancellationToken cancellation) work, {
+ CancellationToken? cancellation,
+ }) {
+ try {
+ return register(cancellation: cancellation).run(work);
+ } on Object catch (error, stack) {
+ return Future<T>.error(error, stack);
+ }
+ }
+
+ /// Checks at listener delivery, including events buffered while paused.
+ Stream<T> guardStream<T>(
+ Stream<T> source, {
+ CancellationToken? cancellation,
+ }) => _SessionStream<T>(this, source, cancellation);
+}
+
+/// Reserved synchronously, before constructing an eager upload task.
+class SessionOperation {
+ SessionOperation._(this._guard);
+
+ final SessionGuard _guard;
+ final CancellationToken token = CancellationToken();
+ void Function()? _removeCaller;
+ void Function()? _removeCancel;
+ bool _finished = false;
+ bool _started = false;
+
+ void check() {
+ _guard.check();
+ token.throwIfCanceled();
+ }
+
+ /// Settles cancellation promptly even if [work] never cooperates.
+ /// Late errors are observed; an optional disposer releases late results.
+ Future<T> run<T>(
+ Future<T> Function(CancellationToken cancellation) work, {
+ void Function(T value)? disposeLate,
+ }) {
+ if (_started || _finished) {
+ return Future<T>.error(const OperationCanceled());
+ }
+ _started = true;
+ final result = Completer<T>();
+ void cancel() {
+ if (!result.isCompleted) result.completeError(const OperationCanceled());
+ finish();
+ }
+
+ _removeCancel = token.onCancel(cancel);
+ try {
+ check();
+ // No await or host callback between the lease check and invocation.
+ final pending = work(token);
+ unawaited(
+ pending.then<void>(
+ (T value) {
+ if (result.isCompleted || !_guard.isActive || token.isCanceled) {
+ try {
+ disposeLate?.call(value);
+ } on Object {
+ _guard._cleanupErrors.add(const TransportException());
+ }
+ cancel();
+ return;
+ }
+ result.complete(value);
+ finish();
+ },
+ onError: (Object error, StackTrace stack) {
+ if (!result.isCompleted) {
+ if (!_guard.isActive || token.isCanceled) {
+ result.completeError(const OperationCanceled());
+ } else {
+ result.completeError(error, stack);
+ }
+ }
+ finish();
+ },
+ ),
+ );
+ } on Object catch (error, stack) {
+ if (!result.isCompleted) {
+ result.completeError(
+ !_guard.isActive || token.isCanceled
+ ? const OperationCanceled()
+ : error,
+ stack,
+ );
+ }
+ finish();
+ }
+ return result.future;
+ }
+
+ /// Detaches all registry and caller-token listeners on every terminal path.
+ void finish() {
+ if (_finished) return;
+ _finished = true;
+ _removeCaller?.call();
+ _removeCancel?.call();
+ _guard._operations.remove(this);
+ }
+}
+
+class _SessionStream<T> extends Stream<T> {
+ _SessionStream(this.guard, this.source, this.cancellation);
+
+ final SessionGuard guard;
+ final Stream<T> source;
+ final CancellationToken? cancellation;
+
+ @override
+ bool get isBroadcast => source.isBroadcast;
+
+ @override
+ StreamSubscription<T> listen(
+ void Function(T event)? onData, {
+ Function? onError,
+ void Function()? onDone,
+ bool? cancelOnError,
+ }) {
+ SessionOperation operation;
+ try {
+ operation = guard.register(cancellation: cancellation);
+ } on Object catch (error, stack) {
+ // A response may have completed before invalidation but remained
+ // unconsumed. Even this late listener must dispose its captured source.
+ try {
+ final discarded = source.listen((_) {}, onError: (Object _) {});
+ unawaited(
+ Future<void>.sync(discarded.cancel).catchError((Object _) {
+ guard._cleanupErrors.add(const TransportException());
+ }),
+ );
+ } on Object {
+ guard._cleanupErrors.add(const TransportException());
+ }
+ return Stream<T>.error(error, stack).listen(
+ onData,
+ onError: onError,
+ onDone: onDone,
+ cancelOnError: cancelOnError,
+ );
+ }
+ StreamSubscription<T>? upstream;
+ var stopped = false;
+ var canceledDelivered = false;
+ void Function(T)? listenerData = onData;
+ Function? listenerError = onError;
+ void Function()? listenerDone = onDone;
+ void Function() removeCancel = () {};
+ late final StreamController<T> output;
+ void stop() {
+ if (stopped) return;
+ stopped = true;
+ removeCancel();
+ operation.finish();
+ final subscription = upstream;
+ if (subscription != null) {
+ unawaited(
+ Future<void>.sync(subscription.cancel).catchError((Object error) {
+ guard._cleanupErrors.add(const TransportException());
+ }),
+ );
+ }
+ }
+
+ output = StreamController<T>(
+ sync: true,
+ onCancel: stop,
+ onPause: () => upstream?.pause(),
+ onResume: () => upstream?.resume(),
+ );
+ removeCancel = operation.token.onCancel(() {
+ if (stopped) return;
+ stop();
+ // Invalidation may be reentrant from the user's onData callback.
+ scheduleMicrotask(() {
+ if (output.isClosed) return;
+ output.addError(const OperationCanceled());
+ unawaited(output.close());
+ });
+ });
+ // A paused output may hold events accepted before invalidation. Checking
+ // inside these callbacks ensures those events never reach the listener.
+ // Ownership is transferred to the returned subscription wrapper.
+ // ignore: cancel_subscriptions
+ final downstream = output.stream.listen(
+ (T value) {
+ if (guard.isActive && !operation.token.isCanceled) {
+ listenerData?.call(value);
+ }
+ },
+ onError: (Object error, StackTrace stack) {
+ final stale = !guard.isActive || operation.token.isCanceled;
+ if (stale && canceledDelivered) return;
+ if (stale) canceledDelivered = true;
+ final safe = stale ? const OperationCanceled() : error;
+ final handler = listenerError;
+ if (handler is void Function(Object, StackTrace)) {
+ handler(safe, stack);
+ } else if (handler is void Function(Object)) {
+ handler(safe);
+ } else {
+ Zone.current.handleUncaughtError(safe, stack);
+ }
+ },
+ onDone: () {
+ removeCancel();
+ stop();
+ listenerDone?.call();
+ },
+ cancelOnError: cancelOnError,
+ );
+ if (!stopped) {
+ upstream = source.listen(
+ (T value) {
+ if (!stopped) output.add(value);
+ },
+ onError: (Object error, StackTrace stack) {
+ if (!stopped) output.addError(error, stack);
+ },
+ onDone: () {
+ if (!stopped) unawaited(output.close());
+ },
+ );
+ // A synchronous source/listener can invalidate during listen itself.
+ if (stopped) {
+ unawaited(
+ Future<void>.sync(upstream.cancel).catchError((Object error) {
+ guard._cleanupErrors.add(const TransportException());
+ }),
+ );
+ }
+ }
+ return _SessionSubscription<T>(
+ downstream,
+ (handler) => listenerData = handler,
+ (handler) => listenerError = handler,
+ (handler) => listenerDone = handler,
+ );
+ }
+}
+
+// Keep the delivery fence when a caller changes a subscription's callbacks.
+class _SessionSubscription<T> implements StreamSubscription<T> {
+ _SessionSubscription(
+ this.delegate,
+ this.setData,
+ this.setError,
+ this.setDone,
+ );
+
+ final StreamSubscription<T> delegate;
+ final void Function(void Function(T)?) setData;
+ final void Function(Function?) setError;
+ final void Function(void Function()?) setDone;
+
+ @override
+ Future<void> cancel() => delegate.cancel();
+ @override
+ bool get isPaused => delegate.isPaused;
+ @override
+ void pause([Future<void>? resumeSignal]) => delegate.pause(resumeSignal);
+ @override
+ void resume() => delegate.resume();
+ @override
+ void onData(void Function(T)? handleData) => setData(handleData);
+ @override
+ void onError(Function? handleError) => setError(handleError);
+ @override
+ void onDone(void Function()? handleDone) => setDone(handleDone);
+ @override
+ Future<E> asFuture<E>([E? futureValue]) {
+ final result = Completer<E>();
+ onDone(() => result.complete(futureValue));
+ onError((Object error, StackTrace stack) {
+ unawaited(
+ cancel().then(
+ (_) => result.completeError(error, stack),
+ onError: (Object _, StackTrace _) =>
+ result.completeError(error, stack),
+ ),
+ );
+ });
+ return result.future;
+ }
+}
+
+/// Fences every gateway attempt and both request and response byte streams.
+class GuardedVmodalTransport implements VmodalTransport {
+ GuardedVmodalTransport(this.guard, this.delegate);
+
+ final SessionGuard guard;
+ final VmodalTransport delegate;
+ Future<void>? _closeFuture;
+
+ @override
+ Future<VmodalResponse> send(VmodalRequest request) {
+ SessionOperation operation;
+ try {
+ operation = guard.register(cancellation: request.cancellation);
+ } on Object catch (error, stack) {
+ return Future<VmodalResponse>.error(error, stack);
+ }
+ VmodalResponse? originalResponse;
+ return operation.run<VmodalResponse>((CancellationToken token) {
+ final captured = VmodalRequest(
+ method: request.method,
+ uri: request.uri,
+ headers: Map<String, String>.unmodifiable(request.headers),
+ jsonBody: request.jsonBody,
+ formFields: Map<String, Object?>.unmodifiable(request.formFields),
+ files: List<VmodalFilePart>.unmodifiable(
+ request.files.map(
+ (part) => VmodalFilePart(
+ fieldName: part.fieldName,
+ fileName: part.fileName,
+ contentLength: part.contentLength,
+ contentType: part.contentType,
+ opener: () {
+ guard.check();
+ token.throwIfCanceled();
+ return guard.guardStream(part.open(), cancellation: token);
+ },
+ ),
+ ),
+ ),
+ responseMode: request.responseMode,
+ cancellation: token,
+ );
+ operation.check();
+ return delegate.send(captured).then((VmodalResponse response) {
+ originalResponse = response;
+ if (!guard.isActive || token.isCanceled) {
+ _discardResponse(response);
+ throw const OperationCanceled();
+ }
+ return VmodalResponse(
+ statusCode: response.statusCode,
+ body: guard.guardStream(
+ response.body,
+ cancellation: request.cancellation,
+ ),
+ headers: Map<String, String>.unmodifiable(response.headers),
+ contentLength: response.contentLength,
+ );
+ });
+ }, disposeLate: (_) => _discardResponse(originalResponse!));
+ }
+
+ void _discardResponse(VmodalResponse response) {
+ try {
+ final subscription = response.body.listen((_) {}, onError: (Object _) {});
+ unawaited(
+ Future<void>.sync(subscription.cancel).catchError((Object _) {
+ guard._cleanupErrors.add(const TransportException());
+ }),
+ );
+ } on Object {
+ guard._cleanupErrors.add(const TransportException());
+ }
+ }
+
+ @override
+ Future<void> close() {
+ final pending = _closeFuture;
+ if (pending != null) return pending;
+ final result = Completer<void>();
+ _closeFuture = result.future;
+ unawaited(
+ Future<void>.sync(
+ delegate.close,
+ ).then(result.complete, onError: result.completeError),
+ );
+ return result.future;
+ }
+}
+
+/// Signed storage attempts never resolve a replacement session or credential.
+class GuardedSignedUploadTransport implements SignedUploadTransport {
+ GuardedSignedUploadTransport(this.guard, this.delegate);
+
+ final SessionGuard guard;
+ final SignedUploadTransport delegate;
+ Future<void>? _closeFuture;
+
+ @override
+ Future<SignedUploadResult> upload({
+ required UploadSource source,
+ required Uri url,
+ String method = 'PUT',
+ int offset = 0,
+ int? length,
+ Map<String, String> headers = const <String, String>{},
+ Duration? timeout,
+ required CancellationToken cancellation,
+ void Function(UploadProgress progress)? onProgress,
+ }) => guard.run((CancellationToken token) {
+ final guardedSource = UploadSource(
+ fileName: source.fileName,
+ contentLength: source.contentLength,
+ contentType: source.contentType,
+ sourceId: source.sourceId,
+ versionTag: source.versionTag,
+ localFile: source.localFile,
+ opener: () {
+ guard.check();
+ token.throwIfCanceled();
+ return guard.guardStream(source.open(), cancellation: token);
+ },
+ rangeOpener: (int offset) {
+ guard.check();
+ token.throwIfCanceled();
+ return guard.guardStream(
+ source.open(offset: offset),
+ cancellation: token,
+ );
+ },
+ );
+ final capturedHeaders = Map<String, String>.unmodifiable(headers);
+ guard.check();
+ token.throwIfCanceled();
+ return delegate.upload(
+ source: guardedSource,
+ url: url,
+ method: method,
+ offset: offset,
+ length: length,
+ headers: capturedHeaders,
+ timeout: timeout,
+ cancellation: token,
+ onProgress: (UploadProgress value) {
+ if (guard.isActive && !token.isCanceled) onProgress?.call(value);
+ },
+ );
+ }, cancellation: cancellation);
+
+ @override
+ Future<void> close() {
+ final pending = _closeFuture;
+ if (pending != null) return pending;
+ final result = Completer<void>();
+ _closeFuture = result.future;
+ unawaited(
+ Future<void>.sync(
+ delegate.close,
+ ).then(result.complete, onError: result.completeError),
+ );
+ return result.future;
+ }
+}
+
+/// Single-isolate commit barrier shared by all owner adapters and controllers.
+/// An accepted non-cancelable custom-store mutation holds the namespace closed
+/// to subsequent writers/readers until it finishes. Cross-isolate/process use
+/// requires a storage implementation with its own transactional lock.
+class OwnerCommitCoordinator {
+ OwnerCommitCoordinator._();
+ static final OwnerCommitCoordinator shared = OwnerCommitCoordinator._();
+ final Map<String, _OwnerCommitSlot> _slots = {};
+
+ OwnerWriterLease open(String namespace, SessionGuard guard) {
+ guard.check();
+ final slot = _slots.putIfAbsent(namespace, _OwnerCommitSlot.new);
+ final current = slot.writer;
+ if (current != null &&
+ identical(current.guard, guard) &&
+ !current.retired) {
+ return current;
+ }
+ current?.retire();
+ final writer = OwnerWriterLease._(slot, guard);
+ slot.writer = writer;
+ return writer;
+ }
+}
+
+class _OwnerCommitSlot {
+ OwnerWriterLease? writer;
+ Future<void> tail = Future<void>.value();
+}
+
+/// A fresh activation owns this namespace; returning to A retires old A writes.
+class OwnerWriterLease {
+ OwnerWriterLease._(this._slot, this.guard);
+ final _OwnerCommitSlot _slot;
+ final SessionGuard guard;
+ bool retired = false;
+
+ void retire() => retired = true;
+ void check() {
+ guard.check();
+ if (retired || !identical(_slot.writer, this)) {
+ throw const OperationCanceled();
+ }
+ }
+
+ Future<T> run<T>(Future<T> Function() work) {
+ try {
+ check();
+ } on Object catch (error, stack) {
+ return Future<T>.error(error, stack);
+ }
+ final pending = _slot.tail.then((_) async {
+ check();
+ final value = await work();
+ check();
+ return value;
+ });
+ // Observe failures without hiding them from the initiating caller.
+ _slot.tail = pending.then<void>(
+ (_) {},
+ onError: (Object _, StackTrace _) {},
+ );
+ return pending;
+ }
+}
+
+/// Stable owner/policy envelope around existing multipart checkpoint storage.
+/// The key never includes tenant credentials or the runtime session identity.
+class OwnerUploadSessionStore implements UploadSessionStore {
+ OwnerUploadSessionStore({
+ required SessionGuard guard,
+ required this.ownerKey,
+ required this.scopeKey,
+ required this.policyRevision,
+ UploadSessionStore? delegate,
+ }) : _delegate = delegate ?? UploadSessionStores.memory,
+ _writer = OwnerCommitCoordinator.shared.open(
+ 'multipart:$scopeKey',
+ guard,
+ );
+
+ final String ownerKey, scopeKey, policyRevision;
+ final UploadSessionStore _delegate;
+ final OwnerWriterLease _writer;
+
+ String _key(String contractKey) => jsonEncode([scopeKey, contractKey]);
+
+ Map<String, Object?> _snapshot(Map<String, Object?> value) =>
+ Map<String, Object?>.from(jsonDecode(jsonEncode(value)) as Map);
+
+ @override
+ Future<Map<String, Object?>?> load(String key) => _writer.run(() async {
+ final value = await _delegate.load(_key(key));
+ _writer.check();
+ if (value == null ||
+ value['ownerKey'] != ownerKey ||
+ value['scopeKey'] != scopeKey ||
+ value['policyRevision'] != policyRevision ||
+ value['contractKey'] != key ||
+ value['checkpoint'] is! Map) {
+ return null;
+ }
+ return _snapshot(Map<String, Object?>.from(value['checkpoint'] as Map));
+ });
+
+ @override
+ Future<void> save(String key, Map<String, Object?> value) {
+ final snapshot = _snapshot(value);
+ return _writer.run(
+ () => _delegate.save(_key(key), {
+ 'ownerKey': ownerKey,
+ 'scopeKey': scopeKey,
+ 'policyRevision': policyRevision,
+ 'contractKey': key,
+ 'checkpoint': snapshot,
+ }),
+ );
+ }
+
+ @override
+ Future<void> remove(String key) =>
+ _writer.run(() => _delegate.remove(_key(key)));
+}
diff --git a/lib/src/transport.dart b/lib/src/transport.dart
index 2d1880a..b930d46 100644
--- a/lib/src/transport.dart
+++ b/lib/src/transport.dart
@@ -36,9 +36,17 @@ class CancellationToken {
_abort.complete();
final callbacks = List<void Function()>.from(_callbacks);
_callbacks.clear();
+ Object? failure;
+ StackTrace? trace;
for (final callback in callbacks) {
- callback();
+ try {
+ callback();
+ } on Object catch (error, stack) {
+ failure ??= error;
+ trace ??= stack;
+ }
}
+ if (failure != null) Error.throwWithStackTrace(failure, trace!);
}
/// @nodoc
diff --git a/lib/src/upload.dart b/lib/src/upload.dart
index b27f61f..62a332b 100644
--- a/lib/src/upload.dart
+++ b/lib/src/upload.dart
@@ -249,9 +249,14 @@ class UploadTask<T> {
void cancel() {
if (_state != UploadTaskState.running) return;
_state = UploadTaskState.canceled;
- cancellation.cancel();
- if (!_result.isCompleted) _result.completeError(const OperationCanceled());
- unawaited(_progress.close());
+ try {
+ cancellation.cancel();
+ } finally {
+ if (!_result.isCompleted) {
+ _result.completeError(const OperationCanceled());
+ }
+ unawaited(_progress.close());
+ }
}
Future<void> _start(UploadRunner<T> runner) async {
diff --git a/lib/src/user_session.dart b/lib/src/user_session.dart
new file mode 100644
index 0000000..ccc5e5a
--- /dev/null
+++ b/lib/src/user_session.dart
@@ -0,0 +1,1318 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:math';
+import 'dart:typed_data';
+
+import 'package:crypto/crypto.dart';
+
+import 'api_key_provider.dart';
+import 'client.dart';
+import 'collection_uploads.dart';
+import 'config.dart';
+import 'content_scope.dart';
+import 'errors.dart';
+import 'models.dart';
+import 'session_guard.dart';
+import 'transcode.dart';
+import 'transport.dart';
+import 'upload.dart';
+import 'utils.dart';
+import 'vmodal.dart';
+
+/// Local permitted operations. These are client guardrails, not server grants.
+enum UserAction {
+ discover,
+ search,
+ upload,
+ metadata,
+ indexation,
+ delete,
+ media,
+}
+
+/// Explicit mapping representation; opaque selectors are never prefixed.
+enum ScopeRepresentation { logical, opaque }
+
+/// A live resource minted by a validated operation. It expires on session close.
+final class SessionAsset {
+ SessionAsset._(
+ this._sessionId,
+ this._scopeKey,
+ this.assetId,
+ this.fileName,
+ this._media,
+ );
+ final String _sessionId;
+ final String _scopeKey;
+ final String? assetId;
+ final String? fileName;
+ final Map<String, Object?> _media;
+}
+
+/// Safe search data; media selectors and raw service capabilities stay private.
+final class SessionSearchResponse extends SearchResponse {
+ SessionSearchResponse._(super.raw, Iterable<SessionAsset> assets)
+ : assets = List<SessionAsset>.unmodifiable(assets);
+ final List<SessionAsset> assets;
+}
+
+/// Safe upload summary and its optional owner-bound asset handle.
+final class SessionUploadResponse extends VideoUploadResponse {
+ SessionUploadResponse._(super.raw, this.asset);
+ final SessionAsset? asset;
+}
+
+/// Live job provenance, created or discovered within an exact allowed stream.
+final class SessionJob extends IndexationSubmitResponse {
+ SessionJob._(super.raw, this._sessionId, this._scopeKey, this._reference);
+ final String _sessionId;
+ final String _scopeKey;
+ final DurableJobReference _reference;
+ DurableJobReference toDurableReference() => _reference;
+}
+
+/// Serializable ownership metadata, never sufficient by itself to prove a job.
+final class DurableJobReference {
+ const DurableJobReference({
+ required this.jobId,
+ required this.ownerKey,
+ required this.scopeKey,
+ required this.policyRevision,
+ });
+ final String jobId;
+ final String ownerKey;
+ final String scopeKey;
+ final String policyRevision;
+}
+
+/// A frozen host-authenticated mapping to one exact backend stream and mode.
+final class ContentMapping {
+ ContentMapping._({
+ required this.representation,
+ required this.collectionId,
+ required this.streamName,
+ required this.mode,
+ required Set<UserAction> actions,
+ required this.collectionWide,
+ this.projectId,
+ this.collectionName,
+ }) : actions = Set<UserAction>.unmodifiable(actions);
+
+ factory ContentMapping.logical({
+ required String projectId,
+ required String collectionName,
+ required String streamName,
+ String mode = 'vid_file',
+ Set<UserAction> actions = const <UserAction>{UserAction.search},
+ bool collectionWide = false,
+ }) {
+ final scope = ContentScope.create(projectId, collectionName, streamName);
+ return ContentMapping._(
+ representation: ScopeRepresentation.logical,
+ collectionId: scope.backendCollectionName,
+ projectId: scope.projectId,
+ collectionName: scope.collectionName,
+ streamName: scope.streamName,
+ mode: strRequired(mode, 'mode'),
+ actions: actions,
+ collectionWide: collectionWide,
+ );
+ }
+
+ factory ContentMapping.opaque({
+ required String collectionId,
+ required String streamName,
+ String mode = 'vid_file',
+ Set<UserAction> actions = const <UserAction>{UserAction.search},
+ bool collectionWide = false,
+ }) => ContentMapping._(
+ representation: ScopeRepresentation.opaque,
+ collectionId: strRequired(collectionId, 'collectionId'),
+ streamName: strRequired(streamName, 'streamName'),
+ mode: strRequired(mode, 'mode'),
+ actions: actions,
+ collectionWide: collectionWide,
+ );
+
+ final ScopeRepresentation representation;
+ final String collectionId;
+ final String streamName;
+ final String mode;
+ final String? projectId;
+ final String? collectionName;
+ final Set<UserAction> actions;
+ final bool collectionWide;
+
+ String get _selector => jsonEncode(<Object?>[
+ representation.name,
+ collectionId,
+ streamName,
+ mode,
+ ]);
+
+ List<Object?> get _policy => <Object?>[
+ _selector,
+ (actions.map((value) => value.name).toList()..sort()),
+ collectionWide,
+ ];
+}
+
+/// Identity and policy resolved by the host from its authenticated app user.
+final class UserSessionPolicy {
+ UserSessionPolicy({
+ required this.tenantId,
+ required this.appUserId,
+ required Iterable<ContentMapping> allowedContentMapping,
+ this.policyRevision,
+ }) : allowedContentMapping = List<ContentMapping>.unmodifiable(
+ allowedContentMapping,
+ ) {
+ strRequired(tenantId, 'tenantId');
+ strRequired(appUserId, 'appUserId');
+ }
+
+ final String tenantId;
+ final String appUserId;
+ final List<ContentMapping> allowedContentMapping;
+ final String? policyRevision;
+}
+
+/// Immutable ownership. Stable keys deliberately exclude credential versions.
+final class SessionContext {
+ SessionContext._(this.serviceNamespace, UserSessionPolicy policy)
+ : tenantId = policy.tenantId,
+ appUserId = policy.appUserId,
+ allowedContentMapping = policy.allowedContentMapping,
+ policyRevision = policy.policyRevision ?? _revision(policy),
+ ownerKey = jsonEncode(<String>[
+ serviceNamespace,
+ policy.tenantId,
+ policy.appUserId,
+ ]);
+
+ final String serviceNamespace;
+ final String tenantId;
+ final String appUserId;
+ final String policyRevision;
+ final String ownerKey;
+ final List<ContentMapping> allowedContentMapping;
+
+ String scopeKey(ContentMapping mapping) => jsonEncode(<String>[
+ ownerKey,
+ mapping.representation.name,
+ mapping.collectionId,
+ mapping.streamName,
+ mapping.mode,
+ ]);
+
+ /// Canonical connection namespace, including the normalized gateway path.
+ static String serviceNamespaceFor(SdkConfig config) {
+ final uri = Uri.parse(config.normalizedBaseUrl);
+ if (uri.hasQuery || uri.hasFragment) {
+ throw const ValidationException(
+ 'User-session service URLs cannot contain a query or fragment',
+ );
+ }
+ return uri
+ .replace(scheme: uri.scheme.toLowerCase(), host: uri.host.toLowerCase())
+ .normalizePath()
+ .toString();
+ }
+
+ static String _revision(UserSessionPolicy policy) {
+ final mappings = policy.allowedContentMapping.map((m) => m._policy).toList()
+ ..sort((a, b) => jsonEncode(a).compareTo(jsonEncode(b)));
+ return sha256.convert(utf8.encode(jsonEncode(mappings))).toString();
+ }
+}
+
+/// One active application identity flow using a shared tenant credential.
+final class UserSessionManager {
+ UserSessionManager({
+ required SdkConfig config,
+ required TenantCredentialSource credentialSource,
+ VmodalTransport Function(SdkConfig config)? transportFactory,
+ SignedUploadTransport Function(SdkConfig config)?
+ signedUploadTransportFactory,
+ UploadSessionStore? uploadSessionStore,
+ this.onInvalidated,
+ }) : _config = config,
+ _credentials = credentialSource,
+ _uploadSessionStore = uploadSessionStore,
+ _transportFactory = transportFactory ?? HttpVmodalTransport.new,
+ _signedFactory =
+ signedUploadTransportFactory ??
+ ((config) => IoSignedUploadTransport(config.timeout)) {
+ if (config.normalizedMode != 'gateway') {
+ throw const ValidationException('User sessions require gateway mode');
+ }
+ if (credentialSource.serviceNamespace !=
+ SessionContext.serviceNamespaceFor(config)) {
+ throw const ValidationException(
+ 'Credential service binding does not match',
+ );
+ }
+ }
+
+ final SdkConfig _config;
+ final TenantCredentialSource _credentials;
+ final UploadSessionStore? _uploadSessionStore;
+ final VmodalTransport Function(SdkConfig) _transportFactory;
+ final SignedUploadTransport Function(SdkConfig) _signedFactory;
+ final void Function(UserSession session)? onInvalidated;
+ static final Expando<bool> _usedTransports = Expando<bool>(
+ 'session transports',
+ );
+ final List<Object> _cleanupErrors = <Object>[];
+ List<Object> get cleanupErrors => List<Object>.unmodifiable(_cleanupErrors);
+ UserSession? _current;
+ int _ticket = 0;
+ bool _closed = false;
+ Future<void>? _closeFuture;
+
+ UserSession? get current => _current?.isActive == true ? _current : null;
+
+ Future<UserSession> openUserSession({
+ required String tenantId,
+ required String appUserId,
+ required Iterable<ContentMapping> allowedContentMapping,
+ String? policyRevision,
+ }) {
+ final policy = UserSessionPolicy(
+ tenantId: tenantId,
+ appUserId: appUserId,
+ allowedContentMapping: allowedContentMapping,
+ policyRevision: policyRevision,
+ );
+ return openResolvedSession(() async => policy);
+ }
+
+ /// Invalidates the outgoing user before resolving any new identity or policy.
+ Future<UserSession> openResolvedSession(
+ Future<UserSessionPolicy> Function() resolve,
+ ) async {
+ if (_closed) throw const OperationCanceled();
+ final ticket = ++_ticket;
+ final old = _current;
+ _current = null;
+ if (old != null) _observeClose(old.close());
+ _checkTicket(ticket);
+ final policy = await resolve();
+ _checkTicket(ticket);
+ if (policy.tenantId != _credentials.tenantId) {
+ throw const ValidationException(
+ 'Credential tenant binding does not match',
+ );
+ }
+ final context = SessionContext._(
+ SessionContext.serviceNamespaceFor(_config),
+ policy,
+ );
+ final selectors = <String>{};
+ for (final mapping in context.allowedContentMapping) {
+ if (!selectors.add(mapping._selector)) {
+ throw const ValidationException('Duplicate content mapping');
+ }
+ }
+ final id = base64UrlEncode(
+ List<int>.generate(24, (_) => Random.secure().nextInt(256)),
+ );
+ final guard = SessionGuard(id);
+ final provider = _credentials.createProvider(
+ isActive: () => guard.isActive,
+ );
+ final config = SdkConfig(
+ baseUrl: _config.baseUrl,
+ timeout: _config.timeout,
+ idleTimeout: _config.idleTimeout,
+ maxRetries: _config.maxRetries,
+ apiKeyProvider: provider,
+ );
+ VmodalTransport? gateway;
+ SignedUploadTransport? signed;
+ try {
+ gateway = _transportFactory(config);
+ if (_usedTransports[gateway] == true) {
+ gateway = null;
+ throw const ValidationException('Session transports must be distinct');
+ }
+ _usedTransports[gateway] = true;
+ _checkTicket(ticket);
+ signed = _signedFactory(config);
+ if (_usedTransports[signed] == true) {
+ signed = null;
+ throw const ValidationException('Session transports must be distinct');
+ }
+ _usedTransports[signed] = true;
+ _checkTicket(ticket);
+ final client = VmodalClient(
+ config: config,
+ transport: GuardedVmodalTransport(guard, gateway),
+ signedUploadTransport: GuardedSignedUploadTransport(guard, signed),
+ );
+ final session = UserSession._(
+ context,
+ _credentials.expectedPrincipal,
+ guard,
+ provider,
+ client,
+ _uploadSessionStore,
+ (session) {
+ if (identical(_current, session) && ticket == _ticket) {
+ _current = null;
+ }
+ onInvalidated?.call(session);
+ },
+ );
+ _checkTicket(ticket);
+ _current = session;
+ return session;
+ } on Object {
+ guard.invalidate();
+ provider.close();
+ if (gateway != null) _observeClose(Future<void>.sync(gateway.close));
+ if (signed != null) _observeClose(Future<void>.sync(signed.close));
+ rethrow;
+ }
+ }
+
+ Future<void> logout() {
+ ++_ticket;
+ final old = _current;
+ _current = null;
+ return old?.close() ?? Future<void>.value();
+ }
+
+ Future<void> close() {
+ if (_closeFuture != null) return _closeFuture!;
+ final done = Completer<void>();
+ _closeFuture = done.future;
+ _closed = true;
+ unawaited(logout().then(done.complete, onError: done.completeError));
+ return done.future;
+ }
+
+ void _checkTicket(int ticket) {
+ if (_closed || ticket != _ticket) throw const OperationCanceled();
+ }
+
+ void _observeClose(Future<void> future) {
+ unawaited(
+ future.catchError((Object _) {
+ _cleanupErrors.add(const TransportException());
+ }),
+ );
+ }
+}
+
+/// Private resources and a fresh runtime lease for one app-user activation.
+final class UserSession {
+ UserSession._(
+ this.context,
+ this._expectedPrincipal,
+ this._guard,
+ this._provider,
+ this._client,
+ this._uploadStore,
+ this._onInvalidated,
+ );
+
+ final SessionContext context;
+ final String _expectedPrincipal;
+ final SessionGuard _guard;
+ final MutableApiKeyProvider _provider;
+ final VmodalClient _client;
+ final void Function(UserSession) _onInvalidated;
+ final UploadSessionStore? _uploadStore;
+ final Set<SessionAsset> _assets = <SessionAsset>{};
+ final Set<SessionJob> _jobs = <SessionJob>{};
+ final List<Object> _cleanupErrors = <Object>[];
+ List<Object> get cleanupErrors => List<Object>.unmodifiable(_cleanupErrors);
+ Future<void>? _closeFuture;
+
+ String get sessionId => _guard.sessionId;
+ bool get isActive => _guard.isActive;
+
+ /// Resolves the tenant principal without turning it into app-user identity.
+ Future<void> verifyPrincipal(
+ String expectedPrincipal, {
+ CancellationToken? cancellation,
+ }) => _run((token) async {
+ if (expectedPrincipal != _expectedPrincipal) {
+ throw const ValidationException(
+ 'Tenant principal binding does not match',
+ );
+ }
+ final profile = await _client.auth.me(cancellation: token);
+ _guard.check();
+ if (profile.userId != _expectedPrincipal) {
+ throw const ValidationException('Tenant principal does not match');
+ }
+ }, cancellation: cancellation);
+
+ /// Discovery returns mapping selectors only, with no tenant metadata or count.
+ Future<List<ContentMapping>> listCollections({
+ CancellationToken? cancellation,
+ }) {
+ _guard.check();
+ final mapped = context.allowedContentMapping
+ .where((m) => m.actions.contains(UserAction.discover))
+ .toList();
+ return _run((token) async {
+ final response = await _client.collections.listGroups(
+ cancellation: token,
+ );
+ _guard.check();
+ return List<ContentMapping>.unmodifiable(
+ mapped.where(
+ (mapping) => response.data.any(
+ (row) =>
+ row.groupName == mapping.collectionId &&
+ row.mode == mapping.mode,
+ ),
+ ),
+ );
+ }, cancellation: cancellation);
+ }
+
+ Future<T> _run<T>(
+ Future<T> Function(CancellationToken) work, {
+ CancellationToken? cancellation,
+ }) => _guard.run(
+ (token) => _safeWork(() => work(token)),
+ cancellation: cancellation,
+ );
+
+ UserScope scope(ContentMapping requested) {
+ _guard.check();
+ final allowed = context.allowedContentMapping.where(
+ (m) => m._selector == requested._selector,
+ );
+ if (allowed.isEmpty) {
+ throw const ValidationException('Scope is not allowed');
+ }
+ return UserScope._(this, allowed.first);
+ }
+
+ /// Invalidates synchronously; callbacks and asynchronous disposal follow.
+ Future<void> close() {
+ if (_closeFuture != null) return _closeFuture!;
+ final done = Completer<void>();
+ _closeFuture = done.future;
+ _guard.invalidate(
+ beforeCancel: () {
+ _provider.close();
+ _assets.clear();
+ _jobs.clear();
+ },
+ );
+ _cleanupErrors.addAll(_guard.cleanupErrors);
+ // Initiate captured resource disposal before notifying the host. The
+ // callback may synchronously open a newer session or reenter close().
+ final closing = Future<void>.sync(_client.close);
+ try {
+ _onInvalidated(this);
+ } on Object {
+ _cleanupErrors.add(
+ const SdkException('Session notification cleanup failed'),
+ );
+ }
+ unawaited(
+ closing.then(
+ done.complete,
+ onError: (Object _, StackTrace _) {
+ const failure = TransportException();
+ _cleanupErrors.add(failure);
+ done.completeError(failure);
+ },
+ ),
+ );
+ return done.future;
+ }
+}
+
+/// An owner-bound host storage barrier, retired by logout or host deactivation.
+/// Host code must capture its path/payload and check before publishing files.
+final class SessionStorageLease {
+ SessionStorageLease._(this._writer);
+ final OwnerWriterLease _writer;
+ String get sessionId => _writer.guard.sessionId;
+ void check() => _writer.check();
+ void retire() => _writer.retire();
+ Future<T> run<T>(Future<T> Function() work) =>
+ _writer.guard.run((_) => _writer.run(work));
+}
+
+/// Restricted operations bound to a frozen mapping and originating session.
+final class UserScope {
+ UserScope._(this._session, this.mapping);
+
+ final UserSession _session;
+ final ContentMapping mapping;
+ late final OwnerUploadSessionStore _uploadStore = OwnerUploadSessionStore(
+ guard: _session._guard,
+ ownerKey: _session.context.ownerKey,
+ scopeKey: scopeKey,
+ policyRevision: _session.context.policyRevision,
+ delegate: _session._uploadStore,
+ );
+ String get sessionId => _session.sessionId;
+ String get scopeKey => _session.context.scopeKey(mapping);
+
+ /// A captured owner barrier for host archive writes. It shares the session
+ /// lifetime and never exposes a transport, credential or mutable guard.
+ SessionStorageLease get storageLease {
+ _session._guard.check();
+ return SessionStorageLease._(
+ OwnerCommitCoordinator.shared.open(
+ 'archive:${jsonEncode([_session.context.ownerKey, mapping.collectionId])}',
+ _session._guard,
+ ),
+ );
+ }
+
+ void _allow(UserAction action, String mode) {
+ _session._guard.check();
+ if (!mapping.actions.contains(action) || mode != mapping.mode) {
+ throw const ValidationException('Action or mode is not allowed');
+ }
+ }
+
+ bool _matches(Map<String, Object?> row, {required bool requireSelectors}) {
+ for (final field in <String, String>{
+ 'group_name': mapping.collectionId,
+ 'stream_name': mapping.streamName,
+ 'mode': mapping.mode,
+ }.entries) {
+ if (!row.containsKey(field.key)) {
+ if (requireSelectors) return false;
+ } else if (row[field.key] != field.value) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ SessionAsset _asset(Map<String, Object?> row) {
+ _session._guard.check();
+ final file =
+ stringValueOrNull(row['video_filename']) ??
+ stringValueOrNull(row['filename_sanitized']) ??
+ stringValueOrNull(row['filename']) ??
+ stringValueOrNull(row['file_name']);
+ final safeFile =
+ file != null &&
+ !file.contains('/') &&
+ !file.contains('\\') &&
+ file != '.' &&
+ file != '..'
+ ? file
+ : null;
+ final asset = SessionAsset._(
+ sessionId,
+ scopeKey,
+ stringValueOrNull(row['asset_id']),
+ safeFile,
+ _fields(row, const <String>{
+ 'modality',
+ 'ts_unix_13digits',
+ 'playback_offset_ms',
+ 'video_time_seconds',
+ 'timestamp_seconds',
+ }),
+ );
+ _session._assets.add(asset);
+ return asset;
+ }
+
+ SessionJob _job(Map<String, Object?> row) {
+ _session._guard.check();
+ final id = strRequired('${row['job_id'] ?? ''}', 'job_id');
+ final job = SessionJob._(
+ _fields(row, _jobFields),
+ sessionId,
+ scopeKey,
+ DurableJobReference(
+ jobId: id,
+ ownerKey: _session.context.ownerKey,
+ scopeKey: scopeKey,
+ policyRevision: _session.context.policyRevision,
+ ),
+ );
+ _session._jobs.add(job);
+ return job;
+ }
+
+ void _checkAsset(SessionAsset asset) {
+ _session._guard.check();
+ if (asset._sessionId != sessionId ||
+ asset._scopeKey != scopeKey ||
+ !_session._assets.contains(asset)) {
+ throw const ValidationException('Asset provenance does not match');
+ }
+ }
+
+ /// Every batch member must come from this exact live scope before dispatch.
+ Future<CollectionAddAssetsResponse> addAssets(
+ List<SessionAsset> assets, {
+ ScopedAddAssetsOptions options = const ScopedAddAssetsOptions(),
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.metadata, options.mode);
+ final captured = List<SessionAsset>.of(assets);
+ for (final asset in captured) {
+ _checkAsset(asset);
+ if (asset.assetId == null) {
+ throw const ValidationException('Asset has no stable identifier');
+ }
+ }
+ return _session._run(
+ (token) async => CollectionAddAssetsResponse(
+ _fields(
+ (await _session._client.collections.addAssets(
+ collectionId: mapping.collectionId,
+ assetIds: captured.map((a) => a.assetId!).toList(),
+ mode: mapping.mode,
+ groupName: mapping.collectionId,
+ streamName: mapping.streamName,
+ cancellation: token,
+ )).raw,
+ const <String>{'status', 'added', 'updated'},
+ ),
+ ),
+ cancellation: cancellation,
+ );
+ }
+
+ /// Mutates a filename minted by a scoped search or completed upload.
+ Future<CollectionDescriptionUpdateResponse> updateAsset(
+ SessionAsset asset, {
+ required ScopedAssetChanges changes,
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.metadata, changes.mode);
+ _checkAsset(asset);
+ if (asset.fileName == null) {
+ throw const FeatureDisabled('This asset has no validated filename');
+ }
+ final tags = changes.tags == null
+ ? null
+ : List<String>.unmodifiable(changes.tags!);
+ return _session._run(
+ (token) async => CollectionDescriptionUpdateResponse(
+ _fields(
+ (await _session._client.collections.updateDescription(
+ groupName: mapping.collectionId,
+ mode: mapping.mode,
+ streamName: mapping.streamName,
+ filenameSanitized: asset.fileName!,
+ description: changes.description,
+ tag: tags,
+ cancellation: token,
+ )).raw,
+ const <String>{'status', 'updated'},
+ ),
+ ),
+ cancellation: cancellation,
+ );
+ }
+
+ /// The URL grant remains private and bytes are fenced through each phase.
+ Future<Uint8List> imageBytes(
+ SessionAsset asset, {
+ int? maxBytes,
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.media, mapping.mode);
+ _checkAsset(asset);
+ if (asset.fileName == null) {
+ throw const FeatureDisabled('This asset has no validated media selector');
+ }
+ final modality = switch (mapping.mode) {
+ 'img_file' => 'img_raw',
+ 'vid_file' || 'vid_stream_day' => 'vid_img',
+ _ => throw const FeatureDisabled('Media is unavailable for this mode'),
+ };
+ final reported = asset._media['modality'];
+ if (reported != null && reported != modality) {
+ throw const ValidationException(
+ 'Media modality does not match the scope',
+ );
+ }
+ Object? timestamp = asset._media['ts_unix_13digits'];
+ // File-video frames are relative to their source video. Day-stream media
+ // requires its real epoch timestamp and cannot use this offset fallback.
+ if (timestamp == null && mapping.mode == 'vid_file') {
+ timestamp = VideoSearchHit(asset._media).playbackOffsetMs;
+ }
+ String? ts13;
+ if (timestamp != null) {
+ final value = '$timestamp';
+ if (!RegExp(r'^\d{1,13}$').hasMatch(value)) {
+ throw const ValidationException('Media timestamp is invalid');
+ }
+ ts13 = value.padLeft(13, '0');
+ }
+ if (mapping.mode != 'img_file' && ts13 == null) {
+ throw const FeatureDisabled(
+ 'This video asset has no validated frame time',
+ );
+ }
+ return _session._run((token) async {
+ final result = await _session._client.images.getUrl(
+ mode: mapping.mode,
+ groupName: mapping.collectionId,
+ streamName: mapping.streamName,
+ modality: modality,
+ filename: asset.fileName!,
+ tsUnix13digits: ts13,
+ cancellation: token,
+ );
+ _session._guard.check();
+ token.throwIfCanceled();
+ if (!result.found || result.urlPreSigned.isEmpty) {
+ throw const FeatureDisabled('Media is unavailable');
+ }
+ return _session._client.images.getImageFromUrl(
+ result.urlPreSigned,
+ maxBytes: maxBytes,
+ cancellation: token,
+ );
+ }, cancellation: cancellation);
+ }
+
+ /// Tenant job lists are filtered by all selectors before minting provenance.
+ Future<List<SessionJob>> listIndexJobs({
+ ScopedIndexJobsOptions options = const ScopedIndexJobsOptions(),
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.indexation, options.mode ?? mapping.mode);
+ return _session._run((token) async {
+ final response = await _session._client.indexes.jobsList(
+ status: options.status,
+ mode: mapping.mode,
+ groupName: mapping.collectionId,
+ limit: options.limit,
+ cancellation: token,
+ );
+ _session._guard.check();
+ return List<SessionJob>.unmodifiable(
+ objectList(response.raw['data'])
+ .where(
+ (row) =>
+ _matches(row, requireSelectors: true) &&
+ stringValueOrNull(row['job_id']) != null,
+ )
+ .map(_job),
+ );
+ }, cancellation: cancellation);
+ }
+
+ Future<IndexationStatusResponse> indexStatus(
+ SessionJob job, {
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.indexation, mapping.mode);
+ if (job._sessionId != sessionId ||
+ job._scopeKey != scopeKey ||
+ !_session._jobs.contains(job)) {
+ throw const ValidationException('Job provenance does not match');
+ }
+ return _session._run((token) async {
+ final response = await _session._client.indexes.indexStatus(
+ job.jobId,
+ cancellation: token,
+ );
+ if (response.jobId != job.jobId ||
+ !_matches(response.raw, requireSelectors: false)) {
+ throw const MalformedResponse('Job result does not match');
+ }
+ return IndexationStatusResponse(_fields(response.raw, _jobFields));
+ }, cancellation: cancellation);
+ }
+
+ /// Rebinding needs current policy and a fresh exact scoped discovery record.
+ Future<SessionJob> rebindJob(
+ DurableJobReference reference, {
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.indexation, mapping.mode);
+ if (reference.ownerKey != _session.context.ownerKey ||
+ reference.scopeKey != scopeKey ||
+ reference.policyRevision != _session.context.policyRevision) {
+ throw const ValidationException('Durable job ownership does not match');
+ }
+ return _session._run((token) async {
+ final jobs = await listIndexJobs(
+ options: ScopedIndexJobsOptions(mode: mapping.mode, limit: 1000),
+ cancellation: token,
+ );
+ _session._guard.check();
+ final matches = jobs.where((job) => job.jobId == reference.jobId);
+ if (matches.isEmpty) {
+ throw const FeatureDisabled(
+ 'Job has no current scoped ownership proof',
+ );
+ }
+ return matches.first;
+ }, cancellation: cancellation);
+ }
+
+ /// Backend index deletion affects the collection, including other streams.
+ Future<IndexationDeleteResponse> deleteIndex(
+ String version, {
+ ScopedDeleteIndexOptions options = const ScopedDeleteIndexOptions(),
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.delete, options.mode);
+ if (!mapping.collectionWide) {
+ throw const ValidationException('Collection-wide access is required');
+ }
+ final request = IndexationDeleteRequest(
+ mode: mapping.mode,
+ groupName: mapping.collectionId,
+ version: version,
+ modality: options.modality,
+ dryRun: options.dryRun,
+ confirm: options.confirm,
+ );
+ return _session._run(
+ (token) async => IndexationDeleteResponse(
+ _fields(
+ (await _session._client.indexes.deleteIndex(
+ request,
+ cancellation: token,
+ )).raw,
+ const <String>{'status', 'deleted', 'dry_run'},
+ ),
+ ),
+ cancellation: cancellation,
+ );
+ }
+
+ /// Aggregate versions require collection-wide access or an exact stream row.
+ Future<GroupItem?> collectionInfo({CancellationToken? cancellation}) {
+ _allow(UserAction.discover, mapping.mode);
+ return _session._run((token) async {
+ final response = await _session._client.collections.listGroups(
+ mode: mapping.mode,
+ cancellation: token,
+ );
+ _session._guard.check();
+ for (final row in response.data) {
+ if (row.groupName != mapping.collectionId || row.mode != mapping.mode) {
+ continue;
+ }
+ if (!mapping.collectionWide &&
+ row.raw['stream_name'] != mapping.streamName) {
+ continue;
+ }
+ return GroupItem(
+ _fields(row.raw, const <String>{
+ 'group_name',
+ 'mode',
+ 'stream_name',
+ 'lancedb_versions',
+ }),
+ );
+ }
+ return null;
+ }, cancellation: cancellation);
+ }
+
+ Future<int?> latestVersion({CancellationToken? cancellation}) =>
+ _session._run(
+ (token) async =>
+ (await collectionInfo(cancellation: token))?.latestLancedbVersion,
+ cancellation: cancellation,
+ );
+
+ Future<SessionSearchResponse> search(
+ String query, {
+ ScopedSearchOptions options = const ScopedSearchOptions(),
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.search, options.mode);
+ final request = SearchRequest(
+ queryText: query,
+ queryMetadata: options.queryMetadata == null
+ ? null
+ : _snapshot(options.queryMetadata!) as Map<String, Object?>,
+ queryMetadataText: options.queryMetadataText,
+ imageQuery: options.imageQuery,
+ mode: mapping.mode,
+ groupName: mapping.collectionId,
+ streamName: mapping.streamName,
+ searchSources: List<String>.unmodifiable(options.searchSources),
+ searchCombineMode: options.searchCombineMode,
+ startDate: options.startDate,
+ endDate: options.endDate,
+ offset: options.offset,
+ limit: options.limit,
+ textEmbScoreMin: options.textEmbScoreMin,
+ imageEmbScoreMin: options.imageEmbScoreMin,
+ versionLancedb: options.versionLancedb,
+ );
+ return _session._run((token) async {
+ final result = await _session._client.searches.searchVideo(
+ request,
+ cancellation: token,
+ );
+ _session._guard.check();
+ final rows = objectList(result.raw['data'])
+ .where((row) => _matches(row, requireSelectors: false))
+ .map((row) => _fields(row, _searchFields))
+ .toList();
+ final assets = rows.map(_asset).toList();
+ return SessionSearchResponse._(
+ _snapshot(<String, Object?>{
+ 'data': rows,
+ 'cnt_actual': rows.length,
+ 'cnt_total': rows.length,
+ })
+ as Map<String, Object?>,
+ assets,
+ );
+ }, cancellation: cancellation);
+ }
+
+ Future<MetadataParquetUploadResponse> uploadMetadata(
+ VmodalFilePart part, {
+ ScopedMetadataOptions options = const ScopedMetadataOptions(),
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.metadata, options.mode);
+ return _session._run((token) async {
+ // Existing metadata records must bind to live scoped asset provenance.
+ // A bounded immutable snapshot prevents the opener changing after validation.
+ final bytes = await readBounded(
+ VmodalResponse(
+ statusCode: 200,
+ contentLength: part.contentLength,
+ body: _session._guard.guardStream(part.open(), cancellation: token),
+ ),
+ 8 * 1024 * 1024,
+ cancellation: token,
+ );
+ _session._guard.check();
+ token.throwIfCanceled();
+ final lines = utf8
+ .decode(bytes)
+ .split('\n')
+ .where((line) => line.trim().isNotEmpty);
+ if (lines.isEmpty) throw const ValidationException('Metadata is empty');
+ for (final line in lines) {
+ final decoded = jsonDecode(line);
+ if (decoded is! Map<String, Object?>) {
+ throw const ValidationException('Metadata row must be an object');
+ }
+ const fields = <String>{
+ 'filename',
+ 'filename_sanitized',
+ 'asset_id',
+ 'description',
+ 'metadata_text',
+ 'tags',
+ 'tag',
+ };
+ if (decoded.keys.any((key) => !fields.contains(key))) {
+ throw const ValidationException('Unsupported metadata field');
+ }
+ final id = stringValueOrNull(decoded['asset_id']);
+ final filename =
+ stringValueOrNull(decoded['filename_sanitized']) ??
+ stringValueOrNull(decoded['filename']);
+ if (id == null && filename == null) {
+ throw const ValidationException('Metadata needs a proven asset');
+ }
+ final proven = _session._assets.any(
+ (asset) =>
+ asset._sessionId == sessionId &&
+ asset._scopeKey == scopeKey &&
+ (id == null || asset.assetId == id) &&
+ (filename == null || asset.fileName == filename),
+ );
+ if (!proven ||
+ decoded['filename'] != null &&
+ decoded['filename_sanitized'] != null &&
+ decoded['filename'] != decoded['filename_sanitized']) {
+ throw const ValidationException(
+ 'Metadata asset provenance does not match',
+ );
+ }
+ for (final value in decoded.values) {
+ if (value is! String &&
+ value is! List<String> &&
+ !(value is List && value.every((v) => v is String))) {
+ throw const ValidationException('Unsupported metadata value');
+ }
+ }
+ }
+ final captured = VmodalFilePart.bytes(
+ fieldName: part.fieldName,
+ fileName: part.fileName,
+ contentType: part.contentType,
+ bytes: bytes,
+ );
+ return MetadataParquetUploadResponse(
+ _fields(
+ (await _session._client.collections.uploadMetadataJsonl(
+ captured,
+ mode: mapping.mode,
+ groupName: mapping.collectionId,
+ streamName: mapping.streamName,
+ writeMode: options.writeMode,
+ allowOverlap: options.allowOverlap,
+ cancellation: token,
+ )).raw,
+ const <String>{'status', 'accepted', 'written', 'uploaded'},
+ ),
+ );
+ }, cancellation: cancellation);
+ }
+
+ UploadTask<SessionUploadResponse> upload(
+ UploadSource source, {
+ ScopedUploadOptions options = const ScopedUploadOptions(),
+ }) {
+ _allow(UserAction.upload, options.mode);
+ if (options.uploadOptions.sessionStore != null) {
+ throw const ValidationException(
+ 'Use only session-owned upload checkpoints',
+ );
+ }
+ if (options.uploadOptions.transcoder.runtimeType !=
+ PassthroughVideoTranscoder) {
+ throw const ValidationException(
+ 'Custom transcoders are not session-owned',
+ );
+ }
+ final captured = options.uploadOptions.copyWith(
+ sessionStore: _uploadStore,
+ metadataTags: options.uploadOptions.metadataTags == null
+ ? null
+ : List<String>.unmodifiable(options.uploadOptions.metadataTags!),
+ );
+ final operation = _session._guard.register();
+ return _SessionUploadTask<SessionUploadResponse>(_session._guard, (
+ cancel,
+ emit,
+ ) async {
+ final remove = cancel.onCancel(operation.token.cancel);
+ return operation.run(
+ (token) => _safeWork(() async {
+ final task = _session._client.collections.videoUpload(
+ source,
+ collectionName: mapping.collectionId,
+ subCollectionName: mapping.streamName,
+ mode: mapping.mode,
+ modality: options.modality,
+ ttl: options.ttl,
+ options: captured,
+ );
+ final detach = token.onCancel(task.cancel);
+ final subscription = _session._guard
+ .guardStream(task.progress, cancellation: token)
+ .listen(emit, onError: (Object _) {});
+ try {
+ final result = await task.result;
+ operation.check();
+ final done = objectMap(result.raw['upload_done']);
+ if (!_matches(done, requireSelectors: false)) {
+ throw const MalformedResponse(
+ 'Upload result scope does not match',
+ );
+ }
+ final safe = _fields(<String, Object?>{
+ ...result.raw,
+ if (done['asset_id'] is String) 'asset_id': done['asset_id'],
+ }, _uploadFields);
+ final asset =
+ stringValueOrNull(safe['asset_id']) != null ||
+ stringValueOrNull(safe['filename']) != null
+ ? _asset(safe)
+ : null;
+ return SessionUploadResponse._(safe, asset);
+ } finally {
+ detach();
+ remove();
+ await subscription.cancel();
+ }
+ }),
+ );
+ });
+ }
+
+ Future<SessionJob> createIndex({
+ ScopedCreateIndexOptions options = const ScopedCreateIndexOptions(),
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.indexation, options.mode);
+ final request = IndexationSubmitRequest(
+ mode: mapping.mode,
+ groupName: mapping.collectionId,
+ streamName: mapping.streamName,
+ indexType: options.indexType,
+ modality: options.modality,
+ insertMode: options.insertMode,
+ createIndex: options.createIndex,
+ version: options.version,
+ startDate: options.startDate,
+ endDate: options.endDate,
+ embeddingModel: options.embeddingModel,
+ reProcess: options.reProcess,
+ dryRun: options.dryRun,
+ );
+ return _session._run((token) async {
+ final result = await _session._client.indexes.createIndex(
+ request,
+ cancellation: token,
+ );
+ _session._guard.check();
+ if (!_matches(result.raw, requireSelectors: false)) {
+ throw const MalformedResponse('Index result scope does not match');
+ }
+ return _job(result.raw);
+ }, cancellation: cancellation);
+ }
+
+ Future<DeleteCollectionResponse> deleteCollection({
+ ScopedDeleteCollectionOptions options =
+ const ScopedDeleteCollectionOptions(),
+ CancellationToken? cancellation,
+ }) {
+ _allow(UserAction.delete, options.mode);
+ if (!mapping.collectionWide) {
+ throw const ValidationException('Collection-wide access is required');
+ }
+ return _session._run(
+ (token) async => DeleteCollectionResponse(
+ _fields(
+ (await _session._client.collections.delete(
+ groupName: mapping.collectionId,
+ mode: mapping.mode,
+ scope: options.scope,
+ dryRun: options.dryRun,
+ confirm: options.confirm,
+ cancellation: token,
+ )).raw,
+ const <String>{'status', 'deleted', 'dry_run'},
+ ),
+ ),
+ cancellation: cancellation,
+ );
+ }
+}
+
+// Fence the public task's stream too: its controller may buffer events while
+// the caller pauses, after the upstream guarded subscription accepted them.
+final class _SessionUploadTask<T> extends UploadTask<T> {
+ _SessionUploadTask(this._guard, UploadRunner<T> runner) : super.start(runner);
+ final SessionGuard _guard;
+ late final Future<T> _guardedResult = _guard.run(
+ (_) => super.result,
+ cancellation: cancellation,
+ );
+ @override
+ Future<T> get result => _guardedResult;
+ @override
+ Stream<UploadProgress> get progress =>
+ _guard.guardStream(super.progress, cancellation: cancellation);
+}
+
+Object? _snapshot(Object? value) {
+ if (value is Map) {
+ if (value.keys.any((key) => key is! String)) {
+ throw const ValidationException('Structured input keys must be strings');
+ }
+ return Map<String, Object?>.unmodifiable(
+ value.map((k, v) => MapEntry(k as String, _snapshot(v))),
+ );
+ }
+ if (value is List) return List<Object?>.unmodifiable(value.map(_snapshot));
+ if (value == null || value is String || value is num || value is bool) {
+ return value;
+ }
+ throw const ValidationException('Structured input must contain JSON values');
+}
+
+const _searchFields = <String>{
+ 'asset_id',
+ 'filename',
+ 'filename_sanitized',
+ 'file_name',
+ 'video_filename',
+ 'title',
+ 'description',
+ 'metadata_text',
+ 'tags',
+ 'playback_offset_ms',
+ 'video_time_seconds',
+ 'timestamp_seconds',
+ 'distance',
+ 'score',
+ 'ts_unix_13digits',
+ 'modality',
+};
+const _uploadFields = <String>{
+ 'asset_id',
+ 'filename',
+ 'size_bytes',
+ 'uploaded',
+ 'upload_strategy',
+ 'part_size_bytes',
+ 'part_count',
+ 'parts_uploaded',
+ 'resumed',
+ 'attempt_count',
+ 'video_filename',
+ 'start_datetime_user',
+ 'start_ts_unix_user_ms',
+ 'timestamp_source',
+ 'reduce_size',
+ 'source_size_bytes',
+ 'temporary_file_deleted',
+ 'temporary_file_reused',
+};
+const _jobFields = <String>{'job_id', 'status', 'version', 'progress'};
+
+// Only documented scalar display fields or homogeneous scalar lists survive.
+// Extension maps and nested records never inherit the outer row's provenance.
+Map<String, Object?> _fields(Map<String, Object?> row, Set<String> allowed) {
+ final safe = <String, Object?>{};
+ for (final key in allowed) {
+ final value = row[key];
+ if (value is String || value is num || value is bool) {
+ safe[key] = value;
+ } else if (value is List &&
+ value.every((v) => v is String || v is num || v is bool)) {
+ safe[key] = List<Object?>.unmodifiable(value);
+ }
+ }
+ return Map<String, Object?>.unmodifiable(safe);
+}
+
+// Restricted errors carry no raw tenant-wide body, signed grant or cause.
+Future<T> _safeWork<T>(Future<T> Function() work) async {
+ try {
+ return await work();
+ } on OperationCanceled {
+ rethrow;
+ } on FeatureDisabled {
+ throw const FeatureDisabled('Operation is unavailable in this scope');
+ } on ValidationException {
+ throw const ValidationException('Operation validation failed');
+ } on AuthException {
+ throw const TenantAuthException();
+ } on ApiException catch (error) {
+ throw ApiException('Scoped operation failed', statusCode: error.statusCode);
+ } on ResponseTooLarge catch (error) {
+ throw ResponseTooLarge(error.limitBytes, error.observedBytes);
+ } on MalformedResponse {
+ throw const MalformedResponse();
+ } on FormatException {
+ throw const ValidationException('Structured input is malformed');
+ } on Object {
+ throw const TransportException();
+ }
+}
diff --git a/lib/vmodal_sdk_flutter.dart b/lib/vmodal_sdk_flutter.dart
index 77a8b3b..5a1f8ff 100644
--- a/lib/vmodal_sdk_flutter.dart
+++ b/lib/vmodal_sdk_flutter.dart
@@ -52,4 +52,5 @@ export 'src/transport.dart'
guessContentType,
streamPart;
export 'src/upload.dart';
+export 'src/user_session.dart';
export 'src/vmodal.dart';
diff --git a/pubspec.yaml b/pubspec.yaml
index 5f3a67a..a27cc10 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,6 +1,6 @@
name: vmodal_sdk_flutter
description: Typed VModal API client for Flutter applications on Android and iOS.
-version: 1.2.3
+version: 1.3.0
license: MIT
repository: https://github.com/v-modal/vmodal_sdk_flutter
issue_tracker: https://github.com/v-modal/vmodal_sdk_flutter/issues
diff --git a/release_note.md b/release_note.md
index c3c1a2b..76eb6fc 100644
--- a/release_note.md
+++ b/release_note.md
@@ -1,7 +1,8 @@
----------------------------------------------------------
-date: 2026-09-27
-origin_commit: pending
-title: Flutter SDK v1.2.3 Dartdoc package archive repair
+date: 2026-10-02
+origin_commit: e02e2e15a2d2eb6af43125e89dc4e5bef904ce20
+title: Flutter SDK v1.3.0 app-user session isolation
summary:
- - Reissued the package with explicit public `lib/` include rules so pub.dev's archive retains the Dart entrypoint for dartdoc.
- - Added a regression assertion for the library include rules and release guidance that requires the package dry-run to list the entrypoint.
+ - Added an opt-in session interface for applications sharing a tenant API key across app users.
+ - Guarded stale network work and isolated local owner namespaces while preserving tenant-scoped API compatibility.
+ - Kept tenant key rotation independent of host login and account switching.
diff --git a/test/auth_http_test.dart b/test/auth_http_test.dart
index b0c2554..d93ffe2 100644
--- a/test/auth_http_test.dart
+++ b/test/auth_http_test.dart
@@ -1,8 +1,42 @@
+import 'dart:async';
+
import 'package:flutter_test/flutter_test.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
import 'fakes.dart';
+TenantCredential _credential(String key) => TenantCredential(
+ serviceNamespace: 'https://gateway.test/api/v1/proxy/search_api',
+ tenantId: 'T',
+ principal: 'tenant-principal',
+ apiKey: key,
+);
+
+TenantCredentialSource _source({Future<TenantCredential> Function()? renew}) =>
+ TenantCredentialSource(
+ serviceNamespace: 'https://gateway.test/api/v1/proxy/search_api',
+ tenantId: 'T',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'old-key',
+ renew: renew,
+ );
+
+VmodalClient _tenantClient(
+ TenantCredentialSource keys,
+ VmodalTransport transport, {
+ int retries = 0,
+ TenantSessionApiKeyProvider? provider,
+}) => VmodalClient(
+ config: SdkConfig(
+ baseUrl: 'https://gateway.test',
+ apiKeyProvider: provider ?? keys.createProvider(isActive: () => true),
+ maxRetries: retries,
+ ),
+ transport: transport,
+ signedUploadTransport: FakeSignedUploadTransport(),
+ delay: (_) async {},
+);
+
void main() {
test(
'gateway request reads provider once and sends no identity headers',
@@ -125,4 +159,231 @@ void main() {
);
expect(() => missing.http.headers(), throwsA(isA<AuthException>()));
});
+
+ test(
+ 'stale-key 401 reconstructs one read with the committed fresh headers',
+ () async {
+ final denied = Completer<VmodalResponse>();
+ final keys = _source();
+ final fake = HandlerTransport((VmodalRequest request) async {
+ return request.headers['Authorization'] == 'Bearer old-key'
+ ? denied.future
+ : jsonResponse('{"status":"ok"}');
+ });
+ final client = _tenantClient(keys, fake);
+ final read = client.health();
+ keys.install(_credential('new-key'));
+ denied.complete(jsonResponse('{"secret":"tenant-body"}', status: 401));
+ await read;
+ expect(fake.requests, hasLength(2));
+ expect(fake.requests.first.headers['Authorization'], 'Bearer old-key');
+ expect(fake.requests.last.headers['Authorization'], 'Bearer new-key');
+ expect(keys.isAvailable, isTrue);
+ },
+ );
+
+ test(
+ 'eligible read denied after renewal terminates with a safe tenant error',
+ () async {
+ var renewals = 0;
+ final keys = _source(
+ renew: () async {
+ renewals++;
+ return _credential('new-key');
+ },
+ );
+ final fake = FakeTransport()
+ ..addResponse(jsonResponse('{"secret":"raw-denial"}', status: 401))
+ ..addResponse(jsonResponse('{"secret":"raw-denial"}', status: 401));
+ final client = _tenantClient(keys, fake, retries: 10);
+ await expectLater(
+ client.health(),
+ throwsA(
+ isA<TenantAuthException>()
+ .having((TenantAuthException e) => e.body, 'body', isNull)
+ .having((TenantAuthException e) => e.details, 'details', isNull),
+ ),
+ );
+ expect(renewals, 1);
+ expect(fake.requests, hasLength(2));
+ expect(keys.currentSnapshot.apiKey, 'new-key');
+ },
+ );
+
+ test(
+ 'ordinary retries and one auth recovery have a shared finite budget',
+ () async {
+ final keys = _source(renew: () async => _credential('new-key'));
+ final fake = FakeTransport()
+ ..addResponse(jsonResponse('{}', status: 503))
+ ..addResponse(jsonResponse('{}', status: 401))
+ ..addResponse(jsonResponse('{}', status: 503));
+ final client = _tenantClient(keys, fake, retries: 1);
+ await expectLater(client.health(), throwsA(isA<ApiException>()));
+ expect(fake.requests, hasLength(3));
+ expect(fake.requests.first.headers['Authorization'], 'Bearer old-key');
+ expect(fake.requests[1].headers['Authorization'], 'Bearer old-key');
+ expect(fake.requests.last.headers['Authorization'], 'Bearer new-key');
+ },
+ );
+
+ test(
+ 'mutations and 403 never obtain a broader credential or replay',
+ () async {
+ var renewals = 0;
+ final keys = _source(
+ renew: () async {
+ renewals++;
+ return _credential('new-key');
+ },
+ );
+ final fake = FakeTransport()
+ ..addResponse(jsonResponse('{}', status: 401))
+ ..addResponse(jsonResponse('{"private":"denied"}', status: 403));
+ final client = _tenantClient(keys, fake, retries: 5);
+ await expectLater(
+ client.searches.searchVideo(const SearchRequest(queryText: 'query')),
+ throwsA(isA<TenantAuthException>()),
+ );
+ await expectLater(
+ client.health(),
+ throwsA(
+ isA<ApiException>()
+ .having((ApiException e) => e.statusCode, 'status', 403)
+ .having((ApiException e) => e.body, 'body', isNull),
+ ),
+ );
+ expect(fake.requests, hasLength(2));
+ expect(renewals, 0);
+ },
+ );
+
+ test(
+ 'closed session awaiting shared renewal dispatches no recovered read',
+ () async {
+ final pending = Completer<TenantCredential>();
+ final started = Completer<void>();
+ final keys = _source(
+ renew: () {
+ started.complete();
+ return pending.future;
+ },
+ );
+ var active = true;
+ final provider = keys.createProvider(isActive: () => active);
+ final fake = FakeTransport()
+ ..addResponse(jsonResponse('{}', status: 401));
+ final client = _tenantClient(keys, fake, provider: provider);
+ final read = client.health();
+ final failure = expectLater(read, throwsA(isA<OperationCanceled>()));
+ await started.future;
+ active = false;
+ provider.close();
+ final b = keys.createProvider(isActive: () => true);
+ pending.complete(_credential('new-key'));
+ await failure;
+ expect(fake.requests, hasLength(1));
+ expect(b.current(), 'new-key');
+ expect(provider.isClosed, isTrue);
+ },
+ );
+
+ test('concurrent read failures join one tenant renewal', () async {
+ final pending = Completer<TenantCredential>();
+ var renewals = 0;
+ final keys = _source(
+ renew: () {
+ renewals++;
+ return pending.future;
+ },
+ );
+ final fake = FakeTransport()
+ ..addResponse(jsonResponse('{}', status: 401))
+ ..addResponse(jsonResponse('{}', status: 401))
+ ..addResponse(jsonResponse('{"status":"ok"}'))
+ ..addResponse(jsonResponse('{"status":"ok"}'));
+ final client = _tenantClient(keys, fake);
+ final first = client.health();
+ final second = client.health();
+ await Future<void>.delayed(Duration.zero);
+ expect(renewals, 1);
+ pending.complete(_credential('new-key'));
+ await Future.wait(<Future<HealthResponse>>[first, second]);
+ expect(fake.requests, hasLength(4));
+ expect(
+ fake.requests
+ .skip(2)
+ .map((VmodalRequest r) => r.headers['Authorization']),
+ everyElement('Bearer new-key'),
+ );
+ });
+
+ test('rotation preserves a successful in-flight mutation snapshot', () async {
+ final response = Completer<VmodalResponse>();
+ final keys = _source();
+ var calls = 0;
+ final fake = HandlerTransport(
+ (_) => calls++ == 0
+ ? response.future
+ : Future<VmodalResponse>.value(jsonResponse('{}')),
+ );
+ final client = _tenantClient(keys, fake);
+ final mutation = client.searches.searchVideo(
+ const SearchRequest(queryText: 'query'),
+ );
+ keys.install(_credential('new-key'));
+ response.complete(jsonResponse('{}'));
+ await mutation;
+ await client.health();
+ expect(fake.requests.first.headers['Authorization'], 'Bearer old-key');
+ expect(fake.requests.last.headers['Authorization'], 'Bearer new-key');
+ expect(fake.requests, hasLength(2));
+ });
+
+ test(
+ 'authoritative revocation during retry delay blocks the next send',
+ () async {
+ final keys = _source();
+ final fake = FakeTransport()
+ ..addResponse(jsonResponse('{}', status: 503));
+ final client = VmodalClient(
+ config: SdkConfig(
+ baseUrl: 'https://gateway.test',
+ apiKeyProvider: keys.createProvider(isActive: () => true),
+ maxRetries: 5,
+ ),
+ transport: fake,
+ signedUploadTransport: FakeSignedUploadTransport(),
+ delay: (_) async {
+ keys.revoke();
+ },
+ );
+ await expectLater(client.health(), throwsA(isA<TenantAuthException>()));
+ expect(fake.requests, hasLength(1));
+ },
+ );
+
+ test(
+ 'renewal failure blocks tenant calls without closing the app session',
+ () async {
+ final keys = _source(
+ renew: () async => throw StateError('private-issuer-error'),
+ );
+ final provider = keys.createProvider(isActive: () => true);
+ final fake = FakeTransport()
+ ..addResponse(jsonResponse('{}', status: 401))
+ ..addResponse(jsonResponse('{}'));
+ final client = _tenantClient(keys, fake, provider: provider);
+ await expectLater(client.health(), throwsA(isA<TenantAuthException>()));
+ await expectLater(client.health(), throwsA(isA<TenantAuthException>()));
+ expect(provider.isClosed, isFalse);
+ expect(fake.requests, hasLength(1));
+ keys.install(_credential('recovered-key'));
+ await client.health();
+ expect(
+ fake.requests.last.headers['Authorization'],
+ 'Bearer recovered-key',
+ );
+ },
+ );
}
diff --git a/test/docs_reference_test.dart b/test/docs_reference_test.dart
index ca75eda..cc7ed91 100644
--- a/test/docs_reference_test.dart
+++ b/test/docs_reference_test.dart
@@ -26,6 +26,12 @@ final requiredDocs = <String>[
'vmodal_sdk_flutter/CollectionsResource/listGroups.html',
'vmodal_sdk_flutter/CollectionUploads/videoUpload.html',
'vmodal_sdk_flutter/UploadTask-class.html',
+ 'vmodal_sdk_flutter/UserSessionManager-class.html',
+ 'vmodal_sdk_flutter/UserSession-class.html',
+ 'vmodal_sdk_flutter/UserScope-class.html',
+ 'vmodal_sdk_flutter/SessionContext-class.html',
+ 'vmodal_sdk_flutter/TenantCredentialSource-class.html',
+ 'vmodal_sdk_flutter/SessionStorageLease-class.html',
];
final forbiddenDocs = <String>[
@@ -104,6 +110,12 @@ void main() {
'vmodal_sdk_flutter.CollectionUploads.videoUpload',
'vmodal_sdk_flutter.UploadTask',
'vmodal_sdk_flutter.SdkException',
+ 'vmodal_sdk_flutter.UserSessionManager',
+ 'vmodal_sdk_flutter.UserSession',
+ 'vmodal_sdk_flutter.UserScope',
+ 'vmodal_sdk_flutter.SessionContext',
+ 'vmodal_sdk_flutter.TenantCredentialSource',
+ 'vmodal_sdk_flutter.SessionStorageLease',
];
stdout.writeln('[docs] index entries=${rows.length}');
for (final name in expected) {
diff --git a/test/readme_pin_test.dart b/test/readme_pin_test.dart
index 8f933da..6c22aa9 100644
--- a/test/readme_pin_test.dart
+++ b/test/readme_pin_test.dart
@@ -20,6 +20,15 @@ void main() {
multiLine: true,
).firstMatch(pubspec)!.group(1);
final tag = RegExp(r'ref:\s*v([^\s]+)').firstMatch(section!)?.group(1);
- if (tag != null) expect(tag, version);
+ final published = RegExp(
+ r'vmodal_sdk_flutter:\s*([^\s]+)',
+ ).firstMatch(section)?.group(1);
+ expect(published, isNotNull);
+ if (tag != null) expect(tag, published);
+ if (published != version) {
+ expect(section, contains('**$version source release**'));
+ expect(section, contains('do not contain these additions'));
+ expect(section, contains('does not publish `$version` to pub.dev'));
+ }
});
}
diff --git a/test/regression_manifest_test.dart b/test/regression_manifest_test.dart
index 06ab699..e287ff9 100644
--- a/test/regression_manifest_test.dart
+++ b/test/regression_manifest_test.dart
@@ -49,6 +49,8 @@ void main() {
'lib/vmodal_sdk_flutter.dart',
'lib/src/client.dart',
'lib/src/content_scope.dart',
+ 'lib/src/user_session.dart',
+ 'lib/src/session_guard.dart',
'lib/src/transport.dart',
'lib/src/upload.dart',
'lib/src/adaptive_upload.dart',
@@ -174,6 +176,11 @@ void main() {
'test.sh',
'tool/live_test.dart',
'tool/perf_benchmark.dart',
+ 'lib/src/user_session.dart',
+ 'lib/src/session_guard.dart',
+ 'test/user_session_test.dart',
+ 'test/session_guard_test.dart',
+ 'test/tenant_credentials_test.dart',
'example/readme.md',
'example/01_full_app/README.md',
'example/01_full_app/lib/main.dart',
@@ -209,6 +216,7 @@ void main() {
'docs/sdk_doc.md',
'docs/manage_api_key.md',
'docs/sdk_contract.md',
+ 'docs/user_session_implementation.md',
]) {
expect(File('${dir.path}/$path').existsSync(), isTrue, reason: path);
}
diff --git a/test/session_guard_test.dart b/test/session_guard_test.dart
new file mode 100644
index 0000000..2377a10
--- /dev/null
+++ b/test/session_guard_test.dart
@@ -0,0 +1,478 @@
+// Verbose acceptance output is required by this SDK's agent rules.
+// ignore_for_file: avoid_print
+
+import 'dart:async';
+import 'dart:collection';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:vmodal_sdk_flutter/src/session_guard.dart';
+import 'package:vmodal_sdk_flutter/src/transport.dart' show readBounded;
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+
+import 'fakes.dart';
+
+class DelayedSignedTransport implements SignedUploadTransport {
+ final Completer<SignedUploadResult> pending = Completer<SignedUploadResult>();
+ void Function(UploadProgress)? emit;
+ int calls = 0;
+
+ @override
+ Future<SignedUploadResult> upload({
+ required UploadSource source,
+ required Uri url,
+ String method = 'PUT',
+ int offset = 0,
+ int? length,
+ Map<String, String> headers = const <String, String>{},
+ Duration? timeout,
+ required CancellationToken cancellation,
+ void Function(UploadProgress)? onProgress,
+ }) {
+ calls++;
+ emit = onProgress;
+ return pending.future;
+ }
+
+ @override
+ Future<void> close() async {}
+}
+
+class FailingCloseTransport extends FakeTransport {
+ void Function()? onClose;
+
+ @override
+ Future<void> close() async {
+ onClose?.call();
+ await super.close();
+ throw StateError('gateway close failed');
+ }
+}
+
+class ReentrantHeaders extends MapBase<String, String> {
+ ReentrantHeaders(this.onRead);
+ final void Function() onRead;
+ @override
+ Iterable<String> get keys {
+ onRead();
+ return const <String>[];
+ }
+
+ @override
+ String? operator [](Object? key) => null;
+ @override
+ void operator []=(String key, String value) =>
+ throw UnsupportedError('read only');
+ @override
+ void clear() => throw UnsupportedError('read only');
+ @override
+ String? remove(Object? key) => throw UnsupportedError('read only');
+}
+
+void main() {
+ test(
+ 'retained multipart sources cannot open after session invalidation',
+ () async {
+ print(
+ '[session guard] captured multipart opener checks before file preparation',
+ );
+ final guard = SessionGuard('A-files');
+ final api = FakeTransport()..addJson(<String, Object?>{});
+ var opened = 0;
+ final response = await GuardedVmodalTransport(guard, api).send(
+ VmodalRequest(
+ method: 'POST',
+ uri: Uri.parse('https://gateway.test/upload'),
+ files: [
+ VmodalFilePart(
+ fieldName: 'file',
+ fileName: 'a.mp4',
+ contentLength: 1,
+ opener: () {
+ opened++;
+ return Stream.value([1]);
+ },
+ ),
+ ],
+ ),
+ );
+ await readBounded(response, 100);
+ guard.invalidate();
+ expect(
+ () => api.requests.single.files.single.open(),
+ throwsA(isA<OperationCanceled>()),
+ );
+ expect(opened, 0);
+ },
+ );
+
+ test(
+ 'a completed response consumed after invalidation disposes its raw source',
+ () async {
+ final guard = SessionGuard('A-body');
+ final body = StreamController<List<int>>();
+ var disposed = false;
+ body.onCancel = () => disposed = true;
+ final api = FakeTransport()
+ ..addResponse(VmodalResponse(statusCode: 200, body: body.stream));
+ final response = await GuardedVmodalTransport(guard, api).send(
+ VmodalRequest(
+ method: 'GET',
+ uri: Uri.parse('https://gateway.test/private'),
+ ),
+ );
+ guard.invalidate();
+ await expectLater(
+ readBounded(response, 100),
+ throwsA(isA<OperationCanceled>()),
+ );
+ expect(disposed, isTrue);
+ await body.close();
+ },
+ );
+
+ test(
+ 'original response is disposed when metadata callbacks invalidate delivery',
+ () async {
+ print(
+ '[session guard] disposal reaches raw body after response metadata reentry',
+ );
+ final guard = SessionGuard('A-race');
+ final pending = Completer<VmodalResponse>();
+ final body = StreamController<List<int>>();
+ var disposed = false;
+ body.onCancel = () => disposed = true;
+ final result =
+ GuardedVmodalTransport(
+ guard,
+ HandlerTransport((_) => pending.future),
+ ).send(
+ VmodalRequest(
+ method: 'GET',
+ uri: Uri.parse('https://gateway.test/search'),
+ ),
+ );
+ final canceled = expectLater(result, throwsA(isA<OperationCanceled>()));
+ pending.complete(
+ VmodalResponse(
+ statusCode: 200,
+ body: body.stream,
+ // Custom transport metadata is captured after the body is wrapped.
+ // Reentry there must dispose the original body, not the closed wrapper.
+ headers: ReentrantHeaders(guard.invalidate),
+ ),
+ );
+ await canceled;
+ await Future<void>.delayed(Duration.zero);
+ expect(disposed, isTrue);
+ await body.close();
+ },
+ );
+
+ test(
+ 'guard invalidates before preparation completes and blocks dispatch',
+ () async {
+ print('[session guard] switch during preparation blocks outgoing sends');
+ final guard = SessionGuard('A-1');
+ final preparation = Completer<void>();
+ var sends = 0;
+ final result = guard.run<int>((token) async {
+ await preparation.future;
+ guard.check();
+ sends++;
+ return 1;
+ });
+ final canceled = expectLater(result, throwsA(isA<OperationCanceled>()));
+ guard.invalidate();
+ expect(guard.isActive, isFalse);
+ await canceled;
+ preparation.complete();
+ await Future<void>.delayed(Duration.zero);
+ expect(sends, 0);
+ await expectLater(
+ guard.run<int>((_) async => 2),
+ throwsA(isA<OperationCanceled>()),
+ );
+ },
+ );
+
+ test(
+ 'uncooperative late payload and sensitive error are never returned',
+ () async {
+ print(
+ '[session guard] public cancellation does not wait for uncooperative I/O',
+ );
+ final guard = SessionGuard('A-1');
+ final payload = Completer<String>();
+ final error = Completer<String>();
+ final first = guard.run<String>((_) => payload.future);
+ final second = guard.run<String>((_) => error.future);
+ final checks = <Future<void>>[
+ expectLater(
+ first,
+ throwsA(
+ isA<OperationCanceled>().having((e) => e.body, 'body', isNull),
+ ),
+ ),
+ expectLater(
+ second,
+ throwsA(
+ isA<OperationCanceled>().having(
+ (e) => e.details,
+ 'details',
+ isNull,
+ ),
+ ),
+ ),
+ ];
+ guard.invalidate();
+ await Future.wait(checks).timeout(const Duration(seconds: 1));
+ payload.complete('A private result');
+ error.completeError(
+ const ApiException('A private error', body: 'A private body'),
+ );
+ await Future<void>.delayed(Duration.zero);
+ },
+ );
+
+ test('session cancellation never cancels a shared caller token', () async {
+ print('[session guard] tokens are linked in one direction only');
+ final a = SessionGuard('A-1');
+ final b = SessionGuard('B-1');
+ final caller = CancellationToken();
+ final pending = Completer<int>();
+ final result = a.run<int>((_) => pending.future, cancellation: caller);
+ final canceled = expectLater(result, throwsA(isA<OperationCanceled>()));
+ a.invalidate();
+ await canceled;
+ expect(caller.isCanceled, isFalse);
+ expect(await b.run<int>((_) async => 3, cancellation: caller), 3);
+ pending.complete(1);
+ });
+
+ test(
+ 'caller cancellation settles public work and detaches completed operations',
+ () async {
+ final guard = SessionGuard('A-1');
+ final caller = CancellationToken();
+ final pending = Completer<int>();
+ final result = guard.run<int>(
+ (_) => pending.future,
+ cancellation: caller,
+ );
+ final canceled = expectLater(result, throwsA(isA<OperationCanceled>()));
+ caller.cancel();
+ await canceled;
+ expect(guard.isActive, isTrue);
+ final operation = guard.register();
+ expect(await operation.run<int>((_) async => 1), 1);
+ guard.invalidate();
+ expect(operation.token.isCanceled, isFalse);
+ pending.complete(2);
+ },
+ );
+
+ test(
+ 'all cancellation callbacks and operation cleanups run even if one throws',
+ () async {
+ print('[session guard] throwing callback cannot interrupt cleanup');
+ final guard = SessionGuard('A-1');
+ final first = guard.register();
+ final second = guard.register();
+ var attempted = 0;
+ first.token.onCancel(() => throw StateError('callback failed'));
+ first.token.onCancel(() => attempted++);
+ second.token.onCancel(() => attempted++);
+ guard.invalidate();
+ guard.invalidate();
+ expect(attempted, 2);
+ expect(guard.cleanupErrors, hasLength(1));
+ expect(second.token.isCanceled, isTrue);
+ },
+ );
+
+ test(
+ 'guarded transport blocks every retry send after invalidation',
+ () async {
+ final guard = SessionGuard('A-1');
+ final api = FakeTransport()..addJson(<String, Object?>{'owner': 'A'});
+ final transport = GuardedVmodalTransport(guard, api);
+ final request = VmodalRequest(
+ method: 'GET',
+ uri: Uri.parse('https://gateway.test/search'),
+ );
+ final response = await transport.send(request);
+ expect(await readBounded(response, 100), isNotEmpty);
+ guard.invalidate();
+ await expectLater(
+ transport.send(request),
+ throwsA(isA<OperationCanceled>()),
+ );
+ expect(api.requests, hasLength(1));
+ expect(request.cancellation.isCanceled, isFalse);
+ },
+ );
+
+ test(
+ 'late response body is disposed after public transport cancellation',
+ () async {
+ final guard = SessionGuard('A-1');
+ final pending = Completer<VmodalResponse>();
+ final body = StreamController<List<int>>();
+ var disposed = false;
+ body.onCancel = () => disposed = true;
+ final api = HandlerTransport((_) => pending.future);
+ final result = GuardedVmodalTransport(guard, api).send(
+ VmodalRequest(
+ method: 'GET',
+ uri: Uri.parse('https://gateway.test/search'),
+ ),
+ );
+ final canceled = expectLater(result, throwsA(isA<OperationCanceled>()));
+ guard.invalidate();
+ await canceled;
+ pending.complete(VmodalResponse(statusCode: 200, body: body.stream));
+ await Future<void>.delayed(Duration.zero);
+ expect(disposed, isTrue);
+ await body.close();
+ },
+ );
+
+ test(
+ 'paused stream and replaced handlers cannot deliver buffered A events',
+ () async {
+ print(
+ '[session guard] delivery fence survives pause and handler replacement',
+ );
+ final guard = SessionGuard('A-1');
+ final source = StreamController<int>(sync: true);
+ final values = <int>[];
+ final errors = <Object>[];
+ final done = Completer<void>();
+ final subscription = guard
+ .guardStream(source.stream)
+ .listen(values.add, onError: errors.add, onDone: done.complete);
+ subscription.pause();
+ source.add(7);
+ subscription.onData(values.add);
+ subscription.onError(errors.add);
+ guard.invalidate();
+ subscription.resume();
+ await done.future.timeout(const Duration(seconds: 1));
+ expect(values, isEmpty);
+ expect(errors, hasLength(1));
+ expect(errors.single, isA<OperationCanceled>());
+ await subscription.cancel();
+ await source.close();
+ },
+ );
+
+ test(
+ 'reentrant invalidation from a stream callback closes cleanly',
+ () async {
+ final guard = SessionGuard('A-1');
+ final source = StreamController<int>(sync: true);
+ final values = <int>[];
+ final errors = <Object>[];
+ final done = Completer<void>();
+ guard
+ .guardStream(source.stream)
+ .listen(
+ (value) {
+ values.add(value);
+ guard.invalidate();
+ },
+ onError: errors.add,
+ onDone: done.complete,
+ );
+ source.add(1);
+ source.add(2);
+ await done.future.timeout(const Duration(seconds: 1));
+ expect(values, <int>[1]);
+ expect(errors.single, isA<OperationCanceled>());
+ await source.close();
+ },
+ );
+
+ test(
+ 'response consumption stops promptly if source stream never finishes',
+ () async {
+ final guard = SessionGuard('A-1');
+ final source = StreamController<List<int>>();
+ final api = FakeTransport()
+ ..addResponse(VmodalResponse(statusCode: 200, body: source.stream));
+ final response = await GuardedVmodalTransport(guard, api).send(
+ VmodalRequest(
+ method: 'GET',
+ uri: Uri.parse('https://gateway.test/search'),
+ ),
+ );
+ final result = readBounded(response, 100);
+ final canceled = expectLater(result, throwsA(isA<OperationCanceled>()));
+ guard.invalidate();
+ await canceled.timeout(const Duration(seconds: 1));
+ await source.close();
+ },
+ );
+
+ test(
+ 'signed PUT progress and completion are dropped after invalidation',
+ () async {
+ print('[session guard] signed storage uses same originating activation');
+ final guard = SessionGuard('A-1');
+ final signed = DelayedSignedTransport();
+ final progress = <UploadProgress>[];
+ final caller = CancellationToken();
+ final source = UploadSource(
+ fileName: 'a.mp4',
+ contentLength: 1,
+ opener: () => Stream<List<int>>.value(<int>[1]),
+ );
+ final transport = GuardedSignedUploadTransport(guard, signed);
+ final result = transport.upload(
+ source: source,
+ url: Uri.parse('https://storage.test/signed'),
+ cancellation: caller,
+ onProgress: progress.add,
+ );
+ final canceled = expectLater(result, throwsA(isA<OperationCanceled>()));
+ guard.invalidate();
+ await canceled;
+ signed.emit!(const UploadProgress(1, 1));
+ signed.pending.complete(const SignedUploadResult(statusCode: 200));
+ await Future<void>.delayed(Duration.zero);
+ expect(progress, isEmpty);
+ expect(caller.isCanceled, isFalse);
+ await expectLater(
+ transport.upload(
+ source: source,
+ url: Uri.parse('https://storage.test/signed'),
+ cancellation: caller,
+ ),
+ throwsA(isA<OperationCanceled>()),
+ );
+ expect(signed.calls, 1);
+ },
+ );
+
+ test(
+ 'client attempts both transport closes and returns same cleanup Future',
+ () async {
+ final api = FailingCloseTransport();
+ final signed = FakeSignedUploadTransport();
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'same-key'),
+ transport: api,
+ signedUploadTransport: signed,
+ );
+ Future<void>? reentrant;
+ api.onClose = () => reentrant = client.close();
+ final first = client.close();
+ final second = client.close();
+ expect(identical(first, second), isTrue);
+ expect(identical(first, reentrant), isTrue);
+ await expectLater(first, throwsA(isA<StateError>()));
+ expect(api.closeCalls, 1);
+ expect(signed.closeCalls, 1);
+ },
+ );
+}
diff --git a/test/session_lifecycle_test.dart b/test/session_lifecycle_test.dart
new file mode 100644
index 0000000..dd6194d
--- /dev/null
+++ b/test/session_lifecycle_test.dart
@@ -0,0 +1,467 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+
+import 'fakes.dart';
+import 'user_session_test.dart' as sessions;
+
+class LifecycleTransport extends FakeTransport {
+ LifecycleTransport(this.onClose);
+ final Future<void> Function() onClose;
+
+ @override
+ Future<void> close() {
+ closeCalls++;
+ closed = true;
+ return onClose();
+ }
+}
+
+void main() {
+ test(
+ 'transport ownership cannot be shared between session managers',
+ () async {
+ stdout.writeln(
+ '[lifecycle] weak ownership tracking covers all session managers',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final source = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final shared = FakeTransport()..addJson({'data': <Object?>[]});
+ UserSessionManager manager() => UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: (_) => shared,
+ signedUploadTransportFactory: (_) => FakeSignedUploadTransport(),
+ );
+ final first = manager();
+ final second = manager();
+ final map = sessions.mapping('same');
+ final a = await first.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ await expectLater(
+ second.openResolvedSession(() async => sessions.policy('B', map)),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(shared.closed, isFalse);
+ await a.scope(map).search('A still owns this transport');
+ await second.close();
+ expect(shared.closed, isFalse);
+ await first.close();
+ expect(shared.closeCalls, 1);
+ },
+ );
+
+ test(
+ 'factory reentry retires its candidate before creating another resource',
+ () async {
+ stdout.writeln(
+ '[lifecycle] activation tickets fence synchronous factory reentry',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final source = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ late UserSessionManager manager;
+ Future<UserSession>? newest;
+ final gateways = <FakeTransport>[];
+ final providers = <MutableApiKeyProvider>[];
+ var signedCount = 0;
+ manager = UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: (bound) {
+ final result = FakeTransport();
+ gateways.add(result);
+ providers.add(bound.apiKeyProvider! as MutableApiKeyProvider);
+ if (gateways.length == 1) {
+ newest = manager.openResolvedSession(
+ () async => sessions.policy('C', sessions.mapping('C')),
+ );
+ }
+ return result;
+ },
+ signedUploadTransportFactory: (_) {
+ signedCount++;
+ return FakeSignedUploadTransport();
+ },
+ );
+ await expectLater(
+ manager.openResolvedSession(
+ () async => sessions.policy('A', sessions.mapping('A')),
+ ),
+ throwsA(isA<OperationCanceled>()),
+ );
+ final c = await newest!;
+ expect(manager.current, same(c));
+ expect(providers.first.isClosed, isTrue);
+ expect(gateways.first.closed, isTrue);
+ expect(gateways.last.closed, isFalse);
+ expect(signedCount, 1);
+ await manager.close();
+ },
+ );
+
+ test(
+ 'provider is permanently closed before cancellation and host reentry',
+ () async {
+ stdout.writeln(
+ '[lifecycle] internal retirement precedes every external callback',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final source = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final pending = Completer<VmodalResponse>();
+ late MutableApiKeyProvider provider;
+ final dispatched = Completer<void>();
+ var callbacks = 0;
+ late UserSessionManager manager;
+ Future<void>? reentered;
+ manager = UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: (bound) {
+ provider = bound.apiKeyProvider! as MutableApiKeyProvider;
+ return HandlerTransport((request) {
+ request.cancellation.onCancel(() {
+ expect(provider.isClosed, isTrue);
+ expect(
+ () => provider.current(),
+ throwsA(isA<OperationCanceled>()),
+ );
+ callbacks++;
+ });
+ dispatched.complete();
+ return pending.future;
+ });
+ },
+ signedUploadTransportFactory: (_) => FakeSignedUploadTransport(),
+ onInvalidated: (session) {
+ expect(provider.isClosed, isTrue);
+ expect(session.isActive, isFalse);
+ reentered = manager.close();
+ },
+ );
+ final map = sessions.mapping('A');
+ final a = await manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final result = a.scope(map).search('private A');
+ final canceled = expectLater(result, throwsA(isA<OperationCanceled>()));
+ await dispatched.future;
+ final closing = manager.close();
+ expect(manager.close(), same(closing));
+ expect(reentered, same(closing));
+ expect(callbacks, 1);
+ await canceled;
+ await closing;
+ pending.completeError(
+ const ApiException('private A', body: 'private body'),
+ );
+ await Future<void>.delayed(Duration.zero);
+ },
+ );
+
+ test(
+ 'both closes start before host notification and slow gateway completion',
+ () async {
+ stdout.writeln(
+ '[lifecycle] slow outgoing gateway cannot delay signed transport close',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final source = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final pending = Completer<void>();
+ final gateway = LifecycleTransport(() => pending.future);
+ final signed = FakeSignedUploadTransport();
+ final manager = UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: (_) => gateway,
+ signedUploadTransportFactory: (_) => signed,
+ onInvalidated: (_) {
+ expect(gateway.closeCalls, 1);
+ expect(signed.closeCalls, 1);
+ },
+ );
+ final a = await manager.openResolvedSession(
+ () async => sessions.policy('A', sessions.mapping('A')),
+ );
+ final closing = a.close();
+ expect(a.close(), same(closing));
+ expect(a.isActive, isFalse);
+ expect(signed.closed, isTrue);
+ pending.complete();
+ await closing;
+ await manager.close();
+ },
+ );
+
+ test(
+ 'late failed teardown reports payload-free failure and leaves B usable',
+ () async {
+ stdout.writeln(
+ '[lifecycle] raw teardown errors never cross into the next user',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final source = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final failed = Completer<void>();
+ final aGateway = LifecycleTransport(() => failed.future);
+ final bGateway = FakeTransport()..addJson({'data': <Object?>[]});
+ var count = 0;
+ final signed = <FakeSignedUploadTransport>[];
+ final manager = UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: (_) => count++ == 0 ? aGateway : bGateway,
+ signedUploadTransportFactory: (_) {
+ final result = FakeSignedUploadTransport();
+ signed.add(result);
+ return result;
+ },
+ onInvalidated: (session) {
+ if (session.context.appUserId == 'A') {
+ throw const ApiException(
+ 'same-key',
+ body: 'A private body',
+ details: 'A cause',
+ );
+ }
+ },
+ );
+ final map = sessions.mapping('shared');
+ final a = await manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final b = await manager.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ expect(signed.first.closed, isTrue);
+ failed.completeError(
+ const ApiException('same-key', body: 'A body', details: 'A cause'),
+ );
+ await Future<void>.delayed(Duration.zero);
+ await expectLater(a.close(), throwsA(isA<TransportException>()));
+ expect(manager.current, same(b));
+ await b.scope(map).search('B');
+ for (final error in [...a.cleanupErrors, ...manager.cleanupErrors]) {
+ expect(error, isA<SdkException>());
+ final safe = error as SdkException;
+ expect(safe.body, isNull);
+ expect(safe.details, isNull);
+ expect(safe.toString(), isNot(contains('same-key')));
+ expect(safe.toString(), isNot(contains('A body')));
+ }
+ expect(() => manager.cleanupErrors.clear(), throwsUnsupportedError);
+ await manager.close();
+ },
+ );
+
+ test(
+ 'synchronous gateway close failure still closes signed transport',
+ () async {
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final source = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final gateway = LifecycleTransport(
+ () => throw StateError('same-key private A'),
+ );
+ final signed = FakeSignedUploadTransport();
+ final manager = UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: (_) => gateway,
+ signedUploadTransportFactory: (_) => signed,
+ );
+ final a = await manager.openResolvedSession(
+ () async => sessions.policy('A', sessions.mapping('A')),
+ );
+ final closing = a.close();
+ expect(a.close(), same(closing));
+ await expectLater(
+ closing,
+ throwsA(
+ isA<TransportException>().having((e) => e.details, 'details', isNull),
+ ),
+ );
+ expect(signed.closeCalls, 1);
+ expect(a.isActive, isFalse);
+ await manager.close();
+ },
+ );
+
+ test(
+ 'caller cannot replace the captured tenant principal during verification',
+ () async {
+ final cfg = sessions.setup();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', sessions.mapping('A')),
+ );
+ await expectLater(
+ a.verifyPrincipal('other-principal'),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.single.requests, isEmpty);
+ cfg.apis.single.addJson({'user_id': 'other-principal'});
+ await expectLater(
+ a.verifyPrincipal('tenant-principal'),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(a.isActive, isTrue);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'service namespace normalizes default ports and rejects URL adornments',
+ () {
+ expect(
+ SessionContext.serviceNamespaceFor(
+ SdkConfig(baseUrl: 'https://GATEWAY.test:443'),
+ ),
+ SessionContext.serviceNamespaceFor(
+ SdkConfig(baseUrl: 'https://gateway.test'),
+ ),
+ );
+ for (final suffix in ['?tenant=another', '#another']) {
+ expect(
+ () => SessionContext.serviceNamespaceFor(
+ SdkConfig(baseUrl: 'https://gateway.test$suffix'),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ }
+ },
+ );
+
+ test(
+ 'session-owned storage barrier fences A to B to A publication',
+ () async {
+ final cfg = sessions.setup();
+ final map = sessions.mapping('same');
+ final oldA = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final writer = oldA.scope(map).storageLease;
+ final pending = Completer<void>();
+ final started = Completer<void>();
+ final oldWrite = writer.run(() {
+ started.complete();
+ return pending.future;
+ });
+ final canceled = expectLater(oldWrite, throwsA(isA<OperationCanceled>()));
+ await started.future;
+ final b = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ // The public storage operation settles without releasing the physical
+ // commit barrier protecting a future generation of the same owner.
+ await canceled.timeout(const Duration(seconds: 1));
+ var bWrites = 0;
+ await b.scope(map).storageLease.run(() async => bWrites++);
+ final newA = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ var newWrites = 0;
+ final newWrite = newA
+ .scope(map)
+ .storageLease
+ .run(() async => newWrites++);
+ await Future<void>.delayed(Duration.zero);
+ expect(bWrites, 1);
+ expect(newWrites, 0);
+ pending.complete();
+ await newWrite;
+ expect(newWrites, 1);
+ expect(() => writer.check(), throwsA(isA<OperationCanceled>()));
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'video media derives exact wire modality and captured relative frame time',
+ () async {
+ stdout.writeln(
+ '[media] proven file-video offset becomes a vid_img selector',
+ );
+ final cfg = sessions.setup();
+ final map = sessions.mapping(
+ 'same',
+ actions: {UserAction.search, UserAction.media},
+ );
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.single.addJson({
+ 'data': [
+ {
+ 'asset_id': 'a',
+ 'filename': 'a.mp4',
+ 'playback_offset_ms': 2300,
+ 'preview_image_url': 'https://another-user.test/private',
+ },
+ {
+ 'asset_id': 'invalid',
+ 'filename': 'a.mp4',
+ 'modality': 'img_raw',
+ 'ts_unix_13digits': 1000,
+ },
+ {'asset_id': 'no-time', 'filename': 'a.mp4'},
+ ],
+ });
+ final hits = (await a.scope(map).search('a')).assets;
+ cfg.apis.single.addJson({
+ 'found': true,
+ 'url_pre_signed': 'https://objects.test/scoped',
+ });
+ cfg.apis.single.addResponse(
+ VmodalResponse(statusCode: 200, body: Stream.value([1])),
+ );
+ expect(await a.scope(map).imageBytes(hits.first), [1]);
+ final body = cfg.apis.single.requests[1].jsonBody! as Map;
+ expect(body['modality'], 'vid_img');
+ expect(body['ts_unix_13digits'], '0000000002300');
+ expect(
+ (cfg.apis.single.requests.last.jsonBody! as Map)['url_pre_signed'],
+ 'https://objects.test/scoped',
+ );
+ expect(
+ () => a.scope(map).imageBytes(hits[1]),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(
+ () => a.scope(map).imageBytes(hits[2]),
+ throwsA(isA<FeatureDisabled>()),
+ );
+ expect(cfg.apis.single.requests, hasLength(3));
+ await cfg.manager.close();
+ },
+ );
+}
diff --git a/test/session_storage_test.dart b/test/session_storage_test.dart
new file mode 100644
index 0000000..25fdd31
--- /dev/null
+++ b/test/session_storage_test.dart
@@ -0,0 +1,145 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:vmodal_sdk_flutter/src/errors.dart';
+import 'package:vmodal_sdk_flutter/src/session_guard.dart';
+import 'package:vmodal_sdk_flutter/src/upload.dart';
+
+class DelayedStore extends MemoryUploadSessionStore {
+ final started = Completer<void>();
+ final release = Completer<void>();
+ bool block = true;
+ @override
+ Future<void> save(String key, Map<String, Object?> value) async {
+ if (block) {
+ block = false;
+ started.complete();
+ await release.future;
+ }
+ await super.save(key, value);
+ }
+}
+
+void main() {
+ OwnerUploadSessionStore store(
+ SessionGuard guard,
+ String owner,
+ UploadSessionStore delegate, {
+ String policy = 'p1',
+ }) => OwnerUploadSessionStore(
+ guard: guard,
+ ownerKey: owner,
+ scopeKey: jsonEncode([owner, 'same-scope']),
+ policyRevision: policy,
+ delegate: delegate,
+ );
+
+ test(
+ 'identical upload contracts are owner partitioned and policy checked',
+ () async {
+ final backend = MemoryUploadSessionStore();
+ final a = SessionGuard('a');
+ final b = SessionGuard('b');
+ final sa = store(a, 'owner-a', backend);
+ final sb = store(b, 'owner-b', backend);
+ final data = <String, Object?>{
+ 'parts': <Object?>[1],
+ };
+ final save = sa.save('same-contract', data);
+ (data['parts'] as List).add(2);
+ await save;
+ expect(await sa.load('same-contract'), {
+ 'parts': [1],
+ });
+ expect(await sb.load('same-contract'), isNull);
+ await sb.remove('same-contract');
+ expect(await sa.load('same-contract'), isNotNull);
+ a.invalidate();
+ final narrowed = store(
+ SessionGuard('new-a'),
+ 'owner-a',
+ backend,
+ policy: 'p2',
+ );
+ expect(await narrowed.load('same-contract'), isNull);
+ },
+ );
+
+ test(
+ 'new A readers and writers fence accepted old A custom-store commit',
+ () async {
+ final backend = DelayedStore();
+ final a = SessionGuard('old-a');
+ final old = store(a, 'race-owner', backend);
+ final oldWrite = old.save('contract', {'value': 'old'});
+ final rejected = expectLater(oldWrite, throwsA(isA<OperationCanceled>()));
+ await backend.started.future;
+ a.invalidate();
+ final fresh = store(SessionGuard('new-a'), 'race-owner', backend);
+ var readFinished = false;
+ final read = fresh.load('contract').then((value) {
+ readFinished = true;
+ return value;
+ });
+ await Future<void>.delayed(Duration.zero);
+ expect(readFinished, isFalse);
+ final latest = fresh.save('contract', {'value': 'new'});
+ backend.release.complete();
+ await rejected;
+ expect(await read, {'value': 'old'});
+ await latest;
+ expect(await fresh.load('contract'), {'value': 'new'});
+ await expectLater(
+ old.remove('contract'),
+ throwsA(isA<OperationCanceled>()),
+ );
+ expect(await fresh.load('contract'), {'value': 'new'});
+ },
+ );
+
+ test(
+ 'queued retired save/remove cannot overwrite newer activation',
+ () async {
+ final backend = DelayedStore();
+ final a = SessionGuard('queued-old');
+ final old = store(a, 'queued-owner', backend);
+ final first = old.save('contract', {'value': 1});
+ final firstFailure = expectLater(
+ first,
+ throwsA(isA<OperationCanceled>()),
+ );
+ await backend.started.future;
+ final queued = old.remove('contract');
+ final queuedFailure = expectLater(
+ queued,
+ throwsA(isA<OperationCanceled>()),
+ );
+ final fresh = store(SessionGuard('queued-new'), 'queued-owner', backend);
+ final latest = fresh.save('contract', {'value': 2});
+ backend.release.complete();
+ await Future.wait([firstFailure, queuedFailure, latest]);
+ expect(await fresh.load('contract'), {'value': 2});
+ },
+ );
+
+ test(
+ 'checkpoint namespace survives fresh generation with unchanged policy',
+ () async {
+ final backend = MemoryUploadSessionStore();
+ final a = SessionGuard('restart-a');
+ await store(a, 'stable-owner', backend).save('contract', {
+ 'parts': [1, 2],
+ });
+ a.invalidate();
+ final restored = store(
+ SessionGuard('restart-new-a'),
+ 'stable-owner',
+ backend,
+ );
+ expect(await restored.load('contract'), {
+ 'parts': [1, 2],
+ });
+ },
+ );
+}
diff --git a/test/tenant_credentials_test.dart b/test/tenant_credentials_test.dart
new file mode 100644
index 0000000..30209d9
--- /dev/null
+++ b/test/tenant_credentials_test.dart
@@ -0,0 +1,216 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+
+TenantCredential credential(String key, {int? version, String tenant = 'T'}) =>
+ TenantCredential(
+ serviceNamespace: 'https://gateway.test/api/v1/proxy/search_api',
+ tenantId: tenant,
+ principal: 'tenant-principal',
+ apiKey: key,
+ issuerVersion: version,
+ );
+
+TenantCredentialSource source({
+ Future<TenantCredential> Function()? renew,
+ int? version,
+ bool retain = false,
+}) => TenantCredentialSource(
+ serviceNamespace: 'https://gateway.test/api/v1/proxy/search_api',
+ tenantId: 'T',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ initialIssuerVersion: version,
+ renew: renew,
+ retainOnRenewalFailure: retain,
+);
+
+void main() {
+ test('same tenant and key produce distinct permanently closed providers', () {
+ final keys = source();
+ var activeA = true;
+ final a = keys.createProvider(isActive: () => activeA);
+ expect(a.current(), 'same-key');
+ activeA = false;
+ a.close();
+ final b = keys.createProvider(isActive: () => true);
+ keys.install(credential('rotated-key'));
+ expect(b.current(), 'rotated-key');
+ expect(b.installedRevision, 1);
+ expect(() => a.current(), throwsA(isA<OperationCanceled>()));
+ expect(a.isClosed, isTrue);
+ expect(() => a.rotate('reopened'), throwsA(isA<AuthException>()));
+ });
+
+ test(
+ 'normal renewals coalesce even when originating session closes',
+ () async {
+ final pending = Completer<TenantCredential>();
+ var calls = 0;
+ final keys = source(
+ renew: () {
+ calls++;
+ return pending.future;
+ },
+ );
+ final a = keys.createProvider(isActive: () => true);
+ final first = keys.renewCredential();
+ final second = keys.renewCredential();
+ expect(identical(first, second), isTrue);
+ a.close();
+ final b = keys.createProvider(isActive: () => true);
+ pending.complete(credential('next-key'));
+ await Future.wait(<Future<TenantCredentialSnapshot>>[first, second]);
+ expect(calls, 1);
+ expect(b.current(), 'next-key');
+ expect(a.isClosed, isTrue);
+ },
+ );
+
+ test(
+ 'external install fences a pending renewal for the same app user',
+ () async {
+ final pending = Completer<TenantCredential>();
+ final keys = source(renew: () => pending.future);
+ final a = keys.createProvider(isActive: () => true);
+ final renewal = keys.renewCredential();
+ keys.install(credential('external-new-key'));
+ pending.complete(credential('stale-key'));
+ expect((await renewal).apiKey, 'external-new-key');
+ expect(keys.revision, 1);
+ expect(a.current(), 'external-new-key');
+ },
+ );
+
+ test(
+ 'superseded renewal cannot overwrite a newer out-of-order result',
+ () async {
+ final old = Completer<TenantCredential>();
+ final newer = Completer<TenantCredential>();
+ var calls = 0;
+ final keys = source(
+ renew: () => calls++ == 0 ? old.future : newer.future,
+ );
+ final first = keys.renewCredential();
+ final second = keys.renewCredential(supersede: true);
+ newer.complete(credential('newer-key'));
+ await second;
+ old.complete(credential('older-key'));
+ await first;
+ expect(keys.currentSnapshot.apiKey, 'newer-key');
+ expect(keys.revision, 1);
+ },
+ );
+
+ test('rotation during setup is installed before a new provider reads', () {
+ final keys = source();
+ final candidate = keys.createProvider(isActive: () => true);
+ keys.install(credential('latest-key'));
+ final next = keys.createProvider(isActive: () => true);
+ expect(candidate.current(), 'latest-key');
+ expect(next.current(), 'latest-key');
+ expect(next.installedRevision, keys.revision);
+ });
+
+ test('binding and issuer version changes fail without replacing the key', () {
+ final keys = source(version: 2);
+ expect(
+ () => keys.install(credential('wrong-key', tenant: 'other', version: 3)),
+ throwsA(isA<TenantAuthException>()),
+ );
+ expect(
+ () => keys.install(credential('older-key', version: 1)),
+ throwsA(isA<TenantAuthException>()),
+ );
+ expect(
+ () => keys.install(credential('different-key', version: 2)),
+ throwsA(isA<TenantAuthException>()),
+ );
+ expect(
+ () => keys.install(credential('missing-version')),
+ throwsA(isA<TenantAuthException>()),
+ );
+ expect(keys.currentSnapshot.apiKey, 'same-key');
+ expect(keys.revision, 0);
+ keys.install(credential('new-key', version: 3));
+ expect(keys.currentSnapshot.apiKey, 'new-key');
+ });
+
+ test(
+ 'synchronous renewal failure is classified and blocks without rollback',
+ () async {
+ final keys = source(
+ renew: () => throw StateError('secret-issuer-message'),
+ );
+ final a = keys.createProvider(isActive: () => true);
+ await expectLater(
+ keys.renewCredential(),
+ throwsA(
+ isA<TenantAuthException>()
+ .having(
+ (TenantAuthException e) => e.details,
+ 'safe details',
+ isNull,
+ )
+ .having((TenantAuthException e) => e.body, 'safe body', isNull),
+ ),
+ );
+ expect(keys.revision, 0);
+ expect(a.isClosed, isFalse);
+ expect(() => a.current(), throwsA(isA<TenantAuthException>()));
+ keys.install(credential('recovered'));
+ expect(a.current(), 'recovered');
+ },
+ );
+
+ test(
+ 'retaining an old key requires an explicit authoritative validity policy',
+ () async {
+ final keys = source(
+ renew: () async => throw StateError('issuer failure'),
+ retain: true,
+ );
+ await expectLater(
+ keys.renewCredential(),
+ throwsA(isA<TenantAuthException>()),
+ );
+ expect(keys.currentSnapshot.apiKey, 'same-key');
+ expect(keys.revision, 0);
+ },
+ );
+
+ test('revocation and retirement fence in-flight renewal results', () async {
+ final pending = Completer<TenantCredential>();
+ final keys = source(renew: () => pending.future);
+ final provider = keys.createProvider(isActive: () => true);
+ final renewal = keys.renewCredential();
+ final assertion = expectLater(renewal, throwsA(isA<TenantAuthException>()));
+ keys.revoke();
+ pending.complete(credential('late-key'));
+ await assertion;
+ expect(() => provider.current(), throwsA(isA<TenantAuthException>()));
+ keys.close();
+ expect(provider.isClosed, isTrue);
+ expect(
+ () => keys.install(credential('reopened')),
+ throwsA(isA<TenantAuthException>()),
+ );
+ });
+
+ test(
+ 'no resolver and stale 401 leave a committed newer revision intact',
+ () async {
+ final keys = source();
+ await expectLater(keys.recover(0), throwsA(isA<TenantAuthException>()));
+ expect(keys.isAvailable, isTrue);
+ keys.install(credential('current-key'));
+ expect((await keys.recover(0)).apiKey, 'current-key');
+ expect(keys.isAvailable, isTrue);
+ expect(
+ '$keys ${keys.currentSnapshot} ${credential('hidden')}',
+ isNot(contains('current-key')),
+ );
+ },
+ );
+}
diff --git a/test/user_provenance_test.dart b/test/user_provenance_test.dart
new file mode 100644
index 0000000..a024aac
--- /dev/null
+++ b/test/user_provenance_test.dart
@@ -0,0 +1,572 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+
+import 'user_session_test.dart' as sessions;
+
+class UnboundTranscoder implements VideoTranscoder {
+ @override
+ bool get isPassthrough => false;
+ @override
+ Future<TranscodeResult> reduce(File input) =>
+ throw StateError('must not run');
+}
+
+ContentMapping content({String stream = 'camera', bool wide = false}) =>
+ ContentMapping.opaque(
+ collectionId: 'shared',
+ streamName: stream,
+ collectionWide: wide,
+ actions: UserAction.values.toSet(),
+ );
+
+Map<String, Object?> row(String id, {String stream = 'camera'}) =>
+ <String, Object?>{
+ 'job_id': id,
+ 'group_name': 'shared',
+ 'stream_name': stream,
+ 'mode': 'vid_file',
+ 'status': 'completed',
+ 'secret': 'tenant-private',
+ 'assets': <Object?>[
+ {'asset_id': 'other'},
+ ],
+ };
+
+void main() {
+ test(
+ 'public upload progress buffered while paused is dropped after switch',
+ () async {
+ stdout.writeln(
+ '[provenance] listener delivery fence applies to the public upload task',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final sent = Completer<void>();
+ final release = Completer<void>();
+ Stream<List<int>> bytes() async* {
+ yield [1];
+ sent.complete();
+ await release.future;
+ yield [2];
+ }
+
+ cfg.apis.single.addJson({
+ 'url': 'https://objects.test/a',
+ 'key': 'private',
+ 'method': 'PUT',
+ });
+ final source = UploadSource(
+ fileName: 'a.mp4',
+ contentLength: 2,
+ opener: bytes,
+ );
+ final task = a.scope(map).upload(source);
+ final values = <UploadProgress>[];
+ final subscription = task.progress.listen(
+ values.add,
+ onError: (Object _) {},
+ )..pause();
+ final rejected = expectLater(
+ task.result,
+ throwsA(isA<OperationCanceled>()),
+ );
+ await sent.future;
+ await cfg.manager.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ await rejected;
+ subscription.resume();
+ await Future<void>.delayed(Duration.zero);
+ expect(values, isEmpty);
+ release.complete();
+ await subscription.cancel();
+ await cfg.manager.close();
+ },
+ );
+
+ test('metadata batches validate every live resource before dispatch', () async {
+ stdout.writeln(
+ '[provenance] metadata preparation validates rows and freezes the payload',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.single.addJson({
+ 'data': [
+ {'asset_id': 'a', 'filename': 'a.mp4'},
+ ],
+ });
+ await a.scope(map).search('a');
+ VmodalFilePart part(String data) => VmodalFilePart.bytes(
+ fieldName: 'file',
+ fileName: 'metadata.jsonl',
+ bytes: utf8.encode(data),
+ );
+ await expectLater(
+ a
+ .scope(map)
+ .uploadMetadata(
+ part('{"filename":"B.mp4","description":"B"}'),
+ options: const ScopedMetadataOptions(mode: 'vid_file'),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ await expectLater(
+ a
+ .scope(map)
+ .uploadMetadata(
+ part('{"filename":"a.mp4","user_id":"B"}'),
+ options: const ScopedMetadataOptions(mode: 'vid_file'),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.single.requests, hasLength(1));
+ cfg.apis.single.addJson({
+ 'status': 'ok',
+ 'raw': {'secret': 'B'},
+ });
+ final result = await a
+ .scope(map)
+ .uploadMetadata(
+ part('{"filename":"a.mp4","asset_id":"a","description":"new"}'),
+ options: const ScopedMetadataOptions(mode: 'vid_file'),
+ );
+ expect(result.raw, {'status': 'ok'});
+ expect(cfg.apis.single.requests.last.formFields['group_name'], 'shared');
+ await cfg.manager.close();
+ });
+
+ test('switch during metadata file preparation prevents dispatch', () async {
+ stdout.writeln(
+ '[provenance] pending file stream settles on invalidation without dispatch',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final input = StreamController<List<int>>();
+ final opened = Completer<void>();
+ final file = VmodalFilePart(
+ fieldName: 'file',
+ fileName: 'metadata.jsonl',
+ contentLength: 0,
+ opener: () {
+ opened.complete();
+ return input.stream;
+ },
+ );
+ final result = a
+ .scope(map)
+ .uploadMetadata(
+ file,
+ options: const ScopedMetadataOptions(mode: 'vid_file'),
+ );
+ final rejected = expectLater(result, throwsA(isA<OperationCanceled>()));
+ await opened.future;
+ final b = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ await rejected.timeout(const Duration(seconds: 1));
+ expect(cfg.apis.first.requests, isEmpty);
+ expect(b.isActive, isTrue);
+ await input.close();
+ await cfg.manager.close();
+ });
+
+ test(
+ 'upload strips signed grants, object keys and paths; custom hooks reject locally',
+ () async {
+ stdout.writeln(
+ '[provenance] signed upload emits only the scoped safe completion summary',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final source = UploadSource(
+ fileName: 'a.mp4',
+ contentLength: 1,
+ opener: () => Stream.value([1]),
+ );
+ expect(
+ () => a
+ .scope(map)
+ .upload(
+ source,
+ options: ScopedUploadOptions(
+ uploadOptions: VideoUploadOptions(
+ transcoder: UnboundTranscoder(),
+ ),
+ ),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.single.requests, isEmpty);
+ cfg.apis.single.addJson({
+ 'url': 'https://objects.test/private?signature=secret',
+ 'method': 'PUT',
+ 'key': 'tenant-key',
+ 'user_id': 'tenant',
+ });
+ cfg.apis.single.addJson({
+ 'asset_id': 'a',
+ 'dest_path': 'tenant/private',
+ 'filepath_local': '/private/file',
+ 'source_filepath_local': '/private/source',
+ });
+ final result = await a.scope(map).upload(source).result;
+ expect(result.asset?.assetId, 'a');
+ expect(result.url, isEmpty);
+ expect(result.key, isEmpty);
+ expect(result.destPath, isEmpty);
+ expect(result.filePath, isEmpty);
+ expect(result.uploadId, isEmpty);
+ expect(result.raw.keys, isNot(contains('user_id')));
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'discovery omits broader counts, nested data and unproven jobs',
+ () async {
+ stdout.writeln('[provenance] exact collection + stream + mode required');
+ final cfg = sessions.setup();
+ final map = content();
+ final session = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.single.addJson({
+ 'data': <Object?>[
+ row('allowed'),
+ row('other-stream', stream: 'elsewhere'),
+ {'job_id': 'unknown', 'group_name': 'shared', 'mode': 'vid_file'},
+ {...row('other-mode'), 'mode': 'img_file'},
+ ],
+ 'total': 999,
+ 'tenant_secret': 'private',
+ });
+ final jobs = await session.scope(map).listIndexJobs();
+ expect(jobs.map((j) => j.jobId), ['allowed']);
+ expect(jobs.single.raw, {'job_id': 'allowed', 'status': 'completed'});
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'search rebuilds raw/data/counts and handles only safe scoped hits',
+ () async {
+ stdout.writeln(
+ '[provenance] sanitized scoped results mint live asset handles',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final session = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.single.addJson({
+ 'data': <Object?>[
+ {
+ 'asset_id': 'a',
+ 'filename': 'a.mp4',
+ 'score': 0.3,
+ 'preview_image_url': 'https://objects.test/private',
+ 'assets': [
+ {'asset_id': 'B'},
+ ],
+ 'raw': {'private': 'B'},
+ 'userdata': 'tenant-secret',
+ },
+ {'asset_id': 'b', 'stream_name': 'other'},
+ {'asset_id': 'c', 'mode': 'img_file'},
+ ],
+ 'cnt_actual': 100,
+ 'cnt_total': 999,
+ 'extra': 'private',
+ });
+ final result = await session.scope(map).search('query');
+ expect(result.cntActual, 1);
+ expect(result.cntTotal, 1);
+ expect(result.assets.single.assetId, 'a');
+ expect(result.raw.keys.toSet(), {'data', 'cnt_actual', 'cnt_total'});
+ expect(result.videoHits.single.raw, {
+ 'asset_id': 'a',
+ 'filename': 'a.mp4',
+ 'score': 0.3,
+ });
+ expect(result.videoHits.single.previewImageUrl, isNull);
+ cfg.apis.single.addJson({
+ 'status': 'ok',
+ 'assets': [
+ {'asset_id': 'B'},
+ ],
+ });
+ await session
+ .scope(map)
+ .updateAsset(
+ result.assets.single,
+ changes: const ScopedAssetChanges(description: 'new'),
+ );
+ expect(
+ cfg.apis.single.requests.last.formFields['filename_sanitized'],
+ 'a.mp4',
+ );
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'every association member must match live session and exact scope',
+ () async {
+ stdout.writeln('[provenance] mixed scope batch denied before dispatch');
+ final cfg = sessions.setup();
+ final map = content();
+ final other = content(stream: 'other');
+ final session = await cfg.manager.openUserSession(
+ tenantId: 'same-tenant',
+ appUserId: 'A',
+ allowedContentMapping: [map, other],
+ );
+ cfg.apis.single.addJson({
+ 'data': [
+ {'asset_id': 'a', 'filename': 'a.mp4'},
+ ],
+ });
+ final a = (await session.scope(map).search('a')).assets.single;
+ cfg.apis.single.addJson({
+ 'data': [
+ {'asset_id': 'b', 'filename': 'b.mp4'},
+ ],
+ });
+ final b = (await session.scope(other).search('b')).assets.single;
+ expect(
+ () => session.scope(map).addAssets([a, b]),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.single.requests, hasLength(2));
+ cfg.apis.single.addJson({'status': 'ok', 'data': 'tenant-private'});
+ final added = await session.scope(map).addAssets([a]);
+ expect(added.raw, {'status': 'ok'});
+ expect((cfg.apis.single.requests.last.jsonBody! as Map)['asset_ids'], [
+ 'a',
+ ]);
+ final next = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ expect(
+ () => next.scope(map).addAssets([a]),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.last.requests, isEmpty);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'job status requires live provenance and strips response bodies',
+ () async {
+ stdout.writeln(
+ '[provenance] index create binds trusted job; late owner reuse denied',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.single.addJson({
+ 'job_id': 'job-a',
+ 'status': 'queued',
+ 'signed_url': 'secret',
+ });
+ final job = await a.scope(map).createIndex();
+ expect(job.raw, {'job_id': 'job-a', 'status': 'queued'});
+ cfg.apis.single.addJson({
+ 'job_id': 'job-a',
+ 'status': 'done',
+ 'data': [
+ {'secret': 'B'},
+ ],
+ });
+ expect((await a.scope(map).indexStatus(job)).raw, {
+ 'job_id': 'job-a',
+ 'status': 'done',
+ });
+ final b = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ expect(
+ () => b.scope(map).indexStatus(job),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(
+ () => b.scope(map).rebindJob(job.toDurableReference()),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.last.requests, isEmpty);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'durable job rebind needs exact owner policy and scoped discovery proof',
+ () async {
+ stdout.writeln(
+ '[provenance] restart references do not authorize tenant-wide status lookup',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.single.addJson({'job_id': 'job-a', 'status': 'queued'});
+ final durable = (await a.scope(map).createIndex()).toDurableReference();
+ final again = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.last.addJson({
+ 'data': [
+ {'job_id': 'job-a'},
+ ],
+ });
+ await expectLater(
+ again.scope(map).rebindJob(durable),
+ throwsA(isA<FeatureDisabled>()),
+ );
+ cfg.apis.last.addJson({
+ 'data': [row('job-a')],
+ });
+ final rebound = await again.scope(map).rebindJob(durable);
+ expect(rebound.jobId, 'job-a');
+ expect(
+ cfg.apis.last.requests.every(
+ (r) => r.uri.path.endsWith(Routes.indexationJobs),
+ ),
+ isTrue,
+ );
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'collection discovery filters mappings; aggregate metadata needs wide grant',
+ () async {
+ stdout.writeln(
+ '[provenance] hidden collection metadata and counts are not exposed',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final data = {
+ 'data': [
+ {
+ 'group_name': 'shared',
+ 'mode': 'vid_file',
+ 'lancedb_versions': ['v1', 'v99'],
+ 'secret': 'private',
+ },
+ {'group_name': 'B-private', 'mode': 'vid_file', 'secret': 'B'},
+ ],
+ 'total': 999,
+ };
+ cfg.apis.single.addJson(data);
+ expect(await a.listCollections(), [map]);
+ cfg.apis.single.addJson(data);
+ expect(await a.scope(map).collectionInfo(), isNull);
+ expect(
+ () => a.scope(map).deleteIndex('v1'),
+ throwsA(isA<ValidationException>()),
+ );
+ final wide = content(wide: true);
+ final current = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', wide),
+ );
+ cfg.apis.last.addJson(data);
+ expect(await current.scope(wide).latestVersion(), 99);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'media exposes guarded bytes using only a proven scoped selector',
+ () async {
+ stdout.writeln(
+ '[provenance] caller never receives storage URL or arbitrary sink',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.single.addJson({
+ 'data': [
+ {'asset_id': 'a', 'filename': 'a.mp4', 'ts_unix_13digits': 123},
+ ],
+ });
+ final hit = (await a.scope(map).search('a')).assets.single;
+ cfg.apis.single.addJson({
+ 'found': true,
+ 'url_pre_signed': 'https://objects.test/private',
+ });
+ cfg.apis.single.addResponse(
+ VmodalResponse(statusCode: 200, body: Stream.value([1, 2, 3])),
+ );
+ final bytes = await a.scope(map).imageBytes(hit);
+ expect(bytes, Uint8List.fromList([1, 2, 3]));
+ expect(
+ (cfg.apis.single.requests[1].jsonBody! as Map)['group_name'],
+ 'shared',
+ );
+ final b = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ expect(
+ () => b.scope(map).imageBytes(hit),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.last.requests, isEmpty);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'scoped API errors omit server body, details and server message',
+ () async {
+ stdout.writeln(
+ '[provenance] tenant error bodies never escape restricted interface',
+ );
+ final cfg = sessions.setup();
+ final map = content();
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ cfg.apis.single.addJson({'detail': 'B private signed URL'}, status: 403);
+ await expectLater(
+ a.scope(map).search('a'),
+ throwsA(
+ isA<SdkException>()
+ .having((e) => e.body, 'body', isNull)
+ .having((e) => e.details, 'details', isNull)
+ .having(
+ (e) => e.message.contains('B private'),
+ 'message',
+ isFalse,
+ ),
+ ),
+ );
+ await cfg.manager.close();
+ },
+ );
+}
diff --git a/test/user_session_acceptance_test.dart b/test/user_session_acceptance_test.dart
new file mode 100644
index 0000000..27e869b
--- /dev/null
+++ b/test/user_session_acceptance_test.dart
@@ -0,0 +1,674 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+
+import 'fakes.dart';
+import 'user_session_test.dart' as sessions;
+
+/// Deliberately ignores cancellation to exercise the restricted public facade.
+class AcceptanceSignedTransport extends FakeSignedUploadTransport {
+ final started = Completer<void>();
+ final release = Completer<SignedUploadResult>();
+ void Function(UploadProgress)? emit;
+
+ @override
+ Future<SignedUploadResult> upload({
+ required UploadSource source,
+ required Uri url,
+ String method = 'PUT',
+ int offset = 0,
+ int? length,
+ Map<String, String> headers = const {},
+ Duration? timeout,
+ required CancellationToken cancellation,
+ void Function(UploadProgress)? onProgress,
+ }) {
+ calls.add(
+ SignedCall(
+ url: url,
+ method: method,
+ headers: Map.of(headers),
+ offset: offset,
+ length: length ?? source.contentLength,
+ ),
+ );
+ emit = onProgress;
+ if (!started.isCompleted) started.complete();
+ return release.future;
+ }
+}
+
+TenantCredential credential(SdkConfig config, String key) => TenantCredential(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ principal: 'tenant-principal',
+ apiKey: key,
+);
+
+UserSessionManager manager(
+ SdkConfig config,
+ TenantCredentialSource source,
+ List<VmodalTransport> apis, {
+ SignedUploadTransport? signed,
+}) {
+ var count = 0;
+ return UserSessionManager(
+ config: config,
+ credentialSource: source,
+ transportFactory: (_) => apis[count++],
+ signedUploadTransportFactory: (_) =>
+ count == 1 && signed != null ? signed : FakeSignedUploadTransport(),
+ );
+}
+
+UploadSource uploadSource() => UploadSource(
+ fileName: 'same.mp4',
+ contentLength: 1,
+ sourceId: 'same-source',
+ versionTag: 'v1',
+ opener: () => Stream.value([7]),
+);
+
+class CustomPassthroughSubclass extends PassthroughVideoTranscoder {
+ bool called = false;
+
+ @override
+ bool get isPassthrough => false;
+
+ @override
+ Future<TranscodeResult> reduce(File input) {
+ called = true;
+ throw StateError('unbound hook');
+ }
+}
+
+void main() {
+ test(
+ 'same principal/key/URL/query never joins A response or cache in B',
+ () async {
+ stdout.writeln(
+ '[acceptance] identical tenant identity and query, independent A/B work',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final keys = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final pending = Completer<VmodalResponse>();
+ final dispatched = Completer<void>();
+ final aApi = HandlerTransport((request) async {
+ if (request.method == 'GET') {
+ return jsonResponse('{"user_id":"tenant-principal"}');
+ }
+ dispatched.complete();
+ return pending.future;
+ });
+ final bApi = FakeTransport()
+ ..addJson({'user_id': 'tenant-principal'})
+ ..addJson({
+ 'data': [
+ {'asset_id': 'B', 'filename': 'B.mp4'},
+ ],
+ });
+ final control = manager(config, keys, [aApi, bApi]);
+ final map = sessions.mapping('same');
+ final a = await control.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ await a.verifyPrincipal('tenant-principal');
+ final old = a.scope(map).search('identical');
+ final rejected = expectLater(old, throwsA(isA<OperationCanceled>()));
+ await dispatched.future;
+ final b = await control.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ await b.verifyPrincipal('tenant-principal');
+ final fresh = await b.scope(map).search('identical');
+ expect(fresh.assets.single.assetId, 'B');
+ expect(aApi.requests.last.uri, bApi.requests.last.uri);
+ expect(aApi.requests.last.jsonBody, bApi.requests.last.jsonBody);
+ expect(aApi.requests.last.headers['Authorization'], 'Bearer same-key');
+ expect(bApi.requests.last.headers['Authorization'], 'Bearer same-key');
+ await rejected.timeout(const Duration(seconds: 1));
+ pending.complete(
+ jsonResponse('{"data":[{"asset_id":"A","filename":"A.mp4"}]}'),
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(control.current, same(b));
+ expect(fresh.assets.single.assetId, 'B');
+ await control.close();
+ },
+ );
+
+ test(
+ 'switch after headers while body stays open cancels public search promptly',
+ () async {
+ stdout.writeln(
+ '[acceptance] uncooperative response body cannot keep A public operation alive',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final keys = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final consumed = Completer<void>();
+ final body = StreamController<List<int>>(onListen: consumed.complete);
+ final aApi = FakeTransport()
+ ..addResponse(VmodalResponse(statusCode: 200, body: body.stream));
+ final bApi = FakeTransport()..addJson({'data': <Object?>[]});
+ final control = manager(config, keys, [aApi, bApi]);
+ final map = sessions.mapping('same');
+ final a = await control.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final result = a.scope(map).search('query');
+ final rejected = expectLater(
+ result,
+ throwsA(isA<OperationCanceled>().having((e) => e.body, 'body', isNull)),
+ );
+ await consumed.future;
+ body.add('{"data":['.codeUnits);
+ final b = await control.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ await rejected.timeout(const Duration(seconds: 1));
+ body.add('{"asset_id":"A"}]}'.codeUnits);
+ await body.close();
+ expect((await b.scope(map).search('query')).assets, isEmpty);
+ expect(control.current, same(b));
+ await control.close();
+ },
+ );
+
+ test(
+ 'gateway retry queued for A does not dispatch after B activation',
+ () async {
+ stdout.writeln(
+ '[acceptance] real gateway retry delay retains originating lease',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test', maxRetries: 3);
+ final keys = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final consumed = Completer<void>();
+ Stream<List<int>> response() async* {
+ yield '{}'.codeUnits;
+ consumed.complete();
+ }
+
+ final aApi = FakeTransport()
+ ..addResponse(VmodalResponse(statusCode: 503, body: response()));
+ final bApi = FakeTransport()..addJson({'user_id': 'tenant-principal'});
+ final control = manager(config, keys, [aApi, bApi]);
+ final map = sessions.mapping('same');
+ final a = await control.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final read = a.verifyPrincipal('tenant-principal');
+ final rejected = expectLater(read, throwsA(isA<OperationCanceled>()));
+ await consumed.future;
+ await Future<void>.delayed(Duration.zero);
+ final b = await control.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ await rejected.timeout(const Duration(seconds: 1));
+ await Future<void>.delayed(const Duration(milliseconds: 80));
+ expect(aApi.requests, hasLength(1));
+ await b.verifyPrincipal('tenant-principal');
+ expect(control.current, same(b));
+ await control.close();
+ },
+ );
+
+ test(
+ 'A switch during shared renewal keeps B recovery and app identity alive',
+ () async {
+ stdout.writeln(
+ '[acceptance] tenant renewal continues for B; outgoing A provider stays closed',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final started = Completer<void>();
+ final pending = Completer<TenantCredential>();
+ var renewals = 0;
+ final keys = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ renew: () {
+ renewals++;
+ started.complete();
+ return pending.future;
+ },
+ );
+ final aApi = FakeTransport()..addJson({}, status: 401);
+ final bApi = FakeTransport()
+ ..addJson({}, status: 401)
+ ..addJson({'user_id': 'tenant-principal'});
+ final control = manager(config, keys, [aApi, bApi]);
+ final map = sessions.mapping('same');
+ final a = await control.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final old = a.verifyPrincipal('tenant-principal');
+ final rejected = expectLater(old, throwsA(isA<OperationCanceled>()));
+ await started.future;
+ final b = await control.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ final fresh = b.verifyPrincipal('tenant-principal');
+ await Future<void>.delayed(Duration.zero);
+ pending.complete(credential(config, 'rotated-key'));
+ await rejected;
+ await fresh;
+ expect(renewals, 1);
+ expect(aApi.requests, hasLength(1));
+ expect(bApi.requests.last.headers['Authorization'], 'Bearer rotated-key');
+ expect(b.context.appUserId, 'B');
+ expect(b.isActive, isTrue);
+ expect(control.current, same(b));
+ await control.close();
+ },
+ );
+
+ test('nested JSON maps with broad key types are immutable snapshots', () async {
+ stdout.writeln(
+ '[acceptance] JSON-compatible nested maps do not retain mutable caller state',
+ );
+ final cfg = sessions.setup();
+ final map = sessions.mapping('same');
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final nested = <Object?, Object?>{
+ 'filter': <Object?>['before'],
+ };
+ cfg.apis.single.addJson({'data': <Object?>[]});
+ final query = a
+ .scope(map)
+ .search(
+ 'same',
+ options: ScopedSearchOptions(queryMetadata: {'nested': nested}),
+ );
+ (nested['filter']! as List<Object?>)[0] = 'after';
+ await query;
+ final body = cfg.apis.single.requests.single.jsonBody! as Map;
+ expect(body['query_metadata'], {
+ 'nested': {
+ 'filter': ['before'],
+ },
+ });
+ await cfg.manager.close();
+ });
+
+ test(
+ 'non-string JSON keys and custom objects reject before dispatch',
+ () async {
+ stdout.writeln(
+ '[acceptance] malformed mutable option values never reach transport',
+ );
+ final cfg = sessions.setup();
+ final map = sessions.mapping('same');
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ for (final value in [
+ <Object?, Object?>{1: 'invalid'},
+ Object(),
+ ]) {
+ expect(
+ () => a
+ .scope(map)
+ .search(
+ 'same',
+ options: ScopedSearchOptions(queryMetadata: {'nested': value}),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ }
+ expect(cfg.apis.single.requests, isEmpty);
+ expect(a.isActive, isTrue);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'out-of-order renewals spanning A/B cannot overwrite newer B credential',
+ () async {
+ stdout.writeln(
+ '[acceptance] revision/ticket fencing survives app-user switch',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final old = Completer<TenantCredential>();
+ final newer = Completer<TenantCredential>();
+ var calls = 0;
+ final keys = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ renew: () => calls++ == 0 ? old.future : newer.future,
+ );
+ final aApi = FakeTransport();
+ final bApi = FakeTransport()..addJson({'data': <Object?>[]});
+ final control = manager(config, keys, [aApi, bApi]);
+ final map = sessions.mapping('same');
+ final a = await control.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final first = keys.renewCredential();
+ final b = await control.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ final second = keys.renewCredential(supersede: true);
+ newer.complete(credential(config, 'newer-key'));
+ await second;
+ old.complete(credential(config, 'older-key'));
+ await first;
+ await b.scope(map).search('B');
+ expect(keys.revision, 1);
+ expect(bApi.requests.single.headers['Authorization'], 'Bearer newer-key');
+ expect(a.isActive, isFalse);
+ expect(() => a.scope(map), throwsA(isA<OperationCanceled>()));
+ expect(control.current, same(b));
+ await control.close();
+ },
+ );
+
+ test(
+ 'authoritative key revocation blocks calls without logging app user out',
+ () async {
+ stdout.writeln(
+ '[acceptance] tenant connection failure preserves the active app identity',
+ );
+ final cfg = sessions.setup();
+ final map = sessions.mapping('same');
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final id = a.sessionId;
+ cfg.credentials.revoke();
+ await expectLater(
+ a.scope(map).search('blocked'),
+ throwsA(isA<TenantAuthException>()),
+ );
+ expect(cfg.apis.single.requests, isEmpty);
+ expect(a.isActive, isTrue);
+ expect(cfg.manager.current, same(a));
+ expect(a.context.appUserId, 'A');
+ cfg.credentials.install(
+ credential(SdkConfig(baseUrl: 'https://gateway.test'), 'recovered-key'),
+ );
+ cfg.apis.single.addJson({'data': <Object?>[]});
+ await a.scope(map).search('recovered');
+ expect(a.sessionId, id);
+ expect(
+ cfg.apis.single.requests.single.headers['Authorization'],
+ 'Bearer recovered-key',
+ );
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'service/principal binding replacements and caller checkpoint stores reject locally',
+ () async {
+ stdout.writeln(
+ '[acceptance] in-place credential identity changes and unbound storage reject',
+ );
+ final cfg = sessions.setup();
+ final map = sessions.mapping('same', actions: {UserAction.upload});
+ final a = await cfg.manager.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ for (final candidate in [
+ TenantCredential(
+ serviceNamespace: 'https://another.test',
+ tenantId: 'same-tenant',
+ principal: 'tenant-principal',
+ apiKey: 'same-key',
+ ),
+ TenantCredential(
+ serviceNamespace: a.context.serviceNamespace,
+ tenantId: 'another',
+ principal: 'tenant-principal',
+ apiKey: 'same-key',
+ ),
+ TenantCredential(
+ serviceNamespace: a.context.serviceNamespace,
+ tenantId: 'same-tenant',
+ principal: 'another',
+ apiKey: 'same-key',
+ ),
+ ]) {
+ expect(
+ () => cfg.credentials.install(candidate),
+ throwsA(isA<TenantAuthException>()),
+ );
+ }
+ expect(cfg.credentials.revision, 0);
+ expect(cfg.credentials.currentSnapshot.apiKey, 'same-key');
+ final hook = CustomPassthroughSubclass();
+ expect(
+ () => a
+ .scope(map)
+ .upload(
+ uploadSource(),
+ options: ScopedUploadOptions(
+ uploadOptions: VideoUploadOptions(transcoder: hook),
+ ),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(hook.called, isFalse);
+ expect(
+ () => a
+ .scope(map)
+ .upload(
+ uploadSource(),
+ options: ScopedUploadOptions(
+ uploadOptions: VideoUploadOptions(
+ sessionStore: MemoryUploadSessionStore(),
+ ),
+ ),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.single.requests, isEmpty);
+ expect(cfg.signed.single.calls, isEmpty);
+ expect(a.isActive, isTrue);
+ await cfg.manager.close();
+ },
+ );
+
+ for (final phase in ['signed', 'retry', 'verification', 'completion']) {
+ test('multipart switch during $phase prevents all later A phases', () async {
+ stdout.writeln(
+ '[acceptance] multipart A lease at $phase; no late signed retry/finalization',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final keys = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final source = uploadSource();
+ final digest = await md5Hex(source, offset: 0, length: 1);
+ final reached = Completer<void>();
+ final release = Completer<VmodalResponse>();
+ final signed = AcceptanceSignedTransport();
+ var statuses = 0;
+ final aApi = HandlerTransport((request) async {
+ final path = request.uri.path;
+ if (path.endsWith(Routes.externalUploadMultipartCreate)) {
+ return jsonResponse(
+ '{"request_id":"r","upload_id":"u","key":"k","part_count":1,"part_size_bytes":5242880}',
+ );
+ }
+ if (path.endsWith(Routes.externalUploadMultipartSignParts)) {
+ return jsonResponse(
+ '{"parts":[{"part_number":1,"url":"https://objects.test/1","method":"PUT"}]}',
+ );
+ }
+ if (path.endsWith(Routes.externalUploadMultipartStatus)) {
+ statuses++;
+ if (statuses == 1 || phase == 'retry') {
+ if (statuses == 2) reached.complete();
+ return jsonResponse('{"status":"uploading","parts":[]}');
+ }
+ if (phase == 'verification') {
+ reached.complete();
+ return release.future;
+ }
+ return jsonResponse(
+ '{"status":"uploading","parts":[{"part_number":1,"size_bytes":1,"etag":"$digest"}]}',
+ );
+ }
+ if (path.endsWith(Routes.externalUploadMultipartComplete)) {
+ reached.complete();
+ return release.future;
+ }
+ throw StateError('A dispatched unexpected phase: $path');
+ });
+ final bApi = FakeTransport()..addJson({'data': <Object?>[]});
+ final control = manager(config, keys, [aApi, bApi], signed: signed);
+ final map = sessions.mapping(
+ 'same',
+ actions: {UserAction.search, UserAction.upload},
+ );
+ final a = await control.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final task = a
+ .scope(map)
+ .upload(
+ source,
+ options: const ScopedUploadOptions(
+ uploadOptions: VideoUploadOptions(
+ multipart: true,
+ partSizeBytes: 5242880,
+ maxConcurrency: 1,
+ maxPartAttempts: 3,
+ ),
+ ),
+ );
+ final progress = <UploadProgress>[];
+ final subscription = task.progress.listen(
+ progress.add,
+ onError: (Object _) {},
+ );
+ final rejected = expectLater(
+ task.result,
+ throwsA(isA<OperationCanceled>()),
+ );
+ await signed.started.future;
+ if (phase != 'signed') {
+ if (phase == 'retry') {
+ signed.release.completeError(
+ SignedUploadFailure(sentBytes: 1, localMd5: digest),
+ );
+ } else {
+ signed.release.complete(
+ SignedUploadResult(statusCode: 200, etag: digest, localMd5: digest),
+ );
+ }
+ await reached.future;
+ await Future<void>.delayed(Duration.zero);
+ }
+ final requestsBefore = aApi.requests.length;
+ final b = await control.openResolvedSession(
+ () async => sessions.policy('B', map),
+ );
+ final emittedBefore = progress.length;
+ await rejected.timeout(const Duration(seconds: 1));
+ signed.emit?.call(const UploadProgress(1, 1));
+ if (phase == 'signed') {
+ signed.release.complete(
+ SignedUploadResult(statusCode: 200, etag: digest, localMd5: digest),
+ );
+ } else if (phase == 'verification' || phase == 'completion') {
+ release.complete(
+ jsonResponse('{"etag":"completed","status":"completed","parts":[]}'),
+ );
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 300));
+ expect(progress, hasLength(emittedBefore));
+ expect(aApi.requests, hasLength(requestsBefore));
+ expect(signed.calls, hasLength(1));
+ expect(
+ signed.calls.single.headers.keys.map((k) => k.toLowerCase()),
+ isNot(contains('authorization')),
+ );
+ expect(
+ aApi.requests.where(
+ (r) => r.uri.path.endsWith(Routes.externalUploadDone),
+ ),
+ isEmpty,
+ );
+ await b.scope(map).search('B still works');
+ expect(control.current, same(b));
+ await subscription.cancel();
+ await control.close();
+ });
+ }
+
+ test(
+ 'rotation while signed PUT waits preserves scope and uses fresh gateway finalization',
+ () async {
+ stdout.writeln(
+ '[acceptance] independent signed capability remains bearer-free across rotation',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final keys = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final api = FakeTransport()
+ ..addJson({
+ 'url': 'https://objects.test/same?signature=old',
+ 'key': 'k',
+ 'method': 'PUT',
+ })
+ ..addJson({'asset_id': 'a', 'filename': 'same.mp4'});
+ final signed = AcceptanceSignedTransport();
+ final control = manager(config, keys, [api], signed: signed);
+ final map = sessions.mapping('same', actions: {UserAction.upload});
+ final a = await control.openResolvedSession(
+ () async => sessions.policy('A', map),
+ );
+ final owner = a.context.ownerKey;
+ final scope = a.context.scopeKey(map);
+ final id = a.sessionId;
+ final task = a.scope(map).upload(uploadSource());
+ await signed.started.future;
+ keys.install(credential(config, 'rotated-key'));
+ signed.release.complete(
+ const SignedUploadResult(statusCode: 200, etag: 'e'),
+ );
+ expect((await task.result).asset?.assetId, 'a');
+ expect(a.context.ownerKey, owner);
+ expect(a.context.scopeKey(map), scope);
+ expect(a.sessionId, id);
+ expect(api.requests.first.headers['Authorization'], 'Bearer same-key');
+ expect(api.requests.last.headers['Authorization'], 'Bearer rotated-key');
+ expect(signed.calls.single.url.queryParameters['signature'], 'old');
+ expect(
+ signed.calls.single.headers.keys.map((k) => k.toLowerCase()),
+ isNot(contains('authorization')),
+ );
+ await control.close();
+ },
+ );
+}
diff --git a/test/user_session_test.dart b/test/user_session_test.dart
new file mode 100644
index 0000000..46864e9
--- /dev/null
+++ b/test/user_session_test.dart
@@ -0,0 +1,383 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+
+import 'fakes.dart';
+
+ContentMapping mapping(String collection, {Set<UserAction>? actions}) =>
+ ContentMapping.opaque(
+ collectionId: collection,
+ streamName: 'camera',
+ actions: actions ?? const <UserAction>{UserAction.search},
+ );
+
+UserSessionPolicy policy(String user, ContentMapping content) =>
+ UserSessionPolicy(
+ tenantId: 'same-tenant',
+ appUserId: user,
+ allowedContentMapping: <ContentMapping>[content],
+ );
+
+({
+ UserSessionManager manager,
+ TenantCredentialSource credentials,
+ List<FakeTransport> apis,
+ List<FakeSignedUploadTransport> signed,
+})
+setup() {
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final credentials = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ final apis = <FakeTransport>[];
+ final signed = <FakeSignedUploadTransport>[];
+ final manager = UserSessionManager(
+ config: config,
+ credentialSource: credentials,
+ transportFactory: (_) {
+ final api = FakeTransport();
+ apis.add(api);
+ return api;
+ },
+ signedUploadTransportFactory: (_) {
+ final transport = FakeSignedUploadTransport();
+ signed.add(transport);
+ return transport;
+ },
+ );
+ return (
+ manager: manager,
+ credentials: credentials,
+ apis: apis,
+ signed: signed,
+ );
+}
+
+void main() {
+ test(
+ 'owner identity preserves exact authenticated user characters',
+ () async {
+ final env = setup();
+ addTearDown(env.manager.close);
+ final content = mapping('shared-scope');
+ final a = await env.manager.openResolvedSession(
+ () async => policy('A', content),
+ );
+ final spaced = await env.manager.openResolvedSession(
+ () async => policy(' A ', content),
+ );
+ expect(spaced.context.appUserId, ' A ');
+ expect(spaced.context.ownerKey, isNot(a.context.ownerKey));
+ expect(
+ spaced.context.scopeKey(content),
+ isNot(a.context.scopeKey(content)),
+ );
+ },
+ );
+
+ test(
+ 'reentrant invalidation callback can activate only its latest ticket',
+ () async {
+ stdout.writeln(
+ '[user-session] callback reentry after synchronous invalidation',
+ );
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final credentials = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ late UserSessionManager manager;
+ Future<UserSession>? reentered;
+ manager = UserSessionManager(
+ config: config,
+ credentialSource: credentials,
+ transportFactory: (_) => FakeTransport(),
+ signedUploadTransportFactory: (_) => FakeSignedUploadTransport(),
+ onInvalidated: (session) {
+ expect(session.isActive, isFalse);
+ if (session.context.appUserId == 'A') {
+ reentered = manager.openResolvedSession(
+ () async => policy('C', mapping('C')),
+ );
+ }
+ },
+ );
+ await manager.openResolvedSession(() async => policy('A', mapping('A')));
+ await expectLater(
+ manager.openResolvedSession(() async => policy('B', mapping('B'))),
+ throwsA(isA<OperationCanceled>()),
+ );
+ final c = await reentered!;
+ expect(manager.current, same(c));
+ expect(c.context.appUserId, 'C');
+ await manager.close();
+ },
+ );
+
+ test(
+ 'same tenant key A/B switch invalidates A and rejects B selectors',
+ () async {
+ stdout.writeln(
+ '[user-session] same tenant, same credential; distinct runtime ownership',
+ );
+ final cfg = setup();
+ final aMap = mapping('A');
+ final bMap = mapping('B');
+ final a = await cfg.manager.openResolvedSession(
+ () async => policy('A', aMap),
+ );
+ final scope = a.scope(aMap);
+ expect(() => a.scope(bMap), throwsA(isA<ValidationException>()));
+ final openingB = cfg.manager.openResolvedSession(
+ () async => policy('B', bMap),
+ );
+ expect(a.isActive, isFalse);
+ expect(() => scope.search('old'), throwsA(isA<OperationCanceled>()));
+ final b = await openingB;
+ expect(b.sessionId, isNot(a.sessionId));
+ expect(b.context.ownerKey, isNot(a.context.ownerKey));
+ cfg.apis.last.addJson(<String, Object?>{'data': <Object?>[]});
+ await b.scope(bMap).search('new');
+ expect(
+ cfg.apis.last.requests.single.headers['Authorization'],
+ 'Bearer same-key',
+ );
+ expect(
+ cfg.apis.last.requests.single.headers,
+ isNot(contains('X-User-Id')),
+ );
+ expect(cfg.apis.first.requests, isEmpty);
+ await cfg.manager.close();
+ },
+ );
+
+ test('late activation cannot publish over the newer ticket', () async {
+ stdout.writeln('[user-session] out-of-order host identity resolution');
+ final cfg = setup();
+ final pending = Completer<UserSessionPolicy>();
+ final openingA = cfg.manager.openResolvedSession(() => pending.future);
+ final rejection = expectLater(openingA, throwsA(isA<OperationCanceled>()));
+ final b = await cfg.manager.openResolvedSession(
+ () async => policy('B', mapping('B')),
+ );
+ pending.complete(policy('A', mapping('A')));
+ await rejection;
+ expect(cfg.manager.current, same(b));
+ expect(cfg.apis, hasLength(1));
+ await cfg.manager.close();
+ });
+
+ test(
+ 'late I/O is discarded promptly when custom transport ignores cancellation',
+ () async {
+ stdout.writeln(
+ '[user-session] pending A response is never delivered after switch',
+ );
+ final response = Completer<VmodalResponse>();
+ final config = SdkConfig(baseUrl: 'https://gateway.test');
+ final credentials = TenantCredentialSource(
+ serviceNamespace: SessionContext.serviceNamespaceFor(config),
+ tenantId: 'same-tenant',
+ expectedPrincipal: 'tenant-principal',
+ initialKey: 'same-key',
+ );
+ var first = true;
+ final manager = UserSessionManager(
+ config: config,
+ credentialSource: credentials,
+ transportFactory: (_) {
+ if (first) {
+ first = false;
+ return HandlerTransport((_) => response.future);
+ }
+ return FakeTransport();
+ },
+ signedUploadTransportFactory: (_) => FakeSignedUploadTransport(),
+ );
+ final map = mapping('same-selector');
+ final a = await manager.openResolvedSession(() async => policy('A', map));
+ final result = a.scope(map).search('private A');
+ final rejected = expectLater(result, throwsA(isA<OperationCanceled>()));
+ final b = await manager.openResolvedSession(() async => policy('B', map));
+ await rejected.timeout(const Duration(seconds: 2));
+ response.complete(jsonResponse('{"data":[{"private":"A"}]}'));
+ await Future<void>.delayed(Duration.zero);
+ expect(manager.current, same(b));
+ expect(b.isActive, isTrue);
+ await manager.close();
+ },
+ );
+
+ test(
+ 'A to B to A keeps old generation retired and stable owner namespaces',
+ () async {
+ stdout.writeln(
+ '[user-session] stable owner keys with fresh A generations',
+ );
+ final cfg = setup();
+ final map = mapping('shared');
+ final oldA = await cfg.manager.openResolvedSession(
+ () async => policy('A', map),
+ );
+ final b = await cfg.manager.openResolvedSession(
+ () async => policy('B', map),
+ );
+ final newA = await cfg.manager.openResolvedSession(
+ () async => policy('A', map),
+ );
+ expect(oldA.isActive, isFalse);
+ expect(b.isActive, isFalse);
+ expect(newA.context.ownerKey, oldA.context.ownerKey);
+ expect(newA.context.scopeKey(map), oldA.context.scopeKey(map));
+ expect(newA.sessionId, isNot(oldA.sessionId));
+ final closing = oldA.close();
+ expect(oldA.close(), same(closing));
+ await closing;
+ expect(cfg.manager.current, same(newA));
+ expect(cfg.apis.last.closed, isFalse);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'caller policy and nested options are snapshotted before request dispatch',
+ () async {
+ stdout.writeln(
+ '[user-session] immutable mappings and nested request options',
+ );
+ final cfg = setup();
+ final actions = <UserAction>{UserAction.search};
+ final map = mapping('opaque__unchanged', actions: actions);
+ final mappings = <ContentMapping>[map];
+ final opening = cfg.manager.openUserSession(
+ tenantId: 'same-tenant',
+ appUserId: 'A',
+ allowedContentMapping: mappings,
+ );
+ mappings.clear();
+ actions.clear();
+ final session = await opening;
+ final nested = <String, Object?>{
+ 'nested': <Object?>['before'],
+ };
+ final sources = <String>['asr'];
+ cfg.apis.single.addJson(<String, Object?>{'data': <Object?>[]});
+ final result = session
+ .scope(map)
+ .search(
+ 'query',
+ options: ScopedSearchOptions(
+ queryMetadata: nested,
+ searchSources: sources,
+ ),
+ );
+ (nested['nested']! as List<Object?>)[0] = 'after';
+ sources.clear();
+ await result;
+ final request = cfg.apis.single.requests.single.jsonBody! as Map;
+ expect(request['group_name'], 'opaque__unchanged');
+ expect(request['query_metadata'], <String, Object?>{
+ 'nested': <Object?>['before'],
+ });
+ expect(request['search_sources'], <String>['asr']);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'same tenant key rotation preserves session and uses new key for future requests',
+ () async {
+ stdout.writeln(
+ '[user-session] tenant credential rotation keeps owner and scope stable',
+ );
+ final cfg = setup();
+ final map = mapping('A');
+ final session = await cfg.manager.openResolvedSession(
+ () async => policy('A', map),
+ );
+ final owner = session.context.ownerKey;
+ final generation = session.sessionId;
+ cfg.credentials.install(
+ TenantCredential(
+ serviceNamespace: session.context.serviceNamespace,
+ tenantId: 'same-tenant',
+ principal: 'tenant-principal',
+ apiKey: 'new-key',
+ ),
+ );
+ cfg.apis.single.addJson(<String, Object?>{'data': <Object?>[]});
+ await session.scope(map).search('after rotation');
+ expect(session.context.ownerKey, owner);
+ expect(session.sessionId, generation);
+ expect(
+ cfg.apis.single.requests.single.headers['Authorization'],
+ 'Bearer new-key',
+ );
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'mode override and stream-only deletion reject before dispatch',
+ () async {
+ stdout.writeln(
+ '[user-session] exact mode and collection-wide permission checks',
+ );
+ final cfg = setup();
+ final map = mapping(
+ 'A',
+ actions: <UserAction>{UserAction.search, UserAction.delete},
+ );
+ final session = await cfg.manager.openResolvedSession(
+ () async => policy('A', map),
+ );
+ expect(
+ () => session
+ .scope(map)
+ .search(
+ 'query',
+ options: const ScopedSearchOptions(mode: 'img_file'),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(
+ () => session.scope(map).deleteCollection(),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.apis.single.requests, isEmpty);
+ await cfg.manager.close();
+ },
+ );
+
+ test(
+ 'logout fences pending resolution and failed activation leaves manager empty',
+ () async {
+ stdout.writeln('[user-session] logout during host resolution');
+ final cfg = setup();
+ final pending = Completer<UserSessionPolicy>();
+ final opening = cfg.manager.openResolvedSession(() => pending.future);
+ final rejected = expectLater(opening, throwsA(isA<OperationCanceled>()));
+ await cfg.manager.logout();
+ pending.complete(policy('A', mapping('A')));
+ await rejected;
+ expect(cfg.manager.current, isNull);
+ await expectLater(
+ cfg.manager.openUserSession(
+ tenantId: 'different',
+ appUserId: 'A',
+ allowedContentMapping: <ContentMapping>[mapping('A')],
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(cfg.manager.current, isNull);
+ await cfg.manager.close();
+ },
+ );
+}
diff --git a/test/workflow_layout_test.dart b/test/workflow_layout_test.dart
index 97b7d05..1c542fe 100644
--- a/test/workflow_layout_test.dart
+++ b/test/workflow_layout_test.dart
@@ -12,7 +12,9 @@ final publicFile = File('release/public_publish.yml').existsSync()
? File('release/public_publish.yml')
: File('.github/workflows/publish.yml');
final public = publicFile.readAsStringSync();
-final release = File('ga_release.sh').readAsStringSync();
+final release = internal.isEmpty
+ ? ''
+ : File('ga_release.sh').readAsStringSync();
final androidProperties = File(
'example/01_full_app/android/gradle.properties',
).readAsStringSync();