Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,59 @@ internal class EmbedCodePluginSpec {
) shouldBe true
}

@Test
fun `reject a version containing path traversal segments`() {
writeBuildFile(
version = "../../escaped",
sha256 = "0".repeat(64),
)

val result = runner(":installEmbedCode").buildAndFail()

result.output shouldContain "Embed Code version `../../escaped` is invalid."
Files.exists(projectDirectory.resolve("escaped")) shouldBe false
}

@Test
fun `reject an executable path outside the installation directory`() {
writeBuildFile(version = TEST_RELEASE_VERSION)
Files.writeString(
projectDirectory.resolve("build.gradle.kts"),
"""

tasks.named<io.spine.embedcode.gradle.InstallEmbedCodeTask>("installEmbedCode") {
executableFile.set(layout.projectDirectory.file("escaped/embed-code"))
}
""".trimIndent(),
StandardOpenOption.APPEND,
)

val result = runner(":installEmbedCode").buildAndFail()

result.output shouldContain "must remain inside"
Files.exists(projectDirectory.resolve("escaped/embed-code")) shouldBe false
}

@Test
fun `reject a checksum path outside the installation directory`() {
writeBuildFile(version = TEST_RELEASE_VERSION)
Files.writeString(
projectDirectory.resolve("build.gradle.kts"),
"""

tasks.named<io.spine.embedcode.gradle.InstallEmbedCodeTask>("installEmbedCode") {
assetChecksumFile.set(layout.projectDirectory.file("escaped/asset.sha256"))
}
""".trimIndent(),
StandardOpenOption.APPEND,
)

val result = runner(":installEmbedCode").buildAndFail()

result.output shouldContain "must remain inside"
Files.exists(projectDirectory.resolve("escaped/asset.sha256")) shouldBe false
}

@Test
fun `defer unsupported platform failure until installation`() {
Files.writeString(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ public class EmbedCodePlugin : Plugin<Project> {
// The installed file name always tracks the host operating system.
// Overriding the task's `operatingSystem` input changes asset selection only.
val installedExecutableName = EmbedCodePlatform.installedExecutableName(operatingSystem)
val requestedVersion = extension.version.map { version -> version.trim() }
val requestedVersion = extension.version.map(::validateVersion)
val installationDirectory = project.layout.buildDirectory.dir("embed-code")
val installTask = project.tasks.register(
installTaskName,
InstallEmbedCodeTask::class.java,
Expand All @@ -73,6 +74,8 @@ public class EmbedCodePlugin : Plugin<Project> {
task.operatingSystem.set(operatingSystem)
task.architecture.set(architecture)
task.offline.set(project.gradle.startParameter.isOffline)
task.installationDirectory.set(installationDirectory)
task.installationDirectory.disallowChanges()
task.executableFile.set(
project.layout.buildDirectory.file(
requestedVersion.map { version ->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright 2026, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package io.spine.embedcode.gradle

import org.gradle.api.InvalidUserDataException

private val validVersion = Regex("[A-Za-z0-9][A-Za-z0-9._+~-]*")

/**
* Trims and validates a user-configured Embed Code release version.
*
* The version becomes both a release URL segment and a cache-directory name,
* so only characters that are safe in both locations are accepted.
*/
internal fun validateVersion(value: String): String {
val version = value.trim()
if (!validVersion.matches(version)) {
throw InvalidUserDataException(
"Embed Code version `$value` is invalid. " +
"Use letters, digits, dots, hyphens, underscores, plus signs, or tildes, " +
"and start with a letter or digit.",
)
}
return version
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ package io.spine.embedcode.gradle

import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
Expand Down Expand Up @@ -91,6 +92,10 @@ public abstract class InstallEmbedCodeTask : DefaultTask() {
@get:Input
public abstract val offline: Property<Boolean>

/** The directory containing executables and their integrity metadata. */
@get:Internal
public abstract val installationDirectory: DirectoryProperty

/** The installed executable used by Embed Code execution tasks. */
@get:OutputFile
public abstract val executableFile: RegularFileProperty
Expand All @@ -116,10 +121,7 @@ public abstract class InstallEmbedCodeTask : DefaultTask() {
*/
@TaskAction
public fun install() {
val requestedVersion = version.orNull
if (requestedVersion != null && requestedVersion.isEmpty()) {
throw GradleException("Embed Code version must not be empty.")
}
val requestedVersion = version.orNull?.let(::validateVersion)
val configuredSha256 = sha256.orNull?.let(::normalizeSha256)
val hostOperatingSystem = operatingSystem.get()
val hostArchitecture = architecture.get()
Expand All @@ -131,11 +133,27 @@ public abstract class InstallEmbedCodeTask : DefaultTask() {
val platform = EmbedCodePlatform.detect(hostOperatingSystem, hostArchitecture)
val asset = platform.assetName
val baseUrl = trimTrailingSlashes(downloadBaseUrl.get())
val destination = executableFile.get().asFile.toPath()
val versionFile = resolvedVersionFile.get().asFile.toPath()
val assetChecksum = assetChecksumFile.get().asFile.toPath()
val executableChecksum = executableChecksumFile.get().asFile.toPath()
val sourceIdentity = sourceIdentityFile.get().asFile.toPath()
val installationRoot = installationDirectory.get().asFile.toPath()
val destination = requireInsideInstallationDirectory(
executableFile.get().asFile.toPath(),
installationRoot,
)
val versionFile = requireInsideInstallationDirectory(
resolvedVersionFile.get().asFile.toPath(),
installationRoot,
)
val assetChecksum = requireInsideInstallationDirectory(
assetChecksumFile.get().asFile.toPath(),
installationRoot,
)
val executableChecksum = requireInsideInstallationDirectory(
executableChecksumFile.get().asFile.toPath(),
installationRoot,
)
val sourceIdentity = requireInsideInstallationDirectory(
sourceIdentityFile.get().asFile.toPath(),
installationRoot,
)
val expectedSourceIdentity = releaseAssetIdentity(baseUrl, asset)
if (offline.get()) {
reuseOfflineInstallation(
Expand Down Expand Up @@ -310,6 +328,23 @@ public abstract class InstallEmbedCodeTask : DefaultTask() {
const val READ_TIMEOUT_MILLIS = 120_000
const val BUFFER_SIZE = 8_192

/**
* Normalizes [path] and verifies that it is below [installationDirectory].
*/
fun requireInsideInstallationDirectory(
path: Path,
installationDirectory: Path,
): Path {
val root = installationDirectory.toAbsolutePath().normalize()
val normalizedPath = path.toAbsolutePath().normalize()
if (normalizedPath == root || !normalizedPath.startsWith(root)) {
throw GradleException(
"Embed Code installation path `$normalizedPath` must remain inside `$root`.",
)
}
return normalizedPath
}

fun selectedVersionName(requestedVersion: String?, resolvedVersion: String?): String =
requestedVersion ?: resolvedVersion ?: "latest release"

Expand Down