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
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ It supports the [AWS, Azure, and Google object stores](storage-targets/cds-featu
* [Storage Targets](#storage-targets)
* [Malware Scanner](#malware-scanner)
* [Specify the maximum file size](#specify-the-maximum-file-size)
* [Restrict allowed MIME types](#restrict-allowed-mime-types)
* [Outbox](#outbox)
* [Restore Endpoint](#restore-endpoint)
* [Motivation](#motivation)
Expand Down Expand Up @@ -214,6 +215,38 @@ The @Validation.Maximum value is a size string consisting of a number followed b

The default is 400MB

### Restrict allowed MIME types

You can restrict which MIME types are allowed for attachments by annotating the content property with @Core.AcceptableMediaTypes. This validation is performed during file upload.

```cds
entity Books {
...
attachments: Composition of many Attachments;
}

annotate Books.attachments with {
content @Core.AcceptableMediaTypes : ['image/jpeg', 'image/png', 'application/pdf'];
}
```

Wildcard patterns are supported:

```cds
annotate Books.attachments with {
content @Core.AcceptableMediaTypes : ['image/*', 'application/pdf'];
}
```

To allow all MIME types (default behavior), either omit the annotation or use:

```cds
annotate Books.attachments with {
content @Core.AcceptableMediaTypes : ['*/*'];
}
```


### Outbox

In this plugin the [persistent outbox](https://cap.cloud.sap/docs/java/outbox#persistent) is used to mark attachments as
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* © 2024-2025 SAP SE or an SAP affiliate company and cds-feature-attachments contributors.
* © 2024-2026 SAP SE or an SAP affiliate company and cds-feature-attachments contributors.
*/
package com.sap.cds.feature.attachments.configuration;

Expand Down Expand Up @@ -123,7 +123,8 @@ public void eventHandlers(CdsRuntimeConfigurer configurer) {
boolean hasApplicationServices =
serviceCatalog.getServices(ApplicationService.class).findFirst().isPresent();
if (hasApplicationServices) {
configurer.eventHandler(new CreateAttachmentsHandler(eventFactory, storage, defaultMaxSize));
configurer.eventHandler(
new CreateAttachmentsHandler(eventFactory, storage, defaultMaxSize, runtime));
configurer.eventHandler(
new UpdateAttachmentsHandler(
eventFactory, attachmentsReader, outboxedAttachmentService, storage, defaultMaxSize));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
import com.sap.cds.feature.attachments.handler.applicationservice.helper.ModifyApplicationHandlerHelper;
import com.sap.cds.feature.attachments.handler.applicationservice.helper.ReadonlyDataContextEnhancer;
import com.sap.cds.feature.attachments.handler.applicationservice.helper.ThreadDataStorageReader;
import com.sap.cds.feature.attachments.handler.applicationservice.helper.validation.AttachmentValidationHelper;
import com.sap.cds.feature.attachments.handler.applicationservice.modifyevents.ModifyAttachmentEventFactory;
import com.sap.cds.feature.attachments.handler.common.ApplicationHandlerHelper;
import com.sap.cds.reflect.CdsEntity;
import com.sap.cds.services.EventContext;
import com.sap.cds.services.ServiceException;
import com.sap.cds.services.cds.ApplicationService;
Expand All @@ -23,6 +25,7 @@
import com.sap.cds.services.handler.annotations.HandlerOrder;
import com.sap.cds.services.handler.annotations.On;
import com.sap.cds.services.handler.annotations.ServiceName;
import com.sap.cds.services.runtime.CdsRuntime;
import com.sap.cds.services.utils.OrderConstants;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -41,14 +44,17 @@ public class CreateAttachmentsHandler implements EventHandler {
private final ModifyAttachmentEventFactory eventFactory;
private final ThreadDataStorageReader storageReader;
private final String defaultMaxSize;
private final CdsRuntime cdsRuntime;

public CreateAttachmentsHandler(
ModifyAttachmentEventFactory eventFactory,
ThreadDataStorageReader storageReader,
String defaultMaxSize) {
String defaultMaxSize,
CdsRuntime cdsRuntime) {
this.eventFactory = requireNonNull(eventFactory, "eventFactory must not be null");
this.storageReader = requireNonNull(storageReader, "storageReader must not be null");
this.defaultMaxSize = requireNonNull(defaultMaxSize, "defaultMaxSize must not be null");
this.cdsRuntime = requireNonNull(cdsRuntime, "cdsRuntime must not be null");
}

@Before
Expand All @@ -61,6 +67,13 @@ void processBeforeForDraft(CdsCreateEventContext context, List<CdsData> data) {
context.getTarget(), data, storageReader.get());
}

@Before(event = {CqnService.EVENT_CREATE, DraftService.EVENT_DRAFT_NEW})
@HandlerOrder(HandlerOrder.BEFORE)
void processBeforeForMetadata(EventContext context, List<CdsData> data) {
CdsEntity target = context.getTarget();
AttachmentValidationHelper.validateMediaAttachments(target, data, cdsRuntime);
}

@Before
@HandlerOrder(HandlerOrder.LATE)
void processBefore(CdsCreateEventContext context, List<CdsData> data) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* © 2026 SAP SE or an SAP affiliate company and cds-feature-attachments contributors.
*/
package com.sap.cds.feature.attachments.handler.applicationservice.helper.media;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sap.cds.feature.attachments.handler.applicationservice.helper.validation.AttachmentValidationHelper;
import com.sap.cds.feature.attachments.handler.common.ApplicationHandlerHelper;
import com.sap.cds.reflect.CdsAnnotation;
import com.sap.cds.reflect.CdsAssociationType;
import com.sap.cds.reflect.CdsEntity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public final class MediaTypeResolver {
private static final String CONTENT_ELEMENT = "content";
private static final String ACCEPTABLE_MEDIA_TYPES_ANNOTATION = "Core.AcceptableMediaTypes";
private static final TypeReference<List<String>> STRING_LIST_TYPE_REF = new TypeReference<>() {};
private static final ObjectMapper objectMapper = new ObjectMapper();

/**
* Resolves the acceptable media (MIME) types for the given {@link CdsEntity}.
*
* <p>The method behaves differently depending on whether the provided entity itself is a media
* entity or a root entity containing compositions:
*
* <p>If no media entities are found (neither the root nor its composition targets), an empty map
* is returned.
*
* @param entity the CDS entity to inspect (root or media entity)
* @return a map of entity qualified names to their allowed media types; empty if no media
* entities are found
*/
public static Map<String, List<String>> getAcceptableMediaTypesFromEntity(CdsEntity entity) {
// If this entity is a media entity
if (ApplicationHandlerHelper.isMediaEntity(entity)) {
return Map.of(entity.getQualifiedName(), fetchAcceptableMediaTypes(entity));
}

// If it's not a mediaEntity, if it's a root entity
Map<String, List<String>> result = new HashMap<>();
entity
.elements()
.filter(e -> e.getType().isAssociation())
.map(e -> e.getType().as(CdsAssociationType.class))
.filter(CdsAssociationType::isComposition)
.forEach(
association -> {
CdsEntity target = association.getTarget();
if (target != null && ApplicationHandlerHelper.isMediaEntity(target)) {
result.put(target.getQualifiedName(), fetchAcceptableMediaTypes(target));
}
});

return result;
}

private static List<String> fetchAcceptableMediaTypes(CdsEntity entity) {
return getAcceptableMediaTypesAnnotation(entity)
.map(CdsAnnotation::getValue)
.map(value -> objectMapper.convertValue(value, STRING_LIST_TYPE_REF))
.orElse(AttachmentValidationHelper.WILDCARD_MEDIA_TYPE);
}

public static Optional<CdsAnnotation<Object>> getAcceptableMediaTypesAnnotation(
CdsEntity entity) {
return Optional.ofNullable(entity.getElement(CONTENT_ELEMENT))
.flatMap(element -> element.findAnnotation(ACCEPTABLE_MEDIA_TYPES_ANNOTATION));
}

private MediaTypeResolver() {
// to prevent instantiation
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* © 2026 SAP SE or an SAP affiliate company and cds-feature-attachments contributors.
*/
package com.sap.cds.feature.attachments.handler.applicationservice.helper.media;

import com.sap.cds.services.ErrorStatuses;
import com.sap.cds.services.ServiceException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class MediaTypeService {
private static final Logger logger = LoggerFactory.getLogger(MediaTypeService.class);
public static final String DEFAULT_MEDIA_TYPE = "application/octet-stream";

/**
* Resolves the MIME type of a file based on its filename (specifically its extension).
*
* @param fileName the name of the file (including extension)
* @return the resolved MIME type, or a default MIME type if it cannot be determined
* @throws ServiceException if the filename is null or blank
*/
public static String resolveMimeType(String fileName) {
if (fileName == null || fileName.isBlank()) {
throw new ServiceException(ErrorStatuses.BAD_REQUEST, "Filename is missing");
}

int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex == -1 || lastDotIndex == fileName.length() - 1) {
return fallbackToDefaultMimeType(fileName);
}

FileNameMap fileNameMap = URLConnection.getFileNameMap();
String actualMimeType = fileNameMap.getContentTypeFor(fileName);

if (actualMimeType == null) {
return fallbackToDefaultMimeType(fileName);
}
return actualMimeType;
}

/**
* Checks if a given MIME type is allowed based on a collection of acceptable media
*
* @param acceptableMediaTypes
* @param mimeType
* @return
*/
public static boolean isMimeTypeAllowed(
Collection<String> acceptableMediaTypes, String mimeType) {
if (mimeType == null) {
return false;
}

if (acceptableMediaTypes == null
|| acceptableMediaTypes.isEmpty()
|| acceptableMediaTypes.contains("*/*")) return true;

String baseMimeType = mimeType.trim().toLowerCase();
Collection<String> normalizedTypes =
acceptableMediaTypes.stream().map(type -> type.trim().toLowerCase()).toList();

return normalizedTypes.stream()
.anyMatch(
type -> {
return type.endsWith("/*")
? baseMimeType.startsWith(type.substring(0, type.length() - 1))
: baseMimeType.equals(type);
});
}

private static String fallbackToDefaultMimeType(String fileName) {
logger.warn(
"Could not determine mime type for file: {}. Setting mime type to default: {}",
fileName,
DEFAULT_MEDIA_TYPE);
return DEFAULT_MEDIA_TYPE;
}

private MediaTypeService() {
// to prevent instantiation
}
}
Loading
Loading