Skip to content
Merged
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,19 @@ GeneratedObject image = new MinecraftTooltipGenerator.Builder()
- **Caching** of rendered objects via Caffeine
- **Alternate fonts** including Galactic (Standard Galactic Alphabet) and Illageralt

## Render limits

Text and options usually reach the generators from untrusted users, so every renderer checks a shared pixel budget (`RenderLimits`) before it allocates a canvas. A render over budget fails with a `GeneratorValidationException` instead of exhausting the heap. Both limits are system properties:

| Property | Default | Limits |
|---|---|---|
| `generator.render.maxCanvasPixels` | 25,000,000 | Pixels in one canvas (about 100 MB of ARGB) |
| `generator.render.maxAnimationPixels` | 400,000,000 | Pixels summed over every frame of one animation |

The animation default leaves room for the largest stock render, a full chest with the 182-frame enchant glint (about 256 million pixels, roughly 1 GB while it renders). Lower it on a host with a small heap.

Individual inputs are bounded as well: icon placeholder repeat counts (`%%dot:N%%`) clamp to 100, tooltip padding clamps to 255, inventories take at most 64 rows and 64 slots per row, scene `scale` is at most 16, scene margins, spacing and offsets at most 4096, and one content template fill produces at most 1,000,000 characters of output.

## Requirements

- Java 25
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.aerh.imagegenerator.effect.impl;

import net.aerh.imagegenerator.image.RenderLimits;
import net.aerh.imagegenerator.effect.EffectContext;
import net.aerh.imagegenerator.effect.EffectResult;
import net.aerh.imagegenerator.effect.ImageEffect;
Expand Down Expand Up @@ -52,6 +53,7 @@ public EffectResult apply(EffectContext context) {
int frameCount = (int) Math.ceil((double) TOTAL_DURATION_MS / FRAME_DELAY_MS);
int width = baseImage.getWidth();
int height = baseImage.getHeight();
RenderLimits.checkFrames(width, height, frameCount);
int[] basePixels = baseImage.getRGB(0, 0, width, height, null, 0, width);

double spriteSpanU = BASE_SPRITE_PIXELS / glintTexture.getWidth();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ private GeneratedObject buildStaticInternal(List<GeneratedObject> generatedObjec
throw new GeneratorException("Calculated image dimensions are invalid (width=" + totalWidth + ", height=" + maxHeight + ")");
}

RenderLimits.checkCanvas((long) totalWidth + 2 * IMAGE_BORDER_PADDING_PX, (long) maxHeight + 2 * IMAGE_BORDER_PADDING_PX);

BufferedImage finalImage = new BufferedImage(totalWidth + 2 * IMAGE_BORDER_PADDING_PX, maxHeight + 2 * IMAGE_BORDER_PADDING_PX, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = finalImage.createGraphics();
try {
Expand Down Expand Up @@ -241,6 +243,8 @@ private GeneratedObject buildAnimatedInternal(List<GeneratedObject> generatedObj
throw new GeneratorException("Calculated animated image dimensions are invalid (width=" + totalWidth + ", height=" + maxHeight + ")");
}

RenderLimits.checkFrames((long) totalWidth + 2 * IMAGE_BORDER_PADDING_PX, (long) maxHeight + 2 * IMAGE_BORDER_PADDING_PX, maxFrames);

List<BufferedImage> compositeFrames = new ArrayList<>();

// Generate each frame
Expand Down Expand Up @@ -319,6 +323,8 @@ private GeneratedObject buildTickTimedComposite(List<GeneratedObject> generatedO
+ totalWidth + ", height=" + maxHeight + ")");
}

RenderLimits.checkFrames((long) totalWidth + 2 * IMAGE_BORDER_PADDING_PX, (long) maxHeight + 2 * IMAGE_BORDER_PADDING_PX, timeline.steps().size());

List<BufferedImage> compositeFrames = new ArrayList<>(timeline.steps().size());
for (AnimationTimeline.Step step : timeline.steps()) {
BufferedImage compositeFrame = new BufferedImage(totalWidth + 2 * IMAGE_BORDER_PADDING_PX, maxHeight + 2 * IMAGE_BORDER_PADDING_PX, BufferedImage.TYPE_INT_ARGB);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
@Slf4j
public class MinecraftTooltip {

/** The widest padding, in px per side, a tooltip accepts; larger values are clamped. */
public static final int MAX_PADDING = 255;

private static final Map<Integer, Map<Integer, List<Character>>> OBFUSCATION_WIDTH_MAPS = new HashMap<>(); // Integer key represents font style index (0: regular, 1: bold, 2: italic, 3: bold-italic)
private static final int[] UNICODE_BLOCK_RANGES = {
0x0020, 0x007E, // Basic Latin
Expand Down Expand Up @@ -314,6 +317,12 @@ public boolean hasFirstLinePadding() {
*
* @return The padded {@link BufferedImage} frame.
*/
/** Checks the padded frame size against the shared pixel budget before any frame is allocated. */
private void checkFrameBudget(int frameWidth, int frameHeight, int frameCount) {
long padding = Math.max(0, this.getPadding()) * 2L;
RenderLimits.checkFrames(frameWidth + padding, frameHeight + padding, frameCount);
}

private BufferedImage addPadding(BufferedImage frame) {
if (this.getPadding() <= 0) {
return frame;
Expand Down Expand Up @@ -1072,6 +1081,7 @@ public MinecraftTooltip render() {
}

int framesToGenerate = this.isAnimated ? this.animationFrameCount : 1;
checkFrameBudget(frameWidth, frameHeight, framesToGenerate);
BufferedImage themeLayer = isThemed() ? buildThemeLayer(frameWidth, frameHeight, this.themeSprites) : null;

for (int i = 0; i < framesToGenerate; i++) {
Expand Down Expand Up @@ -1152,6 +1162,7 @@ private MinecraftTooltip renderAnimatedChrome(int frameWidth, int frameHeight, b
sources.add(Collections.nCopies(this.animationFrameCount, obfuscationTicks));
}
AnimationTimeline timeline = AnimationTimeline.of(sources);
checkFrameBudget(frameWidth, frameHeight, timeline.steps().size());

Map<Long, BufferedImage> themeLayers = new HashMap<>();
List<Integer> delays = new ArrayList<>(timeline.steps().size());
Expand Down Expand Up @@ -1289,7 +1300,7 @@ public Builder withLines(@NotNull Iterable<LineSegment> lines) {
}

public Builder withPadding(int padding) {
this.padding = Math.max(0, padding);
this.padding = Math.max(0, Math.min(padding, MAX_PADDING));
return this;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package net.aerh.imagegenerator.image;

import net.aerh.imagegenerator.exception.GeneratorValidationException;

/**
* The shared pixel budget every renderer checks before it allocates a canvas. Request options and
* text reach the renderers from untrusted callers, and a canvas costs four bytes per pixel per frame,
* so an unchecked size turns a short input into gigabytes of heap. Checking the size up front fails
* the one request with a {@link GeneratorValidationException} instead of exhausting the JVM.
*
* <p>Both limits are read from system properties on each check, so a host can raise or lower them:</p>
* <ul>
* <li>{@value #MAX_CANVAS_PIXELS_PROPERTY} - pixels in one canvas (default
* {@value #DEFAULT_MAX_CANVAS_PIXELS}, about 100 MB of ARGB)</li>
* <li>{@value #MAX_ANIMATION_PIXELS_PROPERTY} - pixels summed over every frame of one animation
* (default {@value #DEFAULT_MAX_ANIMATION_PIXELS}; a full chest with the 182-frame enchant glint
* needs about 256 million)</li>
* </ul>
*/
public final class RenderLimits {

public static final String MAX_CANVAS_PIXELS_PROPERTY = "generator.render.maxCanvasPixels";
public static final String MAX_ANIMATION_PIXELS_PROPERTY = "generator.render.maxAnimationPixels";

public static final long DEFAULT_MAX_CANVAS_PIXELS = 25_000_000L;
public static final long DEFAULT_MAX_ANIMATION_PIXELS = 400_000_000L;

private RenderLimits() {
}

/** The most pixels one canvas may hold. */
public static long maxCanvasPixels() {
return positiveProperty(MAX_CANVAS_PIXELS_PROPERTY, DEFAULT_MAX_CANVAS_PIXELS);
}

/** The most pixels all frames of one animation may hold together. */
public static long maxAnimationPixels() {
return positiveProperty(MAX_ANIMATION_PIXELS_PROPERTY, DEFAULT_MAX_ANIMATION_PIXELS);
}

/**
* Rejects a single canvas that is over the canvas budget. Takes {@code long} sizes so callers can
* pass arithmetic that would overflow an {@code int}.
*
* @throws GeneratorValidationException if either side is not positive or the area is over budget
*/
public static void checkCanvas(long width, long height) {
checkFrames(width, height, 1);
}

/**
* Rejects an animation whose canvas is over the canvas budget or whose frames together are over
* the animation budget.
*
* @throws GeneratorValidationException if the size is not positive or over either budget
*/
public static void checkFrames(long width, long height, long frameCount) {
if (width <= 0 || height <= 0 || width > Integer.MAX_VALUE || height > Integer.MAX_VALUE) {
throw new GeneratorValidationException("Image size %sx%s is out of range",
String.valueOf(width), String.valueOf(height));
}

long maxCanvas = maxCanvasPixels();
long area = width * height;
if (area > maxCanvas) {
throw new GeneratorValidationException(
"Image is too large to render: %sx%s is over the limit of %s pixels",
String.valueOf(width), String.valueOf(height), String.valueOf(maxCanvas));
}

long frames = Math.max(1, frameCount);
long maxAnimation = maxAnimationPixels();
// area fits in 2^62 and frames is small, but guard the product anyway
if (frames > 1 && area > maxAnimation / frames) {
throw new GeneratorValidationException(
"Animation is too large to render: %s frames of %sx%s is over the limit of %s pixels in total",
String.valueOf(frames), String.valueOf(width), String.valueOf(height), String.valueOf(maxAnimation));
}
}

private static long positiveProperty(String property, long fallback) {
Long configured = Long.getLong(property);
return configured != null && configured > 0 ? configured : fallback;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.aerh.imagegenerator.impl;

import net.aerh.imagegenerator.image.RenderLimits;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.AccessLevel;
Expand Down Expand Up @@ -246,6 +247,7 @@ ColorSegment toSegment(ChatColor defaultColor) {
private GeneratedObject renderStatic(@Nullable GenerationContext generationContext) {
int pixelSize = 2 * scaleFactor;
Layout layout = computeLayout(pixelSize);
RenderLimits.checkCanvas(layout.canvasWidth(), layout.canvasHeight());
BufferedImage canvas = new BufferedImage(layout.canvasWidth(), layout.canvasHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = canvas.createGraphics();
try {
Expand Down Expand Up @@ -316,6 +318,7 @@ private GeneratedObject renderAnimated(@Nullable GenerationContext generationCon
BufferedImage staticBackground = backgroundAnimation == null && PackId.isActive(packId)
? repository().resolveContainerBackground(packId).orElse(null)
: null;
RenderLimits.checkFrames(layout.canvasWidth(), layout.canvasHeight(), timeline.steps().size());
List<BufferedImage> frames = new ArrayList<>(timeline.steps().size());
for (AnimationTimeline.Step step : timeline.steps()) {
BufferedImage canvas = new BufferedImage(layout.canvasWidth(), layout.canvasHeight(), BufferedImage.TYPE_INT_ARGB);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.aerh.imagegenerator.impl;

import net.aerh.imagegenerator.image.RenderLimits;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
Expand Down Expand Up @@ -125,6 +126,7 @@ public static int lineTopGuiPx(int lineIndex) {
canvasHeightGuiPx = Math.max(canvasHeightGuiPx, lineTopGuiPx(lineIndex) + artBottomGuiPx);
}

RenderLimits.checkCanvas((long) guiWidth * pixelSize, (long) canvasHeightGuiPx * pixelSize);
BufferedImage canvas = new BufferedImage(canvasWidth, canvasHeightGuiPx * pixelSize,
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = canvas.createGraphics();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.aerh.imagegenerator.impl;

import net.aerh.imagegenerator.image.RenderLimits;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -40,6 +41,9 @@
@ToString
public class MinecraftInventoryGenerator implements Generator {

/** The most rows, and the most slots in a row, an inventory may have. */
public static final int MAX_SLOTS_PER_AXIS = 64;

private static final Color NORMAL_TEXT_COLOR = new Color(255, 255, 255);
private static final Color DROP_SHADOW_COLOR = new Color(63, 63, 63);
private static final Color INVENTORY_BACKGROUND = new Color(198, 198, 198);
Expand Down Expand Up @@ -173,6 +177,7 @@ private void initializeImage() {

int imageWidth = (slotsPerRow * slotSize) + (borderSize * 2);
int imageHeight = (rows * slotSize) + titleHeight + borderSize;
RenderLimits.checkCanvas((long) slotsPerRow * slotSize + borderSize * 2L, (long) rows * slotSize + titleHeight + borderSize);

this.inventoryImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
this.g2d = inventoryImage.createGraphics();
Expand Down Expand Up @@ -732,6 +737,7 @@ private List<BufferedImage> buildAnimationFrames(List<InventoryItem> items) {
return frames;
}

RenderLimits.checkFrames(inventoryImage.getWidth(), inventoryImage.getHeight(), maxFrames);
for (int frameIndex = 0; frameIndex < maxFrames; frameIndex++) {
BufferedImage frame = new BufferedImage(inventoryImage.getWidth(), inventoryImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D frameGraphics = frame.createGraphics();
Expand Down Expand Up @@ -801,6 +807,7 @@ private SceneAnimation buildTextureAnimationFrames(List<InventoryItem> items) {

AnimationTimeline timeline = AnimationTimeline.of(sources);
List<BufferedImage> originalImages = animatedItems.stream().map(InventoryItem::getItemImage).toList();
RenderLimits.checkFrames(inventoryImage.getWidth(), inventoryImage.getHeight(), timeline.steps().size());
List<BufferedImage> frames = new ArrayList<>(timeline.steps().size());
for (AnimationTimeline.Step step : timeline.steps()) {
BufferedImage frame = new BufferedImage(inventoryImage.getWidth(), inventoryImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
Expand Down Expand Up @@ -933,6 +940,9 @@ protected void validate() {
if (rows <= 0 || slotsPerRow <= 0) {
throw new IllegalArgumentException("rows and slotsPerRow must be positive");
}
if (rows > MAX_SLOTS_PER_AXIS || slotsPerRow > MAX_SLOTS_PER_AXIS) {
throw new IllegalArgumentException("rows and slotsPerRow must be at most " + MAX_SLOTS_PER_AXIS);
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@
@Slf4j
public final class StrictJson {

/** The longest number literal accepted, in characters. */
private static final int MAX_NUMBER_LENGTH = 64;
/** The largest decimal exponent, in either direction, a number literal may carry. */
private static final int MAX_NUMBER_SCALE = 400;

private StrictJson() {
}

Expand Down Expand Up @@ -107,7 +112,7 @@ public static JsonElement readElement(JsonReader reader, String what) throws IOE
return new JsonPrimitive(reader.nextString());
}
case NUMBER -> {
return new JsonPrimitive(new BigDecimal(reader.nextString()));
return new JsonPrimitive(readNumber(reader.nextString(), what));
}
case BOOLEAN -> {
return new JsonPrimitive(reader.nextBoolean());
Expand Down Expand Up @@ -157,6 +162,28 @@ public static void warnUnknownKeys(JsonObject object, Set<String> allowed, Strin
*
* @throws IllegalArgumentException naming the key when the value is absent or not an integer
*/
/**
* Parses one number literal, rejecting the ones whose plain form would be enormous. A literal like
* {@code 1e900000000} is a dozen bytes of input, but printing or rescaling it materialises hundreds
* of megabytes of digits, so both its length and its exponent are bounded here.
*/
private static BigDecimal readNumber(String literal, String what) {
if (literal.length() > MAX_NUMBER_LENGTH) {
throw new IllegalArgumentException("Number in " + what + " JSON is too long (over "
+ MAX_NUMBER_LENGTH + " characters)");
}
BigDecimal value;
try {
value = new BigDecimal(literal);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Malformed number in " + what + " JSON: " + literal);
}
if (Math.abs((long) value.scale()) > MAX_NUMBER_SCALE) {
throw new IllegalArgumentException("Number in " + what + " JSON is out of range: " + literal);
}
return value;
}

public static int requireInt(JsonObject object, String key) {
JsonElement element = object.get(key);
if (element == null || !element.isJsonPrimitive() || !element.getAsJsonPrimitive().isNumber()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.aerh.imagegenerator.impl.scene;

import net.aerh.imagegenerator.image.RenderLimits;
import net.aerh.imagegenerator.exception.GeneratorException;
import net.aerh.imagegenerator.item.GeneratedObject;
import net.aerh.imagegenerator.pack.AnimationTimeline;
Expand Down Expand Up @@ -62,9 +63,11 @@ static GeneratedObject compose(List<PlacedObject> placed, int width, int height)
}
}
if (sources.isEmpty()) {
RenderLimits.checkCanvas(width, height);
return new GeneratedObject(composeFrame(placed, width, height, null));
}
AnimationTimeline timeline = AnimationTimeline.of(sources);
RenderLimits.checkFrames(width, height, timeline.steps().size());

List<BufferedImage> compositeFrames = new ArrayList<>(timeline.steps().size());
for (AnimationTimeline.Step step : timeline.steps()) {
Expand Down
Loading