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
8 changes: 8 additions & 0 deletions .grype.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ ignore:
# Remove this entry as soon as a patched braces is published and picked up by the lockfiles.
- vulnerability: GHSA-vfj7-8cjw-p6xm

# source-map-js 1.2.1 (GHSA-68fv-2mgg-jv7q, High, published 2026-09-18): event-loop DoS through
# indexed source-map section offsets in untrusted source maps. Reached only through postcss and
# sass inside the Angular CLI build (ui/), which parses our own sources at build time; nothing of
# it is deployed. The fix, 1.2.2, exists (published 2026-09-30) but the repo's .npmrc
# (min-release-age=7) quarantines it until 2026-10-07. Accepted until then — bump and remove this
# entry per #348.
- vulnerability: GHSA-68fv-2mgg-jv7q

# Registry configuration (if needed for private registries)
# registry:
# auth:
Expand Down
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,13 @@
</exclusion>
</exclusions>
</dependency>
<!-- QR encoding for EN10168 v0.5.0 qr-code entries (#346): the symbol is emitted as SVG path
data, so only core is needed (javase would pull in image I/O). Same version as schema's :shared. -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
Expand Down
4 changes: 3 additions & 1 deletion schemas/EN10168/v0.5.0/stylesheet.xsl
Original file line number Diff line number Diff line change
Expand Up @@ -1588,7 +1588,9 @@
</fo:basic-link>
</xsl:when>
<xsl:when test="$type = 'qr-code'">
<!-- QR code generation typically requires an external library or pre-generated image -->
<!-- The symbol is generated before the stylesheet runs (QrCodeValues, #447): Value arrives as
the SVG data URI of the symbol encoding the certificate's text (its URL), or as the ready
image a certificate issued under the earlier reading embedded. -->
<fo:external-graphic fox:alt-text="QR Code" src="{$value}" content-width="80px" width="80px" scaling="uniform" />
</xsl:when>
<xsl:when test="$type = 'image'">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,10 @@ private static void convertJsonToPdf(String inputFile, String outputFile, String
}

// Build PDF using the command-line builder pattern (with font loading fixes)
// The stylesheet renders a copy with every qr-code symbol generated (#346); the attached
// jsonContent is the certificate as issued.
CommandLinePDFBuilder pdfBuilder = new CommandLinePDFBuilder()
.withXsltTransformer(new XsltTransformer(xsltSource, certificate, baseUri))
.withXsltTransformer(new XsltTransformer(xsltSource, QrCodeValues.embedSymbols(certificate), baseUri))
.withTranslations(new TranslationLoader(translationsPattern, languages))
.withAttachment(new AttachmentManager(jsonContent,
Paths.get(outputFile).getFileName().toString().replace(".pdf", ""),
Expand Down
69 changes: 69 additions & 0 deletions src/main/java/com/materialidentity/schemaservice/QrCodeValues.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: Apache-2.0
package com.materialidentity.schemaservice;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
* Generates the symbol of every {@code qr-code} key-value entry before the stylesheet runs (#346, mirrors schema#447).
*
* <p>EN10168 v0.5.0's {@code KeyValueObject.Type} has carried {@code qr-code} since the {@code url},
* {@code phone}, {@code email} and {@code image} types were added, but nothing ever generated a
* symbol: the stylesheet drew whatever image the value happened to hold, so a certificate had to
* ship a hand-made picture next to the URL it showed. The rule now: <b>the value is the text the
* symbol encodes</b> (typically a URL) and the renderer generates the symbol. A value that is
* already a {@code data:} image URI keeps rendering as that image, so certificates issued under
* the earlier reading render exactly as before.
*
* <p>Done on the JSON rather than in XSLT because Saxon-HE has no QR encoder and the
* transformer factory registers no extension functions. The symbol arrives as an SVG {@code data:} URI, which
* the stylesheet's existing {@code fo:external-graphic} branch draws and the sandboxed FOP resolver
* admits without a fetch. Only the stylesheet sees the substituted document: the JSON attached to
* the PDF stays the certificate as issued.
*/
public final class QrCodeValues {

/** The {@code Type} whose value is encoded. */
static final String TYPE = "qr-code";

private QrCodeValues() {
}

/**
* A copy of the certificate in which every encodable {@code qr-code} value is replaced by the
* SVG data URI of its symbol. The given node is not modified.
*/
public static JsonNode embedSymbols(JsonNode certificate) {
JsonNode copy = certificate.deepCopy();
embedInto(copy);
return copy;
}

private static void embedInto(JsonNode node) {
if (node.isObject()) {
// Children first: a Value is text, never an object, so nothing substituted is revisited.
node.forEach(QrCodeValues::embedInto);
ObjectNode object = (ObjectNode) node;
if (encodes(object)) {
object.put("Value", QrSymbol.of(object.get("Value").asText()).toSvgDataUri());
}
} else if (node.isArray()) {
node.forEach(QrCodeValues::embedInto);
}
}

/** A {@code qr-code} entry whose value is text to encode rather than a ready image. */
static boolean encodes(JsonNode object) {
JsonNode type = object.get("Type");
JsonNode value = object.get("Value");
return type != null && TYPE.equals(type.asText())
&& value != null && value.isTextual()
&& !value.asText().isBlank()
&& !isDataUri(value.asText());
}

/** RFC 2397: the scheme is case-insensitive. */
private static boolean isDataUri(String value) {
return value.regionMatches(true, 0, "data:", 0, 5);
}
}
164 changes: 164 additions & 0 deletions src/main/java/com/materialidentity/schemaservice/QrSymbol.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// SPDX-License-Identifier: Apache-2.0
package com.materialidentity.schemaservice;

import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.EnumMap;
import java.util.Map;

/**
* One QR symbol (ISO/IEC 18004) encoding one string, emitted as SVG path data.
*
* <p>A copy of {@code QrSymbol} in material-identity/schema's {@code :shared} (schema#447), which the
* DPP data carrier and the legacy EN10168 pipeline there share; here it generates an EN10168 v0.5.0
* {@code qr-code} key-value entry's symbol from its value (#346). Same encoder, quiet zone and path
* format, so a symbol rendered by either service is the same picture.
*
* <p>Vector rather than raster: a PNG would have to be either an external reference or a base64
* blob that bloats every rendered view; path data is smaller, stays sharp when printed, and is the
* same input for an HTML view and an XSL-FO page.
*
* <p>The quiet zone is not decoration. ISO/IEC 18004 requires four modules of clear margin, and a
* QR printed flush against surrounding content is one many scanners will not read.
*
* <p>Error-correction level M (~15 %): the data is typically a URL of moderate length, and the
* symbol may end up on a label, a delivery note, or a certificate that has been folded and
* handled. L would be smaller and more fragile than that use deserves.
*/
public record QrSymbol(
String encodedData,
int moduleCount,
String pathData,
boolean[][] modules) {

/** ISO/IEC 18004 requires a four-module clear margin around the symbol. */
public static final int QUIET_ZONE = 4;

private static final String SVG_DATA_URI_PREFIX = "data:image/svg+xml;base64,";

/**
* Encode one string.
*
* @throws IllegalArgumentException for a blank string (an empty QR is worse than none: it
* scans, and yields nothing) or one too long for a single symbol
*/
public static QrSymbol of(String data) {
if (data == null || data.isBlank()) {
throw new IllegalArgumentException("A QR symbol encodes a string; none was given");
}
Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

QRCode qr;
try {
qr = Encoder.encode(data, ErrorCorrectionLevel.M, hints);
} catch (WriterException e) {
throw new IllegalArgumentException(
"Cannot encode as one QR symbol (" + data.length() + " characters): "
+ abbreviate(data), e);
}

ByteMatrix matrix = qr.getMatrix();
int size = matrix.getWidth();
boolean[][] modules = new boolean[size][size];
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
modules[y][x] = matrix.get(x, y) == 1;
}
}

return new QrSymbol(data, size + 2 * QUIET_ZONE, buildPath(modules, size), modules);
}

/**
* One SVG path covering every dark module, offset by the quiet zone.
*
* <p>A single path rather than one {@code <rect>} per module: a symbol of this size has several
* hundred dark modules, and the element-per-module form would add tens of kilobytes of markup
* to every rendered view for no visual difference. Horizontal runs are merged into one
* rectangle each, which roughly halves it again.
*
* <p>Returned as an attribute value, never as markup — so a stylesheet emits the SVG elements
* itself and nothing has to escape past the serializer.
*/
private static String buildPath(boolean[][] modules, int size) {
StringBuilder path = new StringBuilder();
for (int y = 0; y < size; y++) {
int runStart = -1;
for (int x = 0; x <= size; x++) {
boolean dark = x < size && modules[y][x];
if (dark && runStart < 0) {
runStart = x;
} else if (!dark && runStart >= 0) {
int width = x - runStart;
path.append('M').append(runStart + QUIET_ZONE).append(' ').append(y + QUIET_ZONE)
.append('h').append(width).append("v1h-").append(width).append('z');
runStart = -1;
}
}
}
return path.toString();
}

/**
* The symbol as a zxing {@link BitMatrix}, without the quiet zone.
*
* <p>Exists so a test can decode the symbol back and assert it yields the encoded string
* exactly. That round trip is what turns "the symbol encodes the value" from a claim in a
* comment into a verified property.
*/
public BitMatrix toBitMatrix() {
int size = modules.length;
BitMatrix bits = new BitMatrix(size, size);
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
if (modules[y][x]) {
bits.set(x, y);
}
}
}
return bits;
}

/**
* A standalone SVG document: black modules on a white ground, quiet zone included, scaling
* crisply to any size. The encoded string travels in {@code data-encoded} and in the title, so
* a viewer can say what the symbol opens without decoding it.
*/
public String toSvg() {
int n = moduleCount;
String text = escape(encodedData);
return "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 " + n + " " + n + "\""
+ " shape-rendering=\"crispEdges\" role=\"img\" aria-label=\"QR code: " + text + "\""
+ " data-encoded=\"" + text + "\" data-modules=\"" + modules.length + "\">"
+ "<title>" + text + "</title>"
+ "<rect width=\"" + n + "\" height=\"" + n + "\" fill=\"#fff\"/>"
+ "<path fill=\"#000\" d=\"" + pathData + "\"/>"
+ "</svg>\n";
}

/**
* {@link #toSvg()} as a {@code data:} URI, so a stylesheet's {@code fo:external-graphic} can draw
* the symbol with no resource fetch at all.
*/
public String toSvgDataUri() {
return SVG_DATA_URI_PREFIX
+ Base64.getEncoder().encodeToString(toSvg().getBytes(StandardCharsets.UTF_8));
}

private static String escape(String s) {
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}

private static String abbreviate(String s) {
return s.length() <= 80 ? s : s.substring(0, 77) + "...";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import com.materialidentity.schemaservice.PDFBuilder;
import com.materialidentity.schemaservice.TranslationLoader;
import com.materialidentity.schemaservice.WatermarkManager;
import com.materialidentity.schemaservice.QrCodeValues;
import com.materialidentity.schemaservice.XsltTransformer;
import com.materialidentity.schemaservice.config.SchemaControllerConstants;
import com.materialidentity.schemaservice.config.SchemasAndVersions;
Expand Down Expand Up @@ -206,8 +207,10 @@ public ResponseEntity<byte[]> renderPdf(Boolean attachJson, JsonNode certificate
// Derive classpath root URI so json-doc() can resolve relative paths
String baseUri = deriveClasspathRootUri(xsltResource, xsltPath);

// The stylesheet renders a copy with every qr-code symbol generated (#346); the JSON attached
// below (certificateJson) is the certificate as issued.
PDFBuilder pdfBuilder = new PDFBuilder()
.withXsltTransformer(new XsltTransformer(xsltSource, certificate, baseUri))
.withXsltTransformer(new XsltTransformer(xsltSource, QrCodeValues.embedSymbols(certificate), baseUri))
.withTranslations(new TranslationLoader(translationsPattern, languages))
.withAttachment(
new AttachmentManager(certificateJson,
Expand Down
Loading
Loading