QML: Explicitly reject malformed file imports

You cannot just pass a resource path or absolute path. We expect a URL
after all. A relative path is a relative URL, so you can pass that.

Pick-to: 6.2 6.3
Fixes: QTBUG-98181
Change-Id: I010bc08b8cb0ff06712f7b0353955bee96ae36c1
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
This commit is contained in:
Ulf Hermann 2022-02-25 16:24:17 +01:00
parent 79e885537f
commit 1240a440f2
5 changed files with 56 additions and 0 deletions

View File

@ -1397,6 +1397,18 @@ QTypeRevision QQmlImportsPrivate::addFileImport(
const QString& uri, const QString &prefix, QTypeRevision version, uint flags,
QQmlImportDatabase *database, QList<QQmlError> *errors)
{
if (uri.startsWith(Slash) || uri.startsWith(Colon)) {
QQmlError error;
const QString fix = uri.startsWith(Slash) ? QLatin1String("file:") + uri
: QLatin1String("qrc") + uri;
error.setDescription(QQmlImportDatabase::tr(
"\"%1\" is not a valid import URL. "
"You can pass relative paths or URLs with schema, but not "
"absolute paths or resource paths. Try \"%2\".").arg(uri, fix));
errors->prepend(error);
return QTypeRevision();
}
Q_ASSERT(errors);
QQmlImportNamespace *nameSpace = importNamespace(prefix);

View File

@ -0,0 +1,4 @@
import "/foo/bar/baz"
QtObject {}

View File

@ -0,0 +1,4 @@
import ":/absolute/resource/path"
QtObject {}

View File

@ -0,0 +1,4 @@
import ":relative/resource/path"
QtObject {}

View File

@ -60,6 +60,8 @@ private slots:
void cleanup();
void envResourceImportPath();
void preferResourcePath();
void invalidFileImport_data();
void invalidFileImport();
};
void tst_QQmlImport::cleanup()
@ -105,6 +107,36 @@ void tst_QQmlImport::preferResourcePath()
QCOMPARE(o->objectName(), "right");
}
void tst_QQmlImport::invalidFileImport_data()
{
QTest::addColumn<QString>("file");
QTest::addColumn<QString>("import");
QTest::addRow("file absolute")
<< QStringLiteral("absoluteImport.qml")
<< QStringLiteral("/foo/bar/baz");
QTest::addRow("resource absolute")
<< QStringLiteral("absoluteResourceImport.qml")
<< QStringLiteral(":/absolute/resource/path");
QTest::addRow("resource relative")
<< QStringLiteral("relativeResourceImport.qml")
<< QStringLiteral(":relative/resource/path");
}
void tst_QQmlImport::invalidFileImport()
{
QFETCH(QString, file);
QFETCH(QString, import);
QQmlEngine engine;
QQmlComponent component(&engine, testFileUrl(file));
QVERIFY(component.isError());
QVERIFY(component.errorString().contains(
QStringLiteral("\"%1\" is not a valid import URL. "
"You can pass relative paths or URLs with schema, "
"but not absolute paths or resource paths.").arg(import)));
}
void tst_QQmlImport::testDesignerSupported()
{
QQuickView *window = new QQuickView();