Skip to content

Sanitize dartdoc's HTML output. #5181

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
41 changes: 37 additions & 4 deletions app/lib/dartdoc/customization.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ import 'dart:io';
import 'package:collection/collection.dart';
import 'package:html/dom.dart';
import 'package:html/parser.dart' as html_parser;
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;

import 'dartdoc_sanitizer.dart';

final _logger = Logger('dartdoc_customization');

class DartdocCustomizerConfig {
final String packageName;
final String packageVersion;
final bool isLatestStable;
final bool isInternal;
final String docRootUrl;
final String latestStableDocumentationUrl;
final String pubPackagePageUrl;
Expand All @@ -26,6 +33,7 @@ class DartdocCustomizerConfig {
required this.packageName,
required this.packageVersion,
required this.isLatestStable,
required this.isInternal,
required this.docRootUrl,
required this.latestStableDocumentationUrl,
required this.pubPackagePageUrl,
Expand All @@ -46,16 +54,41 @@ class DartdocCustomizer {
final dir = Directory(path);
await for (var fse in dir.list(recursive: true)) {
if (fse is File && fse.path.endsWith('.html')) {
final c = await customizeFile(fse);
final relativeName = p.relative(fse.path, from: dir.path);
final level = p.split(relativeName).length - 1;
final c = await customizeFile(fse, level);
changed = changed || c;
}
}
return changed;
}

Future<bool> customizeFile(File file) async {
final String oldContent = await file.readAsString();
final newContent = customizeHtml(oldContent);
Future<bool> customizeFile(File file, int directoryLevel) async {
final oldContent = await file.readAsString();
var newContent = oldContent;
try {
final sr = config.isInternal
? SanitizerResult(true, oldContent, <String>[])
: sanitizeDartdocHtml(oldContent, directoryLevel);
if (!sr.passed) {
_logger.info(
'[dartdoc-sanitized-html] Failed to sanitize ${config.packageName} ${config.packageVersion} '
'file ${file.path}: ${sr.removed.join('; ')}');
}
newContent = customizeHtml(sr.contentHtml);
} catch (e, st) {
// Per-file catch-all for sanitization and customization, to make sure
// we will inspect all the files before uploading any of them.
_logger.shout(
'[dartdoc-sanitized-html] Failed to customize ${config.packageName} ${config.packageVersion} file ${file.path}',
e,
st);

// Paranoid override, as we don't know what happened.
newContent =
'<html><body>Failed to customize dartdoc file.</body></html>';
}
// override file only if the content changed
if (oldContent != newContent) {
await file.writeAsString(newContent);
return true;
Expand Down
2 changes: 2 additions & 0 deletions app/lib/dartdoc/customizer_config_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ DartdocCustomizerConfig customizerConfig({
required String packageName,
required String packageVersion,
required bool isLatestStable,
required bool isInternal,
}) {
return DartdocCustomizerConfig(
packageName: packageName,
packageVersion: packageVersion,
isLatestStable: isLatestStable,
isInternal: isInternal,
docRootUrl: isLatestStable
? pkgDocUrl(packageName, isLatest: true)
: pkgDocUrl(packageName, version: packageVersion),
Expand Down
5 changes: 5 additions & 0 deletions app/lib/dartdoc/dartdoc_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import '../job/backend.dart';
import '../job/job.dart';
import '../package/backend.dart';
import '../package/models.dart';
import '../package/overrides.dart';
import '../scorecard/backend.dart';
import '../scorecard/models.dart';
import '../shared/configuration.dart';
Expand Down Expand Up @@ -311,10 +312,14 @@ class DartdocJobProcessor extends JobProcessor {

if (hasContent) {
try {
final isInternal =
internalPackageNames.contains(job.packageName!) ||
packageStatus.isPublishedByDartDev;
await DartdocCustomizer(customizerConfig(
packageName: job.packageName!,
packageVersion: job.packageVersion!,
isLatestStable: job.isLatestStable,
isInternal: isInternal,
)).customizeDir(outputDir);
logFileOutput.write('Content customization completed.\n\n');
} catch (e, st) {
Expand Down
67 changes: 67 additions & 0 deletions app/lib/dartdoc/dartdoc_sanitizer.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:html/dom.dart';
import 'package:html/parser.dart' as html_parser;

class SanitizerResult {
final bool passed;
final String contentHtml;
final List<String> removed;

SanitizerResult(this.passed, this.contentHtml, this.removed);
}

/// Removes unsafe elements and attributes from the output of dartdoc.
SanitizerResult sanitizeDartdocHtml(String input, int directoryLevel) {
final parsed = html_parser.parse(input);
final removed = <String>[];

void visit(Element elem) {
// remove elements based on tag and position
final tag = elem.localName?.toLowerCase() ?? '';
if (tag == 'iframe') {
removed.add('iframe src="${elem.attributes['src']}"');
elem.remove();
return;
}

// allow some <script> and remove everything else
if (tag == 'script') {
final src = elem.attributes['src'] ?? '';
final prefix = '../' * directoryLevel;
final allowed = [
'${prefix}static-assets/highlight.pack.js?v1',
'${prefix}static-assets/script.js?v1',
];
if (!allowed.contains(src)) {
removed.add('script src="${elem.attributes['src']}"');
elem.remove();
return;
}
}

// remove on* attributes
elem.attributes.removeWhere((a, value) {
final key = a is String ? a : (a as AttributeName).name;
if (key.toLowerCase().startsWith('on')) {
removed.add('$tag $key');
return true;
}
return false;
});

// visit children
for (final c in elem.children) {
visit(c);
}
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is sufficient, we need to allow list tags, attributes and possibly even validate attribute values.

visit(parsed.documentElement!);
return SanitizerResult(
removed.isEmpty,
removed.isNotEmpty ? parsed.outerHtml : input,
removed,
);
}
2 changes: 2 additions & 0 deletions app/test/dartdoc/customization_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,13 @@ void main() {
packageName: package,
packageVersion: version,
isLatestStable: false,
isInternal: false,
));
final latestCustomizer = DartdocCustomizer(customizerConfig(
packageName: package,
packageVersion: version,
isLatestStable: true,
isInternal: false,
));

final path = '${package}_${version}_$name';
Expand Down
63 changes: 63 additions & 0 deletions app/test/dartdoc/dartdoc_sanitizer_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';

import 'package:pub_dev/dartdoc/dartdoc_sanitizer.dart';
import 'package:test/test.dart';

import 'customization_test.dart';

void main() {
test('accept golden files', () async {
final files = Directory(goldenDir)
.listSync()
.whereType<File>()
.where((f) => f.path.endsWith('.html'))
.where((f) => !f.path.endsWith('.out.html'))
// dygraph templates are not updated to the latest dartdoc
.where((f) => !f.path.contains('/dygraph_'))
.toList();

int _level(String path) {
if (path.endsWith('_index.html')) return 0;
if (path.endsWith('_class.html')) return 1;
if (path.endsWith('_field.html')) return 2;
if (path.endsWith('_constructor.html')) return 2;
return 1;
}

for (final f in files) {
final level = _level(f.path);
final rs = sanitizeDartdocHtml(await f.readAsString(), level);
expect(rs.passed, isTrue, reason: f.path);
}
});

test('unauthorized <script> is removed', () {
final rs = sanitizeDartdocHtml(
'<html><body><p>1</p><script src="x.js"></script><p>2</p></body></html>',
0);
expect(rs.passed, false);
expect(rs.contentHtml,
'<html><head></head><body><p>1</p><p>2</p></body></html>');
});

test('onclick="" is removed', () {
final rs = sanitizeDartdocHtml(
'<html><body><p>1</p><div onclick="window.alert(\'x\');"></div><p>2</p></html>',
0);
expect(rs.passed, false);
expect(rs.contentHtml,
'<html><head></head><body><p>1</p><div></div><p>2</p></body></html>');
});

test('<iframe> is removed', () {
final rs = sanitizeDartdocHtml(
'<html><body><p>1</p><iframe src="x.html"></iframe><p>2</p></html>', 0);
expect(rs.passed, false);
expect(rs.contentHtml,
'<html><head></head><body><p>1</p><p>2</p></body></html>');
});
}