Skip to content

Commit 062819a

Browse files
committed
feat: complete Markdown compatibility and HTML sanitization
Signed-off-by: Patrizio Bekerle <patrizio@bekerle.com>
1 parent aa0aab6 commit 062819a

7 files changed

Lines changed: 332 additions & 6 deletions

File tree

‎markdown-android/src/androidTest/kotlin/org/qownnotes/mobile/markdown/MarkdownRendererInstrumentedTest.kt‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@ import androidx.appcompat.widget.AppCompatTextView
1111
import androidx.test.ext.junit.runners.AndroidJUnit4
1212
import androidx.test.platform.app.InstrumentationRegistry
1313
import io.noties.markwon.core.spans.LinkSpan
14+
import io.noties.markwon.ext.tasklist.TaskListSpan
1415
import io.noties.markwon.image.AsyncDrawableSpan
1516
import io.noties.markwon.image.ImageItem
1617
import io.noties.markwon.image.SchemeHandler
1718
import java.util.concurrent.CountDownLatch
1819
import java.util.concurrent.TimeUnit
1920
import java.util.concurrent.atomic.AtomicInteger
21+
import java.util.concurrent.atomic.AtomicReference
2022
import org.junit.Assert.assertEquals
2123
import org.junit.Assert.assertFalse
2224
import org.junit.Assert.assertNotNull
@@ -187,6 +189,122 @@ class MarkdownRendererInstrumentedTest {
187189
)
188190
}
189191

192+
@Test
193+
fun rendersQOwnNotesIndeterminateTasksWithoutChangingCode() {
194+
lateinit var view: AppCompatTextView
195+
196+
instrumentation.runOnMainSync {
197+
view = textView()
198+
MarkdownRenderer(view.context).render(
199+
view,
200+
"""
201+
- [ ] open
202+
- [x] done
203+
- [-] partial
204+
- [-] nested
205+
* [-] star
206+
+ [-] plus
207+
1. [-] ordered
208+
209+
`- [-] inline code`
210+
211+
```text
212+
- [-] fenced code
213+
```
214+
""".trimIndent()
215+
)
216+
}
217+
218+
val text = view.text as Spanned
219+
assertEquals(7, text.getSpans(0, text.length, TaskListSpan::class.java).size)
220+
assertEquals(5, text.getSpans(0, text.length, IndeterminateTaskSpan::class.java).size)
221+
assertTrue(text.contains("- [-] inline code"))
222+
assertTrue(text.contains("- [-] fenced code"))
223+
}
224+
225+
@Test
226+
fun canonicalizesEncodedImageBeforeDispatch() {
227+
val destination = AtomicReference<String>()
228+
val requested = CountDownLatch(1)
229+
val handler = object : SchemeHandler() {
230+
override fun supportedSchemes(): Collection<String> = listOf("https")
231+
232+
override fun handle(raw: String, uri: Uri): ImageItem {
233+
destination.set(raw)
234+
requested.countDown()
235+
return ImageItem.withResult(ColorDrawable(Color.BLUE))
236+
}
237+
}
238+
239+
instrumentation.runOnMainSync {
240+
val view = textView()
241+
MarkdownRenderer.forTest(view.context, handler).render(
242+
view,
243+
"![encoded](<HTTPS://EXAMPLE.COM/a b.png?x=1&amp;y=2>)",
244+
loadRemoteImages = true
245+
)
246+
}
247+
248+
assertTrue(requested.await(5, TimeUnit.SECONDS))
249+
assertEquals("https://example.com/a%20b.png?x=1&y=2", destination.get())
250+
}
251+
252+
@Test
253+
fun stripsRawHtmlWithoutCreatingLinksOrImageRequests() {
254+
val requestCount = AtomicInteger()
255+
val handler = object : SchemeHandler() {
256+
override fun supportedSchemes(): Collection<String> = listOf("https")
257+
258+
override fun handle(raw: String, uri: Uri): ImageItem {
259+
requestCount.incrementAndGet()
260+
return ImageItem.withResult(ColorDrawable(Color.BLUE))
261+
}
262+
}
263+
lateinit var view: AppCompatTextView
264+
265+
instrumentation.runOnMainSync {
266+
view = textView()
267+
MarkdownRenderer.forTest(view.context, handler).render(
268+
view,
269+
"""
270+
before <b>safe</b> after
271+
272+
danger <script>![tracker](https://example.com/tracker.png)</script> tail
273+
274+
prefix <a href="https://example.com">plain label</a> suffix
275+
276+
<img src="https://example.com/raw.png">
277+
278+
`<script>literal code</script>`
279+
""".trimIndent(),
280+
loadRemoteImages = true
281+
)
282+
}
283+
284+
Thread.sleep(250)
285+
val text = view.text as Spanned
286+
assertTrue(text.contains("before safe after"))
287+
assertTrue(text.contains("plain label"))
288+
assertTrue(text.contains("<script>literal code</script>"))
289+
assertFalse(text.contains("tracker"))
290+
assertFalse(text.contains("<b>"))
291+
assertEquals(0, text.getSpans(0, text.length, LinkSpan::class.java).size)
292+
assertEquals(0, text.getSpans(0, text.length, AsyncDrawableSpan::class.java).size)
293+
assertEquals(0, requestCount.get())
294+
}
295+
296+
@Test
297+
fun doesNotLeakHtmlOnlyInputThroughRawFallback() {
298+
lateinit var view: AppCompatTextView
299+
300+
instrumentation.runOnMainSync {
301+
view = textView()
302+
MarkdownRenderer(view.context).render(view, "<!-- private comment -->")
303+
}
304+
305+
assertEquals("", view.text.toString())
306+
}
307+
190308
private fun textView(): AppCompatTextView {
191309
val context = ContextThemeWrapper(
192310
instrumentation.targetContext,
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
package org.qownnotes.mobile.markdown
2+
3+
import android.content.Context
4+
import android.graphics.Canvas
5+
import android.graphics.ColorFilter
6+
import android.graphics.Paint
7+
import android.graphics.PixelFormat
8+
import android.graphics.RectF
9+
import android.graphics.drawable.Drawable
10+
import io.noties.markwon.AbstractMarkwonPlugin
11+
import io.noties.markwon.MarkwonConfiguration
12+
import io.noties.markwon.MarkwonSpansFactory
13+
import io.noties.markwon.MarkwonVisitor
14+
import io.noties.markwon.ext.tasklist.TaskListItem
15+
import io.noties.markwon.ext.tasklist.TaskListSpan
16+
import io.noties.markwon.utils.ParserUtils
17+
import org.commonmark.node.AbstractVisitor
18+
import org.commonmark.node.ListItem
19+
import org.commonmark.node.Node
20+
import org.commonmark.node.Paragraph
21+
import org.commonmark.node.Text
22+
import org.commonmark.parser.Parser
23+
import org.commonmark.parser.PostProcessor
24+
25+
internal class IndeterminateTaskListPlugin(context: Context) : AbstractMarkwonPlugin() {
26+
private val drawable =
27+
IndeterminateTaskDrawable(context.resolveColor(android.R.attr.textColorLink))
28+
29+
override fun configureParser(builder: Parser.Builder) {
30+
builder.postProcessor(IndeterminateTaskPostProcessor())
31+
}
32+
33+
override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) {
34+
builder.setFactory(IndeterminateTaskListItem::class.java) { configuration, _ ->
35+
IndeterminateTaskSpan(configuration, drawable)
36+
}
37+
}
38+
39+
override fun configureVisitor(builder: MarkwonVisitor.Builder) {
40+
builder.on(IndeterminateTaskListItem::class.java) { visitor, item ->
41+
val start = visitor.length()
42+
visitor.visitChildren(item)
43+
visitor.setSpansForNode(item, start)
44+
if (visitor.hasNext(item)) visitor.ensureNewLine()
45+
}
46+
}
47+
}
48+
49+
internal class IndeterminateTaskSpan(configuration: MarkwonConfiguration, drawable: Drawable) :
50+
TaskListSpan(configuration.theme(), drawable, false)
51+
52+
private class IndeterminateTaskListItem : TaskListItem(false)
53+
54+
private class IndeterminateTaskPostProcessor : PostProcessor {
55+
override fun process(node: Node): Node {
56+
node.accept(
57+
object : AbstractVisitor() {
58+
override fun visit(listItem: ListItem) {
59+
val paragraph = listItem.firstChild as? Paragraph
60+
val text = paragraph?.firstChild as? Text
61+
val match = text?.literal?.let(INDETERMINATE_TASK::matchEntire)
62+
if (paragraph == null || text == null || match == null) {
63+
visitChildren(listItem)
64+
return
65+
}
66+
67+
val task = IndeterminateTaskListItem()
68+
val taskParagraph = Paragraph()
69+
listItem.insertBefore(task)
70+
match.groupValues[1].takeIf(String::isNotEmpty)?.let {
71+
taskParagraph.appendChild(Text(it))
72+
}
73+
ParserUtils.moveChildren(taskParagraph, text)
74+
task.appendChild(taskParagraph)
75+
ParserUtils.moveChildren(task, paragraph)
76+
listItem.unlink()
77+
visitChildren(task)
78+
}
79+
}
80+
)
81+
return node
82+
}
83+
}
84+
85+
private class IndeterminateTaskDrawable(private val color: Int) : Drawable() {
86+
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
87+
this.color =
88+
this@IndeterminateTaskDrawable.color
89+
}
90+
91+
override fun draw(canvas: Canvas) {
92+
val side = minOf(bounds.width(), bounds.height()).toFloat()
93+
val stroke = side / 8F
94+
paint.style = Paint.Style.STROKE
95+
paint.strokeWidth = stroke
96+
val inset = stroke / 2F
97+
val box = RectF(inset, inset, side - inset, side - inset)
98+
canvas.drawRoundRect(box, side / 8F, side / 8F, paint)
99+
paint.style = Paint.Style.FILL
100+
canvas.drawRoundRect(
101+
side * .25F,
102+
side * .44F,
103+
side * .75F,
104+
side * .56F,
105+
stroke / 2F,
106+
stroke / 2F,
107+
paint
108+
)
109+
}
110+
111+
override fun setAlpha(alpha: Int) {
112+
paint.alpha = alpha
113+
}
114+
115+
override fun setColorFilter(colorFilter: ColorFilter?) {
116+
paint.colorFilter = colorFilter
117+
}
118+
119+
@Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")
120+
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
121+
}
122+
123+
private fun Context.resolveColor(attribute: Int): Int {
124+
val attributes = obtainStyledAttributes(intArrayOf(attribute))
125+
return try {
126+
attributes.getColor(0, 0xFF666666.toInt())
127+
} finally {
128+
attributes.recycle()
129+
}
130+
}
131+
132+
private val INDETERMINATE_TASK = Regex("^\\[-]\\s+(.*)")
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package org.qownnotes.mobile.markdown
2+
3+
import io.noties.markwon.AbstractMarkwonPlugin
4+
import org.commonmark.node.AbstractVisitor
5+
import org.commonmark.node.Block
6+
import org.commonmark.node.HtmlBlock
7+
import org.commonmark.node.HtmlInline
8+
import org.commonmark.node.Node
9+
10+
internal class MarkdownHtmlSanitizerPlugin : AbstractMarkwonPlugin() {
11+
override fun beforeRender(node: Node) {
12+
sanitizeMarkdownHtml(node)
13+
}
14+
}
15+
16+
internal fun sanitizeMarkdownHtml(node: Node) {
17+
node.accept(
18+
object : AbstractVisitor() {
19+
override fun visit(htmlBlock: HtmlBlock) {
20+
htmlBlock.unlink()
21+
}
22+
23+
override fun visit(htmlInline: HtmlInline) {
24+
if (ACTIVE_HTML_TAG.containsMatchIn(htmlInline.literal)) {
25+
htmlInline.parentBlock()?.unlink()
26+
} else {
27+
htmlInline.unlink()
28+
}
29+
}
30+
}
31+
)
32+
}
33+
34+
private fun Node.parentBlock(): Block? {
35+
var current = parent
36+
while (current != null && current !is Block) current = current.parent
37+
return current as? Block
38+
}
39+
40+
private val ACTIVE_HTML_TAG = Regex(
41+
"<\\s*/?\\s*(?:script|style|iframe|object|embed|svg|math|video|audio|form)(?:\\s|/?>)",
42+
RegexOption.IGNORE_CASE
43+
)

‎markdown-android/src/main/kotlin/org/qownnotes/mobile/markdown/MarkdownRenderer.kt‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import io.noties.markwon.ext.tables.TablePlugin
2222
import io.noties.markwon.ext.tasklist.TaskListPlugin
2323
import io.noties.markwon.image.ImagesPlugin
2424
import io.noties.markwon.image.SchemeHandler
25+
import io.noties.markwon.image.destination.ImageDestinationProcessor
2526
import java.nio.charset.StandardCharsets
2627
import java.util.Base64
2728
import java.util.Locale
@@ -83,13 +84,12 @@ class MarkdownRenderer private constructor(context: Context, imageSchemeHandler:
8384
fun hasRemoteImages(markdown: String): Boolean {
8485
if (redactEncryptedMarkdown(markdown, replacement = "").blockCount > 0) return false
8586
var found = false
86-
Parser.builder().build().parse(markdown).accept(
87+
val document = Parser.builder().build().parse(markdown)
88+
sanitizeMarkdownHtml(document)
89+
document.accept(
8790
object : AbstractVisitor() {
8891
override fun visit(image: Image) {
89-
if (runCatching { requireSafeHttpsUrl(image.destination) }.isSuccess) {
90-
found =
91-
true
92-
}
92+
if (canonicalSafeImageDestination(image.destination) != null) found = true
9393
}
9494
}
9595
)
@@ -98,10 +98,18 @@ class MarkdownRenderer private constructor(context: Context, imageSchemeHandler:
9898

9999
private fun createMarkwon(imageSchemeHandler: SchemeHandler? = null): Markwon {
100100
val builder = Markwon.builder(applicationContext)
101+
.fallbackToRawInputWhenEmpty(false)
101102
.usePlugin(
102103
object : AbstractMarkwonPlugin() {
103104
override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
104105
builder.syntaxHighlight(BoundedSyntaxHighlight(applicationContext))
106+
builder.imageDestinationProcessor(
107+
object : ImageDestinationProcessor() {
108+
override fun process(destination: String): String =
109+
canonicalSafeImageDestination(destination)
110+
?: BLOCKED_IMAGE_DESTINATION
111+
}
112+
)
105113
builder.linkResolver { view, destination ->
106114
when {
107115
destination.startsWith(WIKI_SCHEME) -> {
@@ -116,8 +124,10 @@ class MarkdownRenderer private constructor(context: Context, imageSchemeHandler:
116124
}
117125
}
118126
)
127+
.usePlugin(MarkdownHtmlSanitizerPlugin())
119128
.usePlugin(StrikethroughPlugin.create())
120129
.usePlugin(TablePlugin.create(applicationContext))
130+
.usePlugin(IndeterminateTaskListPlugin(applicationContext))
121131
.usePlugin(TaskListPlugin.create(applicationContext))
122132
if (imageSchemeHandler != null) {
123133
builder.usePlugin(
@@ -161,6 +171,8 @@ class MarkdownRenderer private constructor(context: Context, imageSchemeHandler:
161171
}
162172
}
163173

174+
private const val BLOCKED_IMAGE_DESTINATION = "qon-blocked-image:blocked"
175+
164176
private data class InternalLinkHandler(
165177
val resolve: (InternalNoteLink) -> ResolvedNoteLink?,
166178
val open: (ResolvedNoteLink) -> Unit

‎markdown-android/src/main/kotlin/org/qownnotes/mobile/markdown/SafeHttpsImageSchemeHandler.kt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ internal fun requireSafeHttpsUrl(raw: String): HttpUrl {
5353
return url
5454
}
5555

56+
internal fun canonicalSafeImageDestination(destination: String): String? =
57+
runCatching { requireSafeHttpsUrl(destination).toString() }.getOrNull()
58+
5659
internal fun isPublicImageAddress(address: InetAddress): Boolean {
5760
if (address.isAnyLocalAddress || address.isLoopbackAddress || address.isLinkLocalAddress ||
5861
address.isSiteLocalAddress || address.isMulticastAddress

0 commit comments

Comments
 (0)