Files
buzz/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzNotificationSVG.swift
Tom Brow fea02d174d fix(ios): fetch profiles and avatars in notification extension (#8369)
A notification can arrive from someone whose profile the main app has
never loaded. The iOS notification extension now fetches and caches
sender profiles, channel details, and avatars itself. The main app
supplies account configuration and Keychain credentials only.

After resolving the message, the extension allows 1.5 seconds for sender
and channel details. It uses available stale data when a refresh is slow
or fails, delivers once, and lets late results update its private cache.
Profiles, channel details, and avatar refresh checks share a one-hour
freshness threshold. A verified avatar removal clears the previous
image. Account removal prevents further use of that sign-in's cached
data.

Profile, channel metadata, and membership use separate bounded
downloads, so an oversized roster cannot discard the smaller records.
Sender enrichment can finish while channel requests are pending. A
successful partial channel refresh atomically removes its old
counterpart, preventing a mixed group identity or recipient count.
Group-specific notification presentation still requires a verified
recipient count.

The
[specification](https://github.com/block/buzz/blob/native-notification-enrichment/docs/native-notification-enrichment.md)
describes the display, caching, and account-removal behavior. General
persistent image caching in Flutter remains separate.

### Validation

[Hosted CI](https://github.com/block/buzz/actions/runs/38780108487)
passed on the final commit, including all Flutter shards, Android, the
full iOS release and simulator builds, and native
controls/push-navigation tests. The [current-commit security
review](https://github.com/block/buzz/pull/8369#issuecomment-6197508385)
found no issues.

The native package passed 159 tests, including new coverage for cache
freshness, avatar replacement and removal, sign-in isolation, concurrent
storage, late results, single delivery, bounded downloads, and SVG
validation. A regression test exposed identical HTTP authentication
event IDs for requests in the same second; each request now includes a
unique nonce, matching the Dart and CLI clients.

Full local CI passed before that small authentication fix. The complete
native suite and signed device build passed again on the latest commit,
including response-size limits, overlapping avatar downloads, canonical
relay-origin matching, independent profile/channel refreshes,
account-key changes before and during requests, and a single initial
snapshot read across 64 accounts, signed IPv6 avatar authorities, and
partial channel refreshes. Focused Flutter regression tests passed 198
tests with three configuration-specific skips; seven avatar widget tests
also passed. Flutter analysis is clean, and the notification extension
builds for the simulator.

On an iPhone SE, the notification displayed the sender name, avatar,
channel, and message before the updated main app was opened. Repeat
notifications used a byte-identical private cache. Three notifications
delivered together displayed the avatar after the authentication fix.
The next notification also displayed correctly after terminating the
extension process. The existing generic-push design can select the same
newest unread message for several pushes; this change does not alter
message selection.

![Notification before first app launch after
upgrade](https://raw.githubusercontent.com/block/buzz/37d450855e026178836e2a9e05b0081ebbc3b479/pr-8369--before-first-app-launch.png)

Authenticated HTTP avatar fetching and persistent HTTP cache reuse also
passed on the SE. The first notification downloaded a relay thumbnail.
After terminating the extension and expiring its separate avatar entry,
the next notification displayed the avatar and refreshed that entry
without another media request in the relay logs. The main app remained
unopened throughout. The original app build and test profile were
restored afterward.

Automated tests cover slow and failed requests, stale images, removal,
and account revocation; those cases have not all been exercised on the
phone.

### Before merge

- [x] Verify authenticated HTTP avatar fetching and cache reuse on iOS
against a working relay media service.

<!-- buzz-review-completed -->

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
2026-10-15 11:16:04 -07:00

169 lines
6.0 KiB
Swift

import Foundation
import SwiftDraw
/// Validates bounded SVG input before passing it to the native renderer.
enum BuzzNotificationSVG {
static func decode(_ data: Data) throws -> Data {
try validate(data)
guard let svg = SVG(data: data), svg.size.width.isFinite, svg.size.height.isFinite,
svg.size.width > 0, svg.size.height > 0,
svg.size.width <= 16384, svg.size.height <= 16384
else { throw BuzzNotificationCacheError.invalidRecord }
let factor = min(1, 320 / max(svg.size.width, svg.size.height))
let png = try svg.sized(
CGSize(width: svg.size.width * factor, height: svg.size.height * factor)
).pngData(scale: 1)
guard png.count <= BuzzNotificationCache.maximumAvatarBytes else {
throw BuzzNotificationCacheError.oversizedRecord
}
return png
}
static func validate(_ data: Data) throws {
guard data.count <= 128 * 1024, let text = String(data: data, encoding: .utf8),
!text.lowercased().contains("<!doctype"), !text.lowercased().contains("<!entity"),
!text.lowercased().contains("@font-face"), !text.lowercased().contains("@import")
else { throw BuzzNotificationCacheError.invalidRecord }
let validator = Validator()
let parser = XMLParser(data: data)
parser.shouldResolveExternalEntities = false
parser.delegate = validator
guard parser.parse(), validator.valid, validator.stack.isEmpty,
validator.nodes.first?.name == "svg"
else { throw BuzzNotificationCacheError.invalidRecord }
try validator.checkReferences()
}
private final class Validator: NSObject, XMLParserDelegate {
struct Node {
let name: String
var children: [Int] = []
var references: [String] = []
}
var nodes: [Node] = []
var stack: [Int] = []
var identifiers: [String: Int] = [:]
var valid = true
private var textBytes = 0
private var styleText = ""
func parser(
_ parser: XMLParser, didStartElement name: String, namespaceURI: String?,
qualifiedName: String?, attributes: [String: String]
) {
guard nodes.count < 512, stack.count < 32,
!["font", "font-face", "foreignObject", "script"].contains(name),
attributes.values.allSatisfy({ $0.utf8.count <= 32768 })
else {
reject(parser)
return
}
let index = nodes.count
nodes.append(Node(name: name))
if let parent = stack.last { nodes[parent].children.append(index) }
stack.append(index)
if let id = attributes["id"] {
guard identifiers[id] == nil else {
reject(parser)
return
}
identifiers[id] = index
}
for (key, value) in attributes {
if key == "href" || key == "xlink:href" {
if value.hasPrefix("#") {
nodes[index].references.append(String(value.dropFirst()))
} else if name == "image", value.hasPrefix("data:image/") {
// Validate compressed raster bounds before SwiftDraw expands it.
guard let comma = value.firstIndex(of: ","),
["data:image/png;base64", "data:image/jpeg;base64", "data:image/webp;base64"]
.contains(String(value[..<comma])),
let bytes = Data(base64Encoded: String(value[value.index(after: comma)...])),
(try? BuzzNotificationAvatarLoader.decode(bytes)) != nil
else {
reject(parser)
return
}
} else {
reject(parser)
return
}
}
if value.contains("url(") {
guard
let expression = try? NSRegularExpression(
pattern: #"url\(\s*['"]?#([^\s)'" ]+)['"]?\s*\)"#)
else {
reject(parser)
return
}
let range = NSRange(value.startIndex..., in: value)
let matches = expression.matches(in: value, range: range)
guard matches.count == value.components(separatedBy: "url(").count - 1 else {
reject(parser)
return
}
for match in matches {
guard let range = Range(match.range(at: 1), in: value) else {
reject(parser)
return
}
nodes[index].references.append(String(value[range]))
}
}
}
}
func parser(
_ parser: XMLParser, didEndElement: String, namespaceURI: String?, qualifiedName: String?
) {
if didEndElement == "style" {
let css = styleText.lowercased()
// CSS escapes can hide resource references. Reject them before parsing.
if css.contains("url(") || css.contains("@") || css.contains("\\") { reject(parser) }
styleText = ""
}
if !stack.isEmpty { stack.removeLast() }
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
textBytes += string.utf8.count
if stack.last.map({ nodes[$0].name == "style" }) == true { styleText += string }
if textBytes > 16384 { reject(parser) }
}
func parser(_ parser: XMLParser, foundCDATA data: Data) {
guard let string = String(data: data, encoding: .utf8) else {
reject(parser)
return
}
self.parser(parser, foundCharacters: string)
}
private func reject(_ parser: XMLParser) {
valid = false
parser.abortParsing()
}
func checkReferences() throws {
var budget = 4096
func visit(_ index: Int, ancestors: Set<Int>) throws {
guard !ancestors.contains(index), budget > 0, ancestors.count < 32 else {
throw BuzzNotificationCacheError.oversizedRecord
}
budget -= 1
var ancestors = ancestors
ancestors.insert(index)
for child in nodes[index].children { try visit(child, ancestors: ancestors) }
for reference in nodes[index].references {
guard let target = identifiers[reference] else {
throw BuzzNotificationCacheError.invalidRecord
}
try visit(target, ancestors: ancestors)
}
}
try visit(0, ancestors: [])
}
}
}