|
| 1 | +/* |
| 2 | + * Janssen Project software is available under the Apache License (2004). See http://www.apache.org/licenses/ for full text. |
| 3 | + * |
| 4 | + * Copyright (c) 2026, Janssen Project |
| 5 | + */ |
| 6 | + |
| 7 | +package io.jans.fido2.service.audit.trace; |
| 8 | + |
| 9 | +import java.io.IOException; |
| 10 | +import java.nio.ByteBuffer; |
| 11 | +import java.nio.channels.FileChannel; |
| 12 | +import java.nio.file.Files; |
| 13 | +import java.nio.file.NoSuchFileException; |
| 14 | +import java.nio.file.Path; |
| 15 | +import java.nio.file.StandardCopyOption; |
| 16 | +import java.nio.file.StandardOpenOption; |
| 17 | +import java.util.UUID; |
| 18 | +import java.util.regex.Pattern; |
| 19 | + |
| 20 | +import com.fasterxml.jackson.databind.DeserializationFeature; |
| 21 | +import com.fasterxml.jackson.databind.JsonNode; |
| 22 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 23 | +import com.fasterxml.jackson.databind.node.ObjectNode; |
| 24 | +import com.fasterxml.jackson.databind.node.TextNode; |
| 25 | + |
| 26 | +/** |
| 27 | + * Per-node TRACE hash chain: producer_chain_id, sequence_number and prev_record_hash. |
| 28 | + * |
| 29 | + * <p>{@link #signAndAdvance(ObjectNode)} is the only way to move the chain. Under one lock it builds the |
| 30 | + * producer_chain member, signs the record, persists the next state, and only then returns the signed record. |
| 31 | + * Consequences: |
| 32 | + * <ul> |
| 33 | + * <li>A signer failure leaves the state unchanged.</li> |
| 34 | + * <li>A persistence failure releases no record, so the same sequence number is reissued after restart. A crash |
| 35 | + * after persistence but before the record is sent leaves a gap, never a duplicate.</li> |
| 36 | + * </ul> |
| 37 | + * |
| 38 | + * <p>The first record of a chain has sequence_number 1 and the all-zero prev_record_hash. Lock rejects any other |
| 39 | + * genesis position. Restart resumes the saved chain when its state is usable. Otherwise it starts a new chain with |
| 40 | + * a new producer_chain_id and, if the previous chain id for this node is still known, a chain_link on its genesis. |
| 41 | + * |
| 42 | + * <p>Sequence numbers never exceed {@code 2^53 - 1}, the JSON safe-integer limit that Lock accepts. When a chain is |
| 43 | + * exhausted, the next record starts a new chain linked to it. |
| 44 | + * |
| 45 | + * <p>Single owner: one instance must own a given state file for its lifetime. Two live instances on the same file |
| 46 | + * can each resume the same snapshot and sign the same sequence numbers for different records. The class does not |
| 47 | + * take a file lock; the server wiring (#15280) must create exactly one instance per state file. |
| 48 | + */ |
| 49 | +public final class TraceChainState { |
| 50 | + |
| 51 | + static final String ZERO_HASH = "sha256:" + "0".repeat(64); |
| 52 | + |
| 53 | + /** Largest sequence_number Lock accepts: 2^53 - 1. */ |
| 54 | + static final long MAX_SEQUENCE = (1L << 53) - 1; |
| 55 | + |
| 56 | + private static final String PRODUCER_CHAIN = "producer_chain"; |
| 57 | + private static final String PRODUCER_CHAIN_ID = "producer_chain_id"; |
| 58 | + private static final String SEQUENCE_NUMBER = "sequence_number"; |
| 59 | + private static final String PREV_RECORD_HASH = "prev_record_hash"; |
| 60 | + private static final String CHAIN_LINK = "chain_link"; |
| 61 | + private static final String PREV_PRODUCER_CHAIN_ID = "prev_producer_chain_id"; |
| 62 | + private static final String SIGNATURE = "signature"; |
| 63 | + private static final String NODE_ID = "node_id"; |
| 64 | + private static final String NEXT_SEQUENCE = "next_sequence"; |
| 65 | + private static final String CHAIN_LINK_PREVIOUS = "chain_link_previous"; |
| 66 | + |
| 67 | + private static final Pattern SHA256_PREFIXED = Pattern.compile("sha256:[0-9a-f]{64}"); |
| 68 | + private static final ObjectMapper MAPPER = new ObjectMapper(); |
| 69 | + /** Rejects concatenated snapshots: trailing content after the first JSON value is an error. */ |
| 70 | + private static final ObjectMapper STATE_READER = new ObjectMapper() |
| 71 | + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); |
| 72 | + |
| 73 | + /** Writes the state file. Replaceable in tests to simulate a failed or interrupted write. */ |
| 74 | + interface StateWriter { |
| 75 | + void write(Path target, byte[] bytes) throws IOException; |
| 76 | + } |
| 77 | + |
| 78 | + private final TraceSigner signer; |
| 79 | + private final Path stateFile; |
| 80 | + private final String nodeId; |
| 81 | + private final StateWriter writer; |
| 82 | + |
| 83 | + // Guarded by "this". |
| 84 | + private String chainId; |
| 85 | + private long nextSequence; |
| 86 | + private String prevRecordHash; |
| 87 | + private String chainLinkPrevious; |
| 88 | + |
| 89 | + /** |
| 90 | + * @param stateFile file that holds the chain state for this node |
| 91 | + * @param nodeId node identifier, for example MetricService.getNodeIdentifier() |
| 92 | + * @param signer Ed25519 TRACE signer |
| 93 | + */ |
| 94 | + public TraceChainState(Path stateFile, String nodeId, TraceSigner signer) { |
| 95 | + this(stateFile, nodeId, signer, TraceChainState::writeAtomically); |
| 96 | + } |
| 97 | + |
| 98 | + TraceChainState(Path stateFile, String nodeId, TraceSigner signer, StateWriter writer) { |
| 99 | + if (stateFile == null || nodeId == null || nodeId.isEmpty() || signer == null || writer == null) { |
| 100 | + throw new IllegalArgumentException("stateFile, nodeId, signer and writer are required"); |
| 101 | + } |
| 102 | + this.stateFile = stateFile; |
| 103 | + this.nodeId = nodeId; |
| 104 | + this.signer = signer; |
| 105 | + this.writer = writer; |
| 106 | + load(); |
| 107 | + } |
| 108 | + |
| 109 | + /** |
| 110 | + * Signs the record and advances the chain. Adds or replaces producer_chain (producer_chain_id, sequence_number, |
| 111 | + * prev_record_hash, and chain_link on a genesis record when known) and signature. The caller's producer_id and |
| 112 | + * producer_instance_id are kept. |
| 113 | + * |
| 114 | + * @param unsigned unsigned record; it is not modified |
| 115 | + * @return a signed copy of the record |
| 116 | + * @throws IllegalStateException if signing or persisting fails; the chain does not advance |
| 117 | + */ |
| 118 | + public synchronized ObjectNode signAndAdvance(ObjectNode unsigned) { |
| 119 | + if (nextSequence > MAX_SEQUENCE) { |
| 120 | + // Exhausted: the last record of the old chain was signed at MAX_SEQUENCE. Start a linked chain first. |
| 121 | + startChain(chainId); |
| 122 | + } |
| 123 | + ObjectNode signed = unsigned.deepCopy(); |
| 124 | + signed.remove(SIGNATURE); |
| 125 | + ObjectNode chain = chainOf(signed); |
| 126 | + chain.put(PRODUCER_CHAIN_ID, chainId); |
| 127 | + chain.put(SEQUENCE_NUMBER, nextSequence); |
| 128 | + chain.put(PREV_RECORD_HASH, prevRecordHash); |
| 129 | + if (nextSequence == 1 && chainLinkPrevious != null) { |
| 130 | + chain.putObject(CHAIN_LINK).put(PREV_PRODUCER_CHAIN_ID, chainLinkPrevious); |
| 131 | + } else { |
| 132 | + chain.remove(CHAIN_LINK); |
| 133 | + } |
| 134 | + |
| 135 | + signed.put(SIGNATURE, signer.sign(signed)); |
| 136 | + String digest = TraceHashes.sha256Prefixed(TraceCanonicalizer.canonicalBytes(signed)); |
| 137 | + |
| 138 | + // Persist first. Memory advances only after the file is written. |
| 139 | + persist(chainId, nextSequence + 1, digest, null); |
| 140 | + nextSequence++; |
| 141 | + prevRecordHash = digest; |
| 142 | + chainLinkPrevious = null; |
| 143 | + return signed; |
| 144 | + } |
| 145 | + |
| 146 | + /** @return the current producer_chain_id (for tests and diagnostics) */ |
| 147 | + public synchronized String getChainId() { |
| 148 | + return chainId; |
| 149 | + } |
| 150 | + |
| 151 | + /** @return the sequence number the next record will receive */ |
| 152 | + public synchronized long getNextSequence() { |
| 153 | + return nextSequence; |
| 154 | + } |
| 155 | + |
| 156 | + /** Returns the producer_chain object of the record, creating it when absent or not an object. */ |
| 157 | + private static ObjectNode chainOf(ObjectNode record) { |
| 158 | + JsonNode existing = record.get(PRODUCER_CHAIN); |
| 159 | + return existing instanceof ObjectNode ? (ObjectNode) existing : record.putObject(PRODUCER_CHAIN); |
| 160 | + } |
| 161 | + |
| 162 | + private void load() { |
| 163 | + JsonNode saved = readSaved(); |
| 164 | + boolean sameNode = saved != null && nodeId.equals(text(saved, NODE_ID)); |
| 165 | + if (sameNode && isUsable(saved)) { |
| 166 | + chainId = text(saved, PRODUCER_CHAIN_ID); |
| 167 | + nextSequence = saved.get(NEXT_SEQUENCE).asLong(); |
| 168 | + prevRecordHash = text(saved, PREV_RECORD_HASH); |
| 169 | + chainLinkPrevious = validChainIdOrNull(text(saved, CHAIN_LINK_PREVIOUS)); |
| 170 | + return; |
| 171 | + } |
| 172 | + // Unusable state: start a new chain. Link to the previous one only when it is still known for this node. |
| 173 | + startChain(sameNode ? validChainIdOrNull(text(saved, PRODUCER_CHAIN_ID)) : null); |
| 174 | + } |
| 175 | + |
| 176 | + /** Starts a new chain at sequence 1 and persists it before memory changes. */ |
| 177 | + private void startChain(String previous) { |
| 178 | + String newChainId = "chain-" + UUID.randomUUID(); |
| 179 | + persist(newChainId, 1, ZERO_HASH, previous); |
| 180 | + chainId = newChainId; |
| 181 | + nextSequence = 1; |
| 182 | + prevRecordHash = ZERO_HASH; |
| 183 | + chainLinkPrevious = previous; |
| 184 | + } |
| 185 | + |
| 186 | + /** |
| 187 | + * @return the saved state, or null when there is no file (absence) or its contents are malformed |
| 188 | + * @throws IllegalStateException when the file exists but cannot be read; the file is left untouched |
| 189 | + */ |
| 190 | + private JsonNode readSaved() { |
| 191 | + byte[] bytes; |
| 192 | + try { |
| 193 | + bytes = Files.readAllBytes(stateFile); |
| 194 | + } catch (NoSuchFileException e) { |
| 195 | + return null; |
| 196 | + } catch (IOException e) { |
| 197 | + throw new IllegalStateException("TRACE chain state could not be read; the file was left unchanged", e); |
| 198 | + } |
| 199 | + try { |
| 200 | + return STATE_READER.readTree(bytes); |
| 201 | + } catch (IOException | RuntimeException e) { |
| 202 | + return null; |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + private static boolean isUsable(JsonNode saved) { |
| 207 | + String id = text(saved, PRODUCER_CHAIN_ID); |
| 208 | + JsonNode next = saved.get(NEXT_SEQUENCE); |
| 209 | + String prev = text(saved, PREV_RECORD_HASH); |
| 210 | + if (validChainIdOrNull(id) == null || !isValidSequence(next)) { |
| 211 | + return false; |
| 212 | + } |
| 213 | + if (prev == null || !SHA256_PREFIXED.matcher(prev).matches()) { |
| 214 | + return false; |
| 215 | + } |
| 216 | + // The zero hash is the prev_record_hash of a genesis record, and only of one. |
| 217 | + return (next.asLong() == 1) == ZERO_HASH.equals(prev); |
| 218 | + } |
| 219 | + |
| 220 | + /** A sequence is an integral JSON number in [1, MAX_SEQUENCE]. */ |
| 221 | + private static boolean isValidSequence(JsonNode next) { |
| 222 | + return next != null && next.isIntegralNumber() && next.canConvertToLong() |
| 223 | + && next.asLong() >= 1 && next.asLong() <= MAX_SEQUENCE; |
| 224 | + } |
| 225 | + |
| 226 | + /** @return the id when it is non-empty and encodes as canonical JSON (no unpaired surrogate), otherwise null */ |
| 227 | + private static String validChainIdOrNull(String id) { |
| 228 | + if (id == null || id.isEmpty()) { |
| 229 | + return null; |
| 230 | + } |
| 231 | + try { |
| 232 | + TraceCanonicalizer.canonicalBytes(TextNode.valueOf(id)); |
| 233 | + return id; |
| 234 | + } catch (IllegalArgumentException e) { |
| 235 | + return null; |
| 236 | + } |
| 237 | + } |
| 238 | + |
| 239 | + private static String text(JsonNode node, String field) { |
| 240 | + JsonNode value = node.get(field); |
| 241 | + return value != null && value.isTextual() ? value.asText() : null; |
| 242 | + } |
| 243 | + |
| 244 | + private void persist(String chain, long next, String prev, String link) { |
| 245 | + ObjectNode state = MAPPER.createObjectNode(); |
| 246 | + state.put(NODE_ID, nodeId); |
| 247 | + state.put(PRODUCER_CHAIN_ID, chain); |
| 248 | + state.put(NEXT_SEQUENCE, next); |
| 249 | + state.put(PREV_RECORD_HASH, prev); |
| 250 | + if (link != null) { |
| 251 | + state.put(CHAIN_LINK_PREVIOUS, link); |
| 252 | + } |
| 253 | + try { |
| 254 | + writer.write(stateFile, MAPPER.writeValueAsBytes(state)); |
| 255 | + } catch (IOException e) { |
| 256 | + throw new IllegalStateException("TRACE chain state could not be persisted", e); |
| 257 | + } |
| 258 | + } |
| 259 | + |
| 260 | + static void writeAtomically(Path target, byte[] bytes) throws IOException { |
| 261 | + Path dir = target.toAbsolutePath().getParent(); |
| 262 | + Files.createDirectories(dir); |
| 263 | + Path tmp = Files.createTempFile(dir, target.getFileName().toString(), ".tmp"); |
| 264 | + try { |
| 265 | + try (FileChannel channel = FileChannel.open(tmp, StandardOpenOption.WRITE, |
| 266 | + StandardOpenOption.TRUNCATE_EXISTING)) { |
| 267 | + ByteBuffer buffer = ByteBuffer.wrap(bytes); |
| 268 | + while (buffer.hasRemaining()) { |
| 269 | + channel.write(buffer); |
| 270 | + } |
| 271 | + channel.force(true); |
| 272 | + } |
| 273 | + // No non-atomic fallback: if the move is not atomic, the error propagates and the target is untouched. |
| 274 | + Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); |
| 275 | + } catch (IOException | RuntimeException e) { |
| 276 | + try { |
| 277 | + Files.deleteIfExists(tmp); |
| 278 | + } catch (IOException cleanupFailure) { |
| 279 | + e.addSuppressed(cleanupFailure); |
| 280 | + } |
| 281 | + throw e; |
| 282 | + } |
| 283 | + syncDirectory(dir); |
| 284 | + } |
| 285 | + |
| 286 | + /** |
| 287 | + * Best-effort: forces the directory entry so the rename survives power loss. Opening a directory for force is not |
| 288 | + * supported on Windows, so there this step is skipped and the stronger guarantee does not hold. The rename has |
| 289 | + * already happened when this runs, so a failure here is not reported. |
| 290 | + */ |
| 291 | + private static void syncDirectory(Path dir) { |
| 292 | + try (FileChannel channel = FileChannel.open(dir, StandardOpenOption.READ)) { |
| 293 | + channel.force(true); |
| 294 | + } catch (IOException e) { |
| 295 | + // Not supported on this platform, or the directory could not be synced. Nothing to undo. |
| 296 | + } |
| 297 | + } |
| 298 | +} |
0 commit comments