Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-masks-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'posthog-ios': patch
---

Fix `screenshotMode` session replay leaving masked content visible where it is drawn outside its view (unclipped images, layer shadows, button titles) and image attachments in text unmasked when `maskAllImages` is on.
5 changes: 3 additions & 2 deletions PostHog/Replay/PostHogMaskSettleAnalysis.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@
self.rect = rect
}

/// Covers everything the view draws itself, including content past its bounds.
init(_ view: UIView, in window: UIWindow?) {
self.init(view, rect: view.toPresentationRect(window))
self.init(view, rect: view.toPresentationRect(window, outsets: view.drawnOutsets))
}

init(_ layer: CALayer, in window: UIWindow?) {
self.init(layer, rect: layer.toPresentationRect(window))
self.init(layer, rect: layer.toPresentationRect(window, outsets: layer.drawnOutsets(of: layer.bounds)))
}
}

Expand Down
34 changes: 32 additions & 2 deletions PostHog/Replay/PostHogReplayIntegration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -948,8 +948,11 @@
}

if let textView = view as? UITextView { // TextEditor, SwiftUI.TextEditorTextView, SwiftUI.UIKitTextView
if isTextViewSensitive(textView) {
// textStorage rather than attributedText, which copies the whole text
if isTextViewSensitive(textView) || hasSensitiveImageAttachment(textView.textStorage) {
maskableWidgets.append(.init(view, in: window))
// an unclipped subview can draw outside the text view's mask
findMaskableWidgets(inSubviewsOf: view, window, &maskableWidgets, maskChildren || view.isNoCapture())
return
}
}
Expand Down Expand Up @@ -1012,8 +1015,10 @@
}

if let label = view as? UILabel { // Text, this code might never be reachable in SwiftUI, see swiftUIImageTypes instead
if isLabelSensitive(label) {
if isLabelSensitive(label) || hasSensitiveImageAttachment(label.attributedText) {
maskableWidgets.append(.init(view, in: window))
// an unclipped subview can draw outside the label's mask
findMaskableWidgets(inSubviewsOf: view, window, &maskableWidgets, maskChildren || view.isNoCapture())
return
}
}
Expand All @@ -1031,6 +1036,8 @@
if let button = view as? UIButton {
if isButtonSensitive(button) {
maskableWidgets.append(.init(view, in: window))
// title and image insets can lay the button's subviews out past its bounds
findMaskableWidgets(inSubviewsOf: view, window, &maskableWidgets, maskChildren || view.isNoCapture())
return
}
}
Expand Down Expand Up @@ -1801,6 +1808,29 @@
}
}

private extension PostHogReplayIntegration {
/// Image attachments in text are drawn by the label or text view itself, with no image view to
/// mask, so masking images masks text that holds one. Like image views, symbols and
/// asset-catalog images stay visible; an attachment whose image can't be read is masked.
func hasSensitiveImageAttachment(_ text: NSAttributedString?) -> Bool {
guard config?.sessionReplayConfig.maskAllImages == true, let text, text.length > 0 else {
return false
}
var found = false
text.enumerateAttribute(.attachment, in: NSRange(location: 0, length: text.length)) { value, _, stop in
guard let attachment = value as? NSTextAttachment else {
return
}
if let image = attachment.image, image.isSymbolImage || isAssetsImage(image) {
return
}
found = true
stop.pointee = true
}
return found
}
}

// MARK: - Plugins

extension PostHogReplayIntegration {
Expand Down
90 changes: 84 additions & 6 deletions PostHog/Replay/UIView+Util.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,12 +162,67 @@
/// while the presentation layer holds the in-flight position the screenshot renders, so
/// mask rects have to come from the presentation tree. Wireframe geometry is a separate
/// consumer with no pixels to agree with and stays on `toAbsoluteRect`.
func toPresentationRect(_ window: UIWindow?) -> CGRect {
/// `outsets` grows the rect past the bounds, for content drawn outside them.
func toPresentationRect(_ window: UIWindow?, outsets: UIEdgeInsets = .zero) -> CGRect {
guard layer.presentation() != nil else {
// UIView's own convert, not the layer's: it resolves a nil window to the view's.
return convert(bounds, to: window)
return convert(bounds.outset(by: outsets), to: window)
}
return layer.toPresentationRect(window)
return layer.toPresentationRect(window, outsets: outsets)
}

/// How far past its bounds the view draws its own content: an image view that doesn't
/// clip draws its image at the size its content mode gives it, and an unclipped layer
/// shadow repeats that content at an offset.
var drawnOutsets: UIEdgeInsets {
var content = bounds
if !clipsToBounds, let imageView = self as? UIImageView {
content = imageView.drawnImageExtent
}
return layer.drawnOutsets(of: content)
}
}

extension UIImageView {
/// The union of the bounds and where each image the view can draw lands, in bounds
/// coordinates. Only fill-to-bounds content modes keep the image inside the bounds.
var drawnImageExtent: CGRect {
switch contentMode {
case .scaleToFill, .scaleAspectFit, .redraw:
return bounds
default:
let sources = [image, highlightedImage].compactMap { $0 }
+ (animationImages ?? []) + (highlightedAnimationImages ?? [])
return sources.reduce(bounds) { $0.union(drawnRect(ofImageSized: $1.size)) }
}
}

private func drawnRect(ofImageSized imageSize: CGSize) -> CGRect {
var size = imageSize
if contentMode == .scaleAspectFill, imageSize.width > 0, imageSize.height > 0 {
let scale = max(bounds.width / imageSize.width, bounds.height / imageSize.height)
size = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
}

let originX: CGFloat
switch contentMode {
case .left, .topLeft, .bottomLeft: originX = 0
case .right, .topRight, .bottomRight: originX = bounds.width - size.width
default: originX = (bounds.width - size.width) / 2
}
let originY: CGFloat
switch contentMode {
case .top, .topLeft, .topRight: originY = 0
case .bottom, .bottomLeft, .bottomRight: originY = bounds.height - size.height
default: originY = (bounds.height - size.height) / 2
}
return CGRect(x: bounds.minX + originX, y: bounds.minY + originY, width: size.width, height: size.height)
}
}

extension CGRect {
func outset(by outsets: UIEdgeInsets) -> CGRect {
inset(by: UIEdgeInsets(top: -outsets.top, left: -outsets.left, bottom: -outsets.bottom, right: -outsets.right))
}
}

Expand All @@ -193,11 +248,34 @@
}

extension CALayer {
func toPresentationRect(_ window: UIWindow?) -> CGRect {
func toPresentationRect(_ window: UIWindow?, outsets: UIEdgeInsets = .zero) -> CGRect {
guard let presentationLayer = presentation() else {
return convert(bounds, to: window?.layer)
return convert(bounds.outset(by: outsets), to: window?.layer)
}
return presentationLayer.convert(
presentationLayer.bounds.outset(by: outsets),
to: window?.layer.presentation() ?? window?.layer
)
}

/// How far past `bounds` the layer draws, given `content`, the extent of its own drawing
/// in bounds coordinates. A shadow without a `shadowPath` repeats the content's shape,
/// text included, so it counts; `masksToBounds` clips the shadow away.
func drawnOutsets(of content: CGRect) -> UIEdgeInsets {
var drawn = content
if !masksToBounds, shadowOpacity > 0, shadowColor != nil, shadowPath == nil {
// Pad by twice the blur radius so the shadow's soft edge is covered too.
let blur = shadowRadius * 2
drawn = drawn.union(
content.offsetBy(dx: shadowOffset.width, dy: shadowOffset.height).insetBy(dx: -blur, dy: -blur)
)
}
return presentationLayer.convert(presentationLayer.bounds, to: window?.layer.presentation() ?? window?.layer)
return UIEdgeInsets(
top: max(0, bounds.minY - drawn.minY),
left: max(0, bounds.minX - drawn.minX),
bottom: max(0, drawn.maxY - bounds.maxY),
right: max(0, drawn.maxX - bounds.maxX)
)
}

/// Backing flag for the SwiftUI `.postHogNoRageClick()` modifier on layer-backed
Expand Down
186 changes: 184 additions & 2 deletions PostHogTests/PostHogMaskFailClosedTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,11 @@
struct PostHogMaskFailClosedTest {
private typealias Sut = (sdk: PostHogSDK, integration: PostHogReplayIntegration)

private func makeSut() -> Sut {
private func makeSut(maskAllTextInputs: Bool = true, maskAllImages: Bool = true) -> Sut {
let config = PostHogConfig(projectToken: "phc_maskFailClosedTest")
config.disableReachabilityForTesting = true
config.sessionReplayConfig.maskAllTextInputs = true
config.sessionReplayConfig.maskAllTextInputs = maskAllTextInputs
config.sessionReplayConfig.maskAllImages = maskAllImages
PostHogReplayIntegration.clearInstalls()
let sdk = PostHogSDK.with(config)
let integration = PostHogReplayIntegration()
Expand Down Expand Up @@ -409,5 +410,186 @@

#expect(sut.integration.collectMaskableRects(in: window) == [])
}

// MARK: - Content drawn outside a masked view's bounds

private func makePhoto(size: CGSize) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
return UIGraphicsImageRenderer(size: size, format: format).image { context in
UIColor.red.setFill()
context.fill(CGRect(origin: .zero, size: size))
}
}

private func isCovered(_ target: CGRect, by rects: [CGRect]?) -> Bool {
rects?.contains { $0.contains(target) } == true
}

@Test("an unclipped aspect-fill image is masked where it overflows its view", arguments: [false, true])
func unclippedAspectFillImage(clipsToBounds: Bool) {
let sut = makeSut()
defer { teardown(sut) }

let imageView = UIImageView(frame: CGRect(x: 100, y: 120, width: 100, height: 100))
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = clipsToBounds
imageView.image = makePhoto(size: CGSize(width: 200, height: 100))
let window = makeWindow(containing: imageView)

// Filling 100x100 with a 2:1 image draws it 200x100, centred: 50pt past each side.
let expected = clipsToBounds ? imageView.frame : CGRect(x: 50, y: 120, width: 200, height: 100)
#expect(sut.integration.collectMaskableRects(in: window) == [expected])
}

@Test("an unclipped image drawn at its natural size is masked where it overflows its view")
func unclippedTopLeftImage() {
let sut = makeSut()
defer { teardown(sut) }

let imageView = UIImageView(frame: CGRect(x: 100, y: 120, width: 50, height: 50))
imageView.contentMode = .topLeft
imageView.clipsToBounds = false
imageView.image = makePhoto(size: CGSize(width: 120, height: 80))
let window = makeWindow(containing: imageView)

#expect(sut.integration.collectMaskableRects(in: window) == [CGRect(x: 100, y: 120, width: 120, height: 80)])
}

private func attributedText(with attachment: NSTextAttachment) -> NSAttributedString {
let text = NSMutableAttributedString(string: "Receipt ")
text.append(NSAttributedString(attachment: attachment))
return text
}

@Test("an image attachment in text is masked when only images are masked", arguments: ["label", "textView"])
func imageAttachmentInText(kind: String) {
let sut = makeSut(maskAllTextInputs: false, maskAllImages: true)
defer { teardown(sut) }

let text = attributedText(with: NSTextAttachment(image: makePhoto(size: CGSize(width: 24, height: 24))))
let frame = CGRect(x: 24, y: 120, width: 200, height: 40)
let view: UIView
switch kind {
case "label":
let label = UILabel(frame: frame)
label.attributedText = text
view = label
default:
let textView = UITextView(frame: frame)
textView.attributedText = text
view = textView
}
let window = makeWindow(containing: view)

#expect(isCovered(frame, by: sut.integration.collectMaskableRects(in: window)))
}

@Test("an image overflowing text masked for its attachment is still masked", arguments: ["label", "textView"])
func imageOverflowingAttachmentText(kind: String) {
let sut = makeSut(maskAllTextInputs: false, maskAllImages: true)
defer { teardown(sut) }

let text = attributedText(with: NSTextAttachment(image: makePhoto(size: CGSize(width: 24, height: 24))))
let frame = CGRect(x: 24, y: 120, width: 200, height: 40)
let view: UIView
switch kind {
case "label":
let label = UILabel(frame: frame)
label.attributedText = text
view = label
default:
let textView = UITextView(frame: frame)
textView.attributedText = text
view = textView
}
view.clipsToBounds = false
let photo = UIImageView(frame: CGRect(x: 0, y: 60, width: 80, height: 80))
photo.image = makePhoto(size: CGSize(width: 80, height: 80))
view.addSubview(photo)
let window = makeWindow(containing: view)

#expect(isCovered(photo.toAbsoluteRect(window), by: sut.integration.collectMaskableRects(in: window)))
}

@Test("a plain subview overflowing no-capture text is masked", arguments: ["label", "textView"])
func plainSubviewOverflowingNoCaptureText(kind: String) {
let sut = makeSut(maskAllTextInputs: false, maskAllImages: false)
defer { teardown(sut) }

let frame = CGRect(x: 24, y: 120, width: 200, height: 40)
let view: UIView
switch kind {
case "label":
let label = UILabel(frame: frame)
label.text = "Sensitive"
view = label
default:
let textView = UITextView(frame: frame)
textView.text = "Sensitive"
view = textView
}
view.accessibilityIdentifier = "ph-no-capture"
view.clipsToBounds = false
let overflow = CustomDrawnSecretView(frame: CGRect(x: 0, y: 60, width: 80, height: 32))
view.addSubview(overflow)
let window = makeWindow(containing: view)

#expect(isCovered(overflow.toAbsoluteRect(window), by: sut.integration.collectMaskableRects(in: window)))
}

@Test("a symbol attachment in text stays visible when only images are masked")
func symbolAttachmentInLabel() throws {
let sut = makeSut(maskAllTextInputs: false, maskAllImages: true)
defer { teardown(sut) }

let label = UILabel(frame: CGRect(x: 24, y: 120, width: 200, height: 40))
label.attributedText = try attributedText(with: NSTextAttachment(image: #require(UIImage(systemName: "star"))))
let window = makeWindow(containing: label)

#expect(sut.integration.collectMaskableRects(in: window) == [])
}

@Test("an unclipped label's layer shadow is masked with the label", arguments: [false, true])
func labelLayerShadow(clipsToBounds: Bool) {
let sut = makeSut()
defer { teardown(sut) }

let label = makeSecretLabel(frame: CGRect(x: 24, y: 120, width: 200, height: 32))
label.clipsToBounds = clipsToBounds
label.layer.shadowOpacity = 1
label.layer.shadowOffset = CGSize(width: 0, height: 60)
label.layer.shadowRadius = 0
let window = makeWindow(containing: label)

let rects = sut.integration.collectMaskableRects(in: window)
if clipsToBounds {
// A clipping layer clips its shadow too, so the mask stays on the label.
#expect(rects == [label.frame])
} else {
#expect(isCovered(label.frame.union(label.frame.offsetBy(dx: 0, dy: 60)), by: rects))
}
}

@Test("a masked button's title drawn outside the button is masked")
func buttonTitleOutsideBounds() throws {
let sut = makeSut()
defer { teardown(sut) }

let button = UIButton(type: .system)
button.frame = CGRect(x: 24, y: 120, width: 100, height: 44)
button.clipsToBounds = false
button.setTitle("SSN 123-45-6789", for: .normal)
button.contentHorizontalAlignment = .left
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 200, bottom: 0, right: -200)
let window = makeWindow(containing: button)
button.layoutIfNeeded()

let title = try #require(button.titleLabel)
let titleRect = title.toAbsoluteRect(window)
try #require(!button.frame.contains(titleRect), "the title must sit outside the button for this test")

#expect(isCovered(titleRect, by: sut.integration.collectMaskableRects(in: window)))
}
}
#endif
Loading