Skip to content

fix:34329-fixed upload svg logo in the workspace api #34977

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

Open
wants to merge 1 commit into
base: release
Choose a base branch
from
Open
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 @@ -7,6 +7,7 @@
import com.appsmith.server.services.AnalyticsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
Expand All @@ -25,9 +26,11 @@
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.appsmith.server.constants.Constraint.THUMBNAIL_PHOTO_DIMENSION;
Expand All @@ -43,11 +46,12 @@ public class AssetServiceCEImpl implements AssetServiceCE {
private static final Set<MediaType> ALLOWED_CONTENT_TYPES = Set.of(
MediaType.IMAGE_JPEG,
MediaType.IMAGE_PNG,
MediaType.valueOf("image/svg+xml"),
MediaType.valueOf("image/x-icon"),
MediaType.valueOf("image/vnd.microsoft.icon"));

private static final Set<String> ALLOWED_CONTENT_TYPES_STR =
Set.of(MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE);
Set.of(MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE, "image/svg+xml");

@Override
public Mono<Asset> getById(String id) {
Expand All @@ -65,13 +69,46 @@ private Boolean checkImageTypeValidation(DataBuffer dataBuffer, MediaType conten
means the file is not an image type file rather any other corrupted file but the extension has been
changed to .png or .jpeg to upload the flawed file. This is a security vulnerability hence reject
*/
if (ALLOWED_CONTENT_TYPES_STR.contains(contentType.toString())) {
Boolean isSvgType = MediaType.valueOf("image/svg+xml").equals(contentType);
if (isSvgType) {
String svgContent = IOUtils.toString(dataBuffer.asInputStream(), StandardCharsets.UTF_8);
dataBuffer.readPosition(0);

if (!isSvgSafe(svgContent)) {
// Throwing validation exception to return separate response for svg type.
throw new AppsmithException(AppsmithError.VALIDATION_FAILURE, "Please upload a valid svg.");
}
} else if (ALLOWED_CONTENT_TYPES_STR.contains(contentType.toString())) {
return false;
}
}
return true;
}

private boolean isSvgSafe(String svgContent) {
// Array of regex patterns to check any malicious content like(style,link,script etc.) against SVG content
String[] patterns = {
"<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>",
"<style\\b[^<]*(?:(?!<\\/style>)<[^<]*)*<\\/style>",
"<a\\b[^>]*>",
"</a>",
"\\s(on[a-zA-Z]+|style)\\s*=\\s*(['\"]).*?\\2",
"\\s(href|src)\\s*=\\s*(['\"])javascript:[^'\"]*\\2"
};

// Compile patterns and check each against svgContent to detect any malicious code.
for (String pattern : patterns) {
if (Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL)
.matcher(svgContent)
.find()) {
return false; // Unsafe SVG
}
}

// If none of the patterns match, consider the SVG safe
return true;
}

@Override
public Mono<Asset> upload(List<Part> fileParts, int maxFileSizeKB, boolean isThumbnail) {
fileParts = fileParts.stream().filter(Objects::nonNull).collect(Collectors.toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1522,6 +1522,66 @@ public void testUpdateAndDeleteLogo_validLogo() throws IOException {
.verifyComplete();
}

@Test
@WithUserDetails(value = "api_user")
public void uploadWorkspaceLogo_validSvg() throws IOException {
FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS);
Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read(
new ClassPathResource("test_assets/valid.svg"), new DefaultDataBufferFactory(), 4096)
.cache();
assertThat(dataBufferFlux.count().block())
.isLessThanOrEqualTo((int) Math.ceil(Constraint.WORKSPACE_LOGO_SIZE_KB / 4.0));

Mockito.when(filepart.content()).thenReturn(dataBufferFlux);
Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.valueOf("image/svg+xml"));

Mono<Workspace> createWorkspace = workspaceService.create(workspace).cache();

final Mono<Tuple2<Workspace, Asset>> resultMono = createWorkspace.flatMap(workspace -> workspaceService
.uploadLogo(workspace.getId(), filepart)
.flatMap(workspaceWithLogo -> Mono.zip(
Mono.just(workspaceWithLogo), assetRepository.findById(workspaceWithLogo.getLogoAssetId()))));

StepVerifier.create(resultMono)
.assertNext(tuple -> {
final Workspace workspaceWithLogo = tuple.getT1();
assertThat(workspaceWithLogo.getLogoUrl()).isNotNull();
assertThat(workspaceWithLogo.getLogoUrl()).contains(workspaceWithLogo.getLogoAssetId());

final Asset asset = tuple.getT2();
assertThat(asset).isNotNull();
})
.verifyComplete();
}

@Test
@WithUserDetails(value = "api_user")
public void uploadWorkspaceLogo_invalidSvg() throws IOException {
FilePart filepart = Mockito.mock(FilePart.class, Mockito.RETURNS_DEEP_STUBS);
Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read(
new ClassPathResource("test_assets/invalid.svg"), new DefaultDataBufferFactory(), 4096)
.cache();
assertThat(dataBufferFlux.count().block())
.isLessThanOrEqualTo((int) Math.ceil(Constraint.WORKSPACE_LOGO_SIZE_KB / 4.0));

Mockito.when(filepart.content()).thenReturn(dataBufferFlux);
Mockito.when(filepart.headers().getContentType()).thenReturn(MediaType.valueOf("image/svg+xml"));

Mono<Workspace> createWorkspace = workspaceService.create(workspace).cache();

final Mono<Tuple2<Workspace, Asset>> resultMono = createWorkspace.flatMap(workspace -> workspaceService
.uploadLogo(workspace.getId(), filepart)
.flatMap(workspaceWithLogo -> Mono.zip(
Mono.just(workspaceWithLogo), assetRepository.findById(workspaceWithLogo.getLogoAssetId()))));

StepVerifier.create(resultMono)
.expectErrorMatches(throwable -> throwable instanceof AppsmithException
&& throwable
.getMessage()
.equals(AppsmithError.VALIDATION_FAILURE.getMessage("Please upload a valid svg.")))
.verify();
}

@Test
@WithUserDetails(value = "api_user")
public void delete_WhenWorkspaceHasApp_ThrowsException() {
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading