Load ShopinBit image attachments with header auth
What changed, and why it matters
This commit fixes a privacy/credential-leak issue in Stack Wallet's ShopinBit support-ticket feature. Previously, image attachments were downloaded using a URL that contained the user's secret access token and customer key as visible query parameters. Because the app's HTTP wrapper logs failed requests and Dart's networking exceptions include the full URL, those secret credentials could have been written to log files on the device. The patch switches to sending the credentials as HTTP headers instead, so the URL stays plain and the sensitive values are not embedded in it. A new test confirms the image loader accepts headers but still caches images by URL alone.
Treat this as a security-hardening fix and include it in the next release. Review whether any existing device logs or crash reports may already contain leaked `Authorization` or `External-Customer-Key` query parameters, and consider rotating any exposed tokens or customer keys. Audit other uses of `getAttachmentUrl` with `useQueryAuth: true` across the codebase to ensure none remain.
Security signals we found
Credential exposure in URLs moved to HTTP headers
HTTP request logging and exception messages could previously leak bearer token and customer key
New `AttachmentRequest` typedef encapsulates URI + headers
Cache key isolation from auth headers prevents unnecessary refetches
Unit test added for header behavior and cache-key equality
Evidence from the diff
The change refactors attachment image loading in lib/pages/shopinbit/shopinbit_ticket_detail.dart to call a new getAttachmentRequest() method that returns a plain Uri plus an Authorization: Bearer <token> and optional External-Customer-Key header map, replacing getAttachmentUrl(..., useQueryAuth: true). TorAwareNetworkImage and fetchTorAwareBytes in lib/networking/tor_aware_network_image.dart are extended to accept optional headers and pass them to the underlying HTTP().get() call. The image cache key remains based only on the URL, so changing headers (e.g., a refreshed token) does not trigger a refetch. A unit test verifies that headers are sent and that two TorAwareNetworkImage instances with different headers but the same URL compare equal.
Changed components
lib/networking/tor_aware_network_image.dartlib/pages/shopinbit/shopinbit_ticket_detail.dartlib/services/shopinbit/src/client.darttest/networking/tor_aware_network_image_test.dartInspect captured patch +96 / −18
### lib/networking/tor_aware_network_image.dart
@@ -14,9 +14,13 @@ import 'http.dart';
/// Fetches [url] through the app's [HTTP] client, routing over Tor when it is
/// enabled. Throws if Tor is enabled but not connected, so nothing falls back
/// to clearnet.
-Future<Uint8List> fetchTorAwareBytes(String url) async {
+Future<Uint8List> fetchTorAwareBytes(
+ String url, {
+ Map<String, String>? headers,
+}) async {
final response = await const HTTP().get(
url: Uri.parse(url),
+ headers: headers,
proxyInfo: !AppConfig.hasFeature(AppFeature.tor)
? null
: Prefs.instance.useTor
@@ -35,10 +39,14 @@ Future<Uint8List> fetchTorAwareBytes(String url) async {
/// Use with [Image] instead of [Image.network], which always goes clearnet.
@immutable
class TorAwareNetworkImage extends ImageProvider<TorAwareNetworkImage> {
- const TorAwareNetworkImage(this.url);
+ const TorAwareNetworkImage(this.url, {this.headers});
final String url;
+ /// Sent with the request but not part of the cache key, so e.g. a refreshed
+ /// auth token doesn't cause a refetch.
+ final Map<String, String>? headers;
+
@override
Future<TorAwareNetworkImage> obtainKey(ImageConfiguration configuration) =>
SynchronousFuture<TorAwareNetworkImage>(this);
@@ -70,7 +78,7 @@ class TorAwareNetworkImage extends ImageProvider<TorAwareNetworkImage> {
expectedTotalBytes: null,
),
);
- final bytes = await fetchTorAwareBytes(key.url);
+ final bytes = await fetchTorAwareBytes(key.url, headers: key.headers);
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
return await decode(buffer);
} catch (_) {
### lib/pages/shopinbit/shopinbit_ticket_detail.dart
@@ -827,9 +827,9 @@ class _AttachmentChip extends StatelessWidget {
/// Renders an authenticated `/attachment-proxy/` image.
///
-/// The signed URL future is built once in [initState] (and only rebuilt when
+/// The request future is built once in [initState] (and only rebuilt when
/// [proxyPath] or [customerKey] actually change) so the surrounding 30s poll
-/// can't re-fire `getAttachmentUrl`/re-fetch the image on every rebuild.
+/// can't re-fire `getAttachmentRequest`/re-fetch the image on every rebuild.
class _ProxyImage extends StatefulWidget {
const _ProxyImage({
required this.client,
@@ -848,26 +848,25 @@ class _ProxyImage extends StatefulWidget {
}
class _ProxyImageState extends State<_ProxyImage> {
- late Future<ApiResponse<Uri>> _urlFuture;
+ late Future<ApiResponse<AttachmentRequest>> _requestFuture;
- Future<ApiResponse<Uri>> _buildFuture() => widget.client.getAttachmentUrl(
- widget.proxyPath,
- useQueryAuth: true,
- customerKey: widget.customerKey,
- );
+ // Header auth: a query-auth URL would put the token and customer key into
+ // logged HTTP errors.
+ Future<ApiResponse<AttachmentRequest>> _buildFuture() => widget.client
+ .getAttachmentRequest(widget.proxyPath, customerKey: widget.customerKey);
@override
void initState() {
super.initState();
- _urlFuture = _buildFuture();
+ _requestFuture = _buildFuture();
}
@override
void didUpdateWidget(covariant _ProxyImage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.proxyPath != widget.proxyPath ||
oldWidget.customerKey != widget.customerKey) {
- _urlFuture = _buildFuture();
+ _requestFuture = _buildFuture();
}
}
@@ -879,8 +878,8 @@ class _ProxyImageState extends State<_ProxyImage> {
borderRadius: BorderRadius.circular(8),
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: _kAttachmentMaxHeight),
- child: FutureBuilder<ApiResponse<Uri>>(
- future: _urlFuture,
+ child: FutureBuilder<ApiResponse<AttachmentRequest>>(
+ future: _requestFuture,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const SizedBox(
@@ -896,7 +895,10 @@ class _ProxyImageState extends State<_ProxyImage> {
image: ResizeImage.resizeIfNeeded(
null,
_kAttachmentDecodeHeight,
- TorAwareNetworkImage(resp.value!.toString()),
+ TorAwareNetworkImage(
+ resp.value!.uri.toString(),
+ headers: resp.value!.headers,
+ ),
),
fit: BoxFit.contain,
semanticLabel: "Image attachment",
### lib/services/shopinbit/src/client.dart
@@ -309,6 +309,31 @@ class ShopInBitClient {
}
}
+ /// URL and auth headers for fetching an attachment via
+ /// `/attachment-proxy/<path>` from an HTTP client that can set headers.
+ Future<ApiResponse<AttachmentRequest>> getAttachmentRequest(
+ String attachmentPath, {
+ String? customerKey,
+ }) async {
+ try {
+ final token = await _tokenManager.getValidToken();
+ final resolved = _resolvePath('/attachment-proxy/$attachmentPath');
+ return ApiResponse(
+ value: (
+ uri: Uri.parse('$baseUrl$resolved'),
+ headers: {
+ 'Authorization': 'Bearer $token',
+ if (customerKey != null) 'External-Customer-Key': customerKey,
+ },
+ ),
+ );
+ } on ApiException catch (e) {
+ return ApiResponse(exception: e);
+ } catch (e) {
+ return ApiResponse(exception: ApiException.network(e));
+ }
+ }
+
/// Download an attachment from `/attachment-proxy/<path>`.
Future<ApiResponse<Response>> getAttachment(
String attachmentPath, {
@@ -1055,6 +1080,8 @@ const kAllowedAttachmentExtensions = [
typedef ResolvedAttachment = ({String mimeType, AttachmentCategory category});
+typedef AttachmentRequest = ({Uri uri, Map<String, String> headers});
+
/// Path + content type, materialized into multipart bytes inside
/// [_multipartRequest]: validation stays separate from encoding, and the
/// encoded bytes can be resent on 401 without re-reading files from disk.
@@ -1075,8 +1102,7 @@ ResolvedAttachment? resolveAttachmentType(String fileName) {
"gif" => (mimeType: "image/gif", category: .image),
"pdf" => (mimeType: "application/pdf", category: .document),
"docx" => (
- mimeType:
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
category: .document,
),
"xlsx" => (
### test/networking/tor_aware_network_image_test.dart
@@ -0,0 +1,42 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/networking/tor_aware_network_image.dart';
+
+void main() {
+ late HttpServer server;
+ late List<HttpRequest> requests;
+
+ setUp(() async {
+ requests = [];
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((request) {
+ requests.add(request);
+ request.response.add([1]);
+ request.response.close();
+ });
+ });
+
+ tearDown(() => server.close(force: true));
+
+ String url(String path) => "http://127.0.0.1:${server.port}$path";
+
+ test("network image sends headers but keys the cache on the url", () async {
+ await fetchTorAwareBytes(
+ url("/a.png"),
+ headers: {"Authorization": "Bearer abc"},
+ );
+ expect(requests.single.headers.value("Authorization"), "Bearer abc");
+
+ expect(
+ TorAwareNetworkImage(
+ url("/a.png"),
+ headers: const {"Authorization": "a"},
+ ),
+ TorAwareNetworkImage(
+ url("/a.png"),
+ headers: const {"Authorization": "b"},
+ ),
+ );
+ });
+}Why this scored 60/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.