Skip to content

Commit 88c72c6

Browse files
Validate region URLs before failing over to them (#1270)
Flutter port of livekit/rust-sdks#1601, livekit/client-sdk-swift#1182 and livekit/client-sdk-android#1052. ## What `isCloud()` is checked against the server URL the application supplied, to decide whether region discovery applies at all. The URLs that came back were then used as they arrived — `fetchRegionSettings` builds a `RegionInfo` straight from `region['url']`, and `getNextBestRegionUrl()` hands that to the connect path. Those URLs are not just connected to, they are authenticated to: `fetchRegionSettings` sends the participant token as a bearer header. An entry should stand on its own merits rather than inherit trust from the configured server URL, and it should not be able to move that exchange onto cleartext. ## Two changes **1. Validate returned region URLs.** New `isTrustedRegionUrl`: must parse, have a host, name a `.livekit.cloud` / `.livekit.run` host, and use `wss` or `https`. Applied to **both** sources of a region list — the `/settings/regions` response *and* `setServerReportedRegions`, which takes the regions the server reports over signalling. Both were unvalidated. Rejections are logged, not silent. **2. `isCloudUrl` matched with `contains`, not a suffix.** This one is Flutter-specific — Rust, Swift and Android all match on the suffix: ```dart // before return uri.host.contains('.livekit.cloud') || uri.host.contains('.livekit.run'); ``` So any host with `.livekit.cloud` anywhere inside it counted as LiveKit Cloud. `project.livekit.cloud.example.com` is someone else's host, and treating it as Cloud sends it the region request with the token attached. Now matched on the suffix, with the host lower-cased first. That second change also tightens `isCloudUrl`'s four other callers: the region gate in `Room`, and the TURN, websocket and cloud-region connection checks. Worth a reviewer's eye — it is strictly more restrictive, and matches the other three SDKs. ## Tests Twelve tests covering both predicates across cloud hosts, cleartext schemes, foreign hosts, suffix near-misses and malformed input, plus one covering the server-reported ingestion path. The suffix test and the ingestion test were both **verified to fail without this change**. Full suite: **501 tests pass**. `flutter analyze`, `dart format` and `import_sorter` all clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com>
1 parent b97e902 commit 88c72c6

3 files changed

Lines changed: 135 additions & 6 deletions

File tree

‎.changes/validate-region-urls‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
patch type="fixed" "Region URLs returned by region discovery are now validated before the SDK fails over to them. Only encrypted (`wss`/`https`) LiveKit Cloud URLs are accepted, and the check is applied to both sources of a region list: the `/settings/regions` response and the regions the server reports over signalling. `isCloudUrl` also now matches the Cloud domains on the host suffix rather than with `contains`, so a host such as `project.livekit.cloud.example.com` is no longer treated as LiveKit Cloud"

‎lib/src/support/region_url_provider.dart‎

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,10 @@ class RegionUrlProvider {
8585
),
8686
)
8787
.toList();
88-
final regionSettings = lk_models.RegionSettings(
89-
regions: regions,
90-
);
9188
lastUpdateAt = DateTime.timestamp().millisecondsSinceEpoch;
92-
return regionSettings;
89+
return lk_models.RegionSettings(
90+
regions: _trustedRegions(regions),
91+
);
9392
} else {
9493
throw ConnectException(
9594
'Could not fetch region settings: ${regionSettingsResponse.body}, status: ${regionSettingsResponse.statusCode}',
@@ -102,10 +101,25 @@ class RegionUrlProvider {
102101
}
103102

104103
void setServerReportedRegions(lk_models.RegionSettings regions) {
105-
regionSettings = regions;
104+
regionSettings = lk_models.RegionSettings(
105+
regions: _trustedRegions(regions.regions),
106+
);
106107
lastUpdateAt = DateTime.timestamp().millisecondsSinceEpoch;
107108
}
108109

110+
/// Keeps only the regions this SDK may fail over to, reporting what it dropped.
111+
///
112+
/// Both sources of a region list are network input, and every URL kept here is later connected
113+
/// to with the participant token. See [isTrustedRegionUrl].
114+
List<lk_models.RegionInfo> _trustedRegions(List<lk_models.RegionInfo> regions) {
115+
final trusted = regions.where((region) => isTrustedRegionUrl(region.url)).toList();
116+
final rejected = regions.length - trusted.length;
117+
if (rejected > 0) {
118+
logger.warning('ignoring $rejected of ${regions.length} regions: not an encrypted LiveKit Cloud URL');
119+
}
120+
return trusted;
121+
}
122+
109123
String getCloudConfigUrl(Uri serverUrl) {
110124
return '${serverUrl.scheme.replaceAll('ws', 'http')}://${serverUrl.host}/settings';
111125
}
@@ -125,8 +139,30 @@ extension RegionSettingsExtension on lk_models.RegionSettings {
125139
);
126140
}
127141

142+
/// Whether [uri] names a LiveKit Cloud project.
143+
///
144+
/// Matched on the suffix, not with `contains`: a host only belongs to LiveKit Cloud when it ends
145+
/// in one of these domains. `project.livekit.cloud.example.com` contains `.livekit.cloud` but is
146+
/// someone else's host, and treating it as Cloud would send it the region request — with the
147+
/// participant token attached.
128148
bool isCloudUrl(Uri uri) {
129-
return uri.host.contains('.livekit.cloud') || uri.host.contains('.livekit.run');
149+
final host = uri.host.toLowerCase();
150+
return host.endsWith('.livekit.cloud') || host.endsWith('.livekit.run');
151+
}
152+
153+
/// Whether [url] is a region URL the SDK may fail over to.
154+
///
155+
/// A region list arrives over the network — from `/settings/regions` and from the regions the
156+
/// server reports over signalling — and the SDK authenticates to whatever it names, sending the
157+
/// participant token as a bearer header. Each entry is therefore checked on its own merits rather
158+
/// than inheriting trust from the server URL the application supplied, and `ws`/`http` entries are
159+
/// refused so a region list cannot move that exchange onto cleartext.
160+
bool isTrustedRegionUrl(String url) {
161+
final uri = Uri.tryParse(url);
162+
if (uri == null || uri.host.isEmpty) return false;
163+
final scheme = uri.scheme.toLowerCase();
164+
if (scheme != 'wss' && scheme != 'https') return false;
165+
return isCloudUrl(uri);
130166
}
131167

132168
/// Whether a failed connection attempt may be retried against a different LiveKit Cloud region.

‎test/support/region_failover_test.dart‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15+
import 'package:fixnum/fixnum.dart';
1516
import 'package:flutter_test/flutter_test.dart';
1617

1718
import 'package:livekit_client/src/exceptions.dart';
19+
import 'package:livekit_client/src/proto/livekit_rtc.pb.dart' as lk_models;
1820
import 'package:livekit_client/src/support/region_url_provider.dart';
1921
import 'package:livekit_client/src/support/websocket.dart' show WebSocketException;
2022

@@ -67,4 +69,94 @@ void main() {
6769
expect(canFailOverToAnotherRegion(StateError('boom')), isFalse);
6870
});
6971
});
72+
73+
group('isCloudUrl', () {
74+
test('accepts LiveKit Cloud hosts', () {
75+
for (final url in [
76+
'wss://project.livekit.cloud',
77+
'wss://project.otokyo1a.production.livekit.cloud',
78+
'wss://project.livekit.run',
79+
'wss://PROJECT.LIVEKIT.CLOUD',
80+
]) {
81+
expect(isCloudUrl(Uri.parse(url)), isTrue, reason: url);
82+
}
83+
});
84+
85+
test('matches the suffix, not a substring anywhere in the host', () {
86+
// `project.livekit.cloud.example.com` contains `.livekit.cloud` but belongs to someone
87+
// else; treating it as Cloud would send it the region request with the token attached.
88+
for (final url in [
89+
'wss://project.livekit.cloud.example.com',
90+
'wss://livekit.run.example.com',
91+
'wss://not-livekit.cloud',
92+
'wss://self-hosted.example.com',
93+
'ws://localhost:7880',
94+
]) {
95+
expect(isCloudUrl(Uri.parse(url)), isFalse, reason: url);
96+
}
97+
});
98+
});
99+
100+
group('isTrustedRegionUrl', () {
101+
test('accepts encrypted LiveKit Cloud urls', () {
102+
for (final url in [
103+
'wss://eu.livekit.cloud',
104+
'https://eu.livekit.cloud',
105+
'https://eu.livekit.cloud:443/rtc',
106+
'wss://staging.livekit.run',
107+
]) {
108+
expect(isTrustedRegionUrl(url), isTrue, reason: url);
109+
}
110+
});
111+
112+
test('rejects cleartext schemes even for a real cloud host', () {
113+
for (final url in ['ws://eu.livekit.cloud', 'http://eu.livekit.cloud']) {
114+
expect(isTrustedRegionUrl(url), isFalse, reason: url);
115+
}
116+
});
117+
118+
test('rejects foreign hosts and suffix near-misses', () {
119+
for (final url in [
120+
'https://other.example.com',
121+
'wss://other.example.com/rtc',
122+
'https://not-livekit.cloud',
123+
'https://livekit.cloud.example.com',
124+
// The one a `contains` match would wrongly accept: the dot-prefixed domain appears in
125+
// the middle of someone else's host.
126+
'https://project.livekit.cloud.example.com',
127+
]) {
128+
expect(isTrustedRegionUrl(url), isFalse, reason: url);
129+
}
130+
});
131+
132+
test('rejects malformed and hostless urls', () {
133+
for (final url in ['', 'eu.livekit.cloud', 'file:///etc/passwd', '::::']) {
134+
expect(isTrustedRegionUrl(url), isFalse, reason: url);
135+
}
136+
});
137+
});
138+
139+
group('region ingestion', () {
140+
lk_models.RegionInfo region(String name, String url) =>
141+
lk_models.RegionInfo(region: name, url: url, distance: Int64(1));
142+
143+
test('server reported regions drop entries the SDK must not fail over to', () async {
144+
final provider = RegionUrlProvider(url: 'wss://project.livekit.cloud', token: 'token');
145+
146+
provider.setServerReportedRegions(
147+
lk_models.RegionSettings(
148+
regions: [
149+
region('foreign', 'https://other.example.com'),
150+
region('cleartext', 'ws://cleartext.livekit.cloud'),
151+
region('near-miss', 'https://livekit.cloud.example.com'),
152+
region('good', 'https://good.livekit.cloud'),
153+
],
154+
),
155+
);
156+
157+
expect(provider.regionSettings!.regions.map((r) => r.url), ['https://good.livekit.cloud']);
158+
expect(await provider.getNextBestRegionUrl(), 'https://good.livekit.cloud');
159+
expect(await provider.getNextBestRegionUrl(), isNull);
160+
});
161+
});
70162
}

0 commit comments

Comments
 (0)