Compare commits

...

10 Commits

Author SHA1 Message Date
e5cdce164a feat(recipes): give 'Bild entfernen' button persistent muted-red color
Was only red on hover — now always red at 60% opacity, full opacity on hover,
making the destructive intent immediately visible.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:40:51 +02:00
73b4fb84e7 feat(recipes): add (min) unit hint to Kochzeit label
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:40:04 +02:00
932155c559 chore(backend): ignore application-dev.yml to prevent leaking local secrets
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:39:01 +02:00
a5bb5d45a3 docs(config): annotate multipart limits explaining JSON body is not covered
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:38:48 +02:00
b2a798d90e docs(tests): clarify why fake base64 is acceptable in allowed-image-type test
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:38:29 +02:00
23c821937f test(recipes): add JPEG input test for ImageCompressor
Confirms the compressor accepts JPEG data URIs as input (not just PNG).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:38:01 +02:00
9df6d6f0c6 test(recipes): verify null preview is stored when compressor returns null
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:37:24 +02:00
ebaf42d83d feat(recipes): return fail(422) when all ingredients filter to empty
Prevents a silent 400 from the backend when the user submits a form
where every ingredient row has quantity <= 0 or blank name.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:36:41 +02:00
56e6143fd2 feat(recipes): validate image MIME type on file select
Rejects non-allowlisted types (only JPEG, PNG, GIF, WebP accepted) with
an inline error message. Uses image/bmp as test vector since it passes
accept="image/*" but is not in the allowed set.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:33:39 +02:00
ed769b18a4 fix(recipe): add server-side image size limit and use .matches() for type check
- @Size(max=7_000_000) on heroImageUrl enforces ~5 MB cap at bean validation
- ALLOWED_IMAGE_PATTERN uses .matches() for unambiguous full-string check
- Tests: oversized image → 400, empty ingredients list → 400

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 09:27:35 +02:00
13 changed files with 180 additions and 23 deletions

3
backend/.gitignore vendored
View File

@@ -31,3 +31,6 @@ build/
### VS Code ###
.vscode/
### Local dev config (may contain secrets / local DB credentials) ###
src/main/resources/application-dev.yml

View File

@@ -191,11 +191,11 @@ public class RecipeService {
// ── Image validation ──
private static final java.util.regex.Pattern ALLOWED_IMAGE_PATTERN =
java.util.regex.Pattern.compile("^data:image/(jpeg|jpg|png|gif|webp);base64,");
java.util.regex.Pattern.compile("data:image/(jpeg|jpg|png|gif|webp);base64,.*");
private void validateHeroImageUrl(String heroImageUrl) {
if (heroImageUrl == null || heroImageUrl.isBlank()) return;
if (!ALLOWED_IMAGE_PATTERN.matcher(heroImageUrl).find()) {
if (!ALLOWED_IMAGE_PATTERN.matcher(heroImageUrl).matches()) {
throw new ValidationException("Ungültiger Bildtyp. Erlaubt sind: JPEG, PNG, GIF, WebP.");
}
}

View File

@@ -12,7 +12,7 @@ public record RecipeCreateRequest(
Integer serves,
Integer cookTimeMin,
@NotBlank @Pattern(regexp = "easy|medium|hard") String effort,
String heroImageUrl,
@Size(max = 7_000_000) String heroImageUrl,
@NotEmpty @Valid List<IngredientEntry> ingredients,
@Valid List<StepEntry> steps,
@NotEmpty List<UUID> tagIds

View File

@@ -21,6 +21,10 @@ spring:
servlet:
multipart:
# NOTE: these limits only apply to multipart/form-data uploads.
# Images sent as base64 inside a JSON body (Content-Type: application/json)
# are NOT constrained here — the @Size(max=7_000_000) annotation on
# RecipeCreateRequest.heroImageUrl enforces the limit for that path.
max-file-size: 5MB
max-request-size: 6MB

View File

@@ -80,6 +80,17 @@ class ImageCompressorTest {
assertThat(compressor.compressToPreview("data:image/jpeg;base64,!!!not-valid!!!")).isNull();
}
@Test
void compressToPreview_acceptsJpegInput() throws Exception {
String dataUri = makeJpegDataUri(800, 600);
String result = compressor.compressToPreview(dataUri);
assertThat(result).startsWith("data:image/jpeg;base64,");
String base64 = result.substring("data:image/jpeg;base64,".length());
BufferedImage img = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64)));
assertThat(img).isNotNull();
assertThat(img.getWidth()).isLessThanOrEqualTo(400);
}
// ── helpers ──
private String makePngDataUri(int width, int height) throws Exception {
@@ -95,4 +106,15 @@ class ImageCompressorTest {
ImageIO.write(img, "png", bos);
return "data:image/png;base64," + Base64.getEncoder().encodeToString(bos.toByteArray());
}
private String makeJpegDataUri(int width, int height) throws Exception {
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
java.awt.Graphics2D g = img.createGraphics();
g.setColor(java.awt.Color.ORANGE);
g.fillRect(0, 0, width, height);
g.dispose();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(img, "jpeg", bos);
return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(bos.toByteArray());
}
}

View File

@@ -161,6 +161,33 @@ class RecipeControllerTest {
verify(recipeService).deleteRecipe(HOUSEHOLD_ID, RECIPE_ID);
}
@Test
void createRecipeWithOversizedHeroImageShouldReturn400() throws Exception {
String heroImageUrl = "data:image/jpeg;base64," + "A".repeat(7_000_000);
String body = "{\"name\":\"Test\",\"effort\":\"easy\",\"tagIds\":[\"" + UUID.randomUUID() + "\"]," +
"\"ingredients\":[{\"quantity\":1,\"unit\":\"g\",\"newIngredientName\":\"x\",\"sortOrder\":0}]," +
"\"heroImageUrl\":\"" + heroImageUrl + "\"}";
mockMvc.perform(post("/v1/recipes")
.principal(() -> "sarah@example.com")
.contentType(MediaType.APPLICATION_JSON)
.content(body))
.andExpect(status().isBadRequest());
}
@Test
void createRecipeWithEmptyIngredientsListShouldReturn400() throws Exception {
var body = """
{"name":"Test","effort":"easy","tagIds":["%s"],"ingredients":[]}
""".formatted(UUID.randomUUID());
mockMvc.perform(post("/v1/recipes")
.principal(() -> "sarah@example.com")
.contentType(MediaType.APPLICATION_JSON)
.content(body))
.andExpect(status().isBadRequest());
}
@Test
void createRecipeWithCapitalisedEffortShouldReturn400() throws Exception {
var body = """

View File

@@ -589,6 +589,8 @@ class RecipeServiceTest {
when(householdRepository.findById(HOUSEHOLD_ID)).thenReturn(Optional.of(household));
when(recipeRepository.save(any(Recipe.class))).thenAnswer(i -> i.getArgument(0));
// "abc" is not valid base64 for a real image; ImageCompressor will return null for the
// preview, but validateHeroImageUrl() should pass for a well-formed data URI prefix.
var request = new RecipeCreateRequest(
"Test", null, null, "easy", "data:image/jpeg;base64,abc",
List.of(), List.of(), List.of());
@@ -604,4 +606,30 @@ class RecipeServiceTest {
assertThat(result).isEmpty();
}
@Test
void createRecipeShouldStoreNullPreviewWhenCompressorReturnsNull() {
var household = testHousehold();
when(householdRepository.findById(HOUSEHOLD_ID)).thenReturn(Optional.of(household));
when(imageCompressor.compressToPreview(any())).thenReturn(null);
when(recipeRepository.save(any(Recipe.class))).thenAnswer(i -> {
Recipe r = i.getArgument(0);
try {
var field = Recipe.class.getDeclaredField("id");
field.setAccessible(true);
field.set(r, UUID.randomUUID());
} catch (Exception e) { throw new RuntimeException(e); }
return r;
});
var request = new RecipeCreateRequest(
"Soup", null, null, "easy", "data:image/jpeg;base64,abc",
List.of(), List.of(), List.of());
RecipeDetailResponse result = recipeService.createRecipe(HOUSEHOLD_ID, request);
assertThat(result.id()).isNotNull();
// verify the recipe was saved without a preview (compressor returned null)
verify(recipeRepository).save(argThat(r -> r.getHeroImagePreview() == null));
}
}

View File

@@ -64,6 +64,7 @@
let imageError = $state<string | null>(null);
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
function handleImageChange(e: Event) {
const file = (e.currentTarget as HTMLInputElement).files?.[0];
@@ -73,6 +74,11 @@
(e.currentTarget as HTMLInputElement).value = '';
return;
}
if (!ALLOWED_MIME_TYPES.includes(file.type)) {
imageError = 'Dateityp nicht unterstützt. Erlaubt: JPEG, PNG, GIF, WebP.';
(e.currentTarget as HTMLInputElement).value = '';
return;
}
imageError = null;
const reader = new FileReader();
reader.onload = () => {
@@ -137,7 +143,7 @@
for="cookTimeMin"
class="mb-[6px] block text-[12px] font-medium text-[var(--color-text)]"
>
Kochzeit
Kochzeit (min)
</label>
<input
id="cookTimeMin"
@@ -189,7 +195,7 @@
<button
type="button"
onclick={() => (heroImageUrl = null)}
class="mb-[8px] text-[12px] text-[var(--color-text-muted)] hover:text-[var(--color-error)] cursor-pointer"
class="mb-[8px] text-[12px] text-[var(--color-error)] opacity-60 hover:opacity-100 cursor-pointer"
>
Bild entfernen
</button>

View File

@@ -189,4 +189,26 @@ describe('RecipeForm', () => {
expect(screen.queryByText(/datei zu groß/i)).not.toBeInTheDocument();
});
it('shows error when selected file has unsupported type', async () => {
const user = userEvent.setup();
render(RecipeForm, { props: emptyProps });
const bmpFile = new File(['content'], 'image.bmp', { type: 'image/bmp' });
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
await user.upload(fileInput, bmpFile);
expect(screen.getByText(/dateityp/i)).toBeInTheDocument();
});
it('does not show type error for supported image types', async () => {
const user = userEvent.setup();
render(RecipeForm, { props: emptyProps });
const jpgFile = new File(['content'], 'photo.jpg', { type: 'image/jpeg' });
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
await user.upload(fileInput, jpgFile);
expect(screen.queryByText(/dateityp/i)).not.toBeInTheDocument();
});
});

View File

@@ -67,6 +67,13 @@ export const actions: Actions = {
return fail(400, { error: 'Ungültige Formulardaten' });
}
const filteredIngredients = (
parsedIngredients as { name: string; quantity: string; unit: string }[]
).filter((ing) => ing.name?.trim() && Number(ing.quantity) > 0);
if (!filteredIngredients.length)
return fail(422, { error: 'Mindestens eine gültige Zutat ist erforderlich' });
const api = apiClient(fetch);
const { error: apiError } = await api.PUT('/v1/recipes/{id}', {
params: { path: { id: params.id } },
@@ -76,14 +83,12 @@ export const actions: Actions = {
cookTimeMin: cookTimeMin ? Number(cookTimeMin) || null : null,
effort,
heroImageUrl,
ingredients: (parsedIngredients as { name: string; quantity: string; unit: string }[])
.filter((ing) => ing.name?.trim() && Number(ing.quantity) > 0)
.map((ing, i) => ({
newIngredientName: ing.name.trim(),
quantity: Number(ing.quantity),
unit: ing.unit || '',
sortOrder: i
})),
ingredients: filteredIngredients.map((ing, i) => ({
newIngredientName: ing.name.trim(),
quantity: Number(ing.quantity),
unit: ing.unit || '',
sortOrder: i
})),
steps: (parsedSteps as string[])
.filter((s) => s?.trim())
.map((s, i) => ({ stepNumber: i + 1, instruction: s.trim() })),

View File

@@ -84,7 +84,7 @@ describe('edit recipe page — update action', () => {
name: 'Test Rezept',
effort: 'easy',
tagIds: ['t1'],
ingredientsJson: '[]',
ingredientsJson: JSON.stringify([{ name: 'Spaghetti', quantity: 200, unit: 'g' }]),
stepsJson: '[]',
...overrides
};
@@ -236,6 +236,24 @@ describe('edit recipe page — update action', () => {
expect(body.ingredients[0].newIngredientName).toBe('Spaghetti');
});
it('returns fail(422) when all ingredients filter to empty after quantity check', async () => {
const result = await actions.update({
request: {
formData: async () =>
makeFormData({
ingredientsJson: JSON.stringify([
{ name: 'Salt', quantity: 0, unit: 'tsp' },
{ name: '', quantity: 100, unit: 'g' }
])
})
},
fetch: vi.fn(),
params: { id: 'r1' }
} as any);
expect(result.status).toBe(422);
expect(result.data.error).toMatch(/zutat/i);
});
it('returns fail(500) when API returns error', async () => {
mockPut.mockResolvedValue({ error: { status: 500 } });
const result = await actions.update({

View File

@@ -40,6 +40,13 @@ export const actions: Actions = {
return fail(400, { error: 'Ungültige Formulardaten' });
}
const filteredIngredients = (
parsedIngredients as { name: string; quantity: string; unit: string }[]
).filter((ing) => ing.name?.trim() && Number(ing.quantity) > 0);
if (!filteredIngredients.length)
return fail(422, { error: 'Mindestens eine gültige Zutat ist erforderlich' });
const api = apiClient(fetch);
const { error: apiError } = await api.POST('/v1/recipes', {
body: {
@@ -48,14 +55,12 @@ export const actions: Actions = {
cookTimeMin: cookTimeMin ? Number(cookTimeMin) || null : null,
effort,
heroImageUrl,
ingredients: (parsedIngredients as { name: string; quantity: string; unit: string }[])
.filter((ing) => ing.name?.trim() && Number(ing.quantity) > 0)
.map((ing, i) => ({
newIngredientName: ing.name.trim(),
quantity: Number(ing.quantity),
unit: ing.unit || '',
sortOrder: i
})),
ingredients: filteredIngredients.map((ing, i) => ({
newIngredientName: ing.name.trim(),
quantity: Number(ing.quantity),
unit: ing.unit || '',
sortOrder: i
})),
steps: (parsedSteps as string[])
.filter((s) => s?.trim())
.map((s, i) => ({ stepNumber: i + 1, instruction: s.trim() })),

View File

@@ -62,7 +62,7 @@ describe('new recipe page — create action', () => {
name: 'Test Rezept',
effort: 'easy',
tagIds: ['t1'],
ingredientsJson: '[]',
ingredientsJson: JSON.stringify([{ name: 'Spaghetti', quantity: 200, unit: 'g' }]),
stepsJson: '[]',
...overrides
};
@@ -189,6 +189,23 @@ describe('new recipe page — create action', () => {
expect(body.ingredients[0].newIngredientName).toBe('Spaghetti');
});
it('returns fail(422) when all ingredients filter to empty after quantity check', async () => {
const result = await actions.create({
request: {
formData: async () =>
makeFormData({
ingredientsJson: JSON.stringify([
{ name: 'Salt', quantity: 0, unit: 'tsp' },
{ name: '', quantity: 100, unit: 'g' }
])
})
},
fetch: vi.fn()
} as any);
expect(result.status).toBe(422);
expect(result.data.error).toMatch(/zutat/i);
});
it('returns fail(500) when API returns error', async () => {
mockPost.mockResolvedValue({ error: { status: 500 } });
const result = await actions.create({