// The Salary Box, as one Kotlin file. Starts with one secret (GATE_SECRET, base64url, 32 bytes). Stores nothing about // any salary or any request, and never knows who anyone is. Optional stats keep a running tally of demand, as two totals. Wire-compatible with ../../src/gate.ts. JDK only: javax.crypto and the // built-in HTTP server. Requests are form-encoded; responses are JSON; every failure is the same 400. // // POST /api/listing listingId, ceiling, basis -> {"locator":…,"verifyKey":…} // POST /api/bid locator, minimum -> {"ticket":…} // GET /api/key -> {"keyId":…} the public fingerprint of the secret // GET /api/stats -> {"listings":…,"bids":…}, or 404 unless STATS is "public" // Checking a ticket is not a call to the server: check() below is what an employer runs, with its verifyKey. // // Locator: "..", with "." // as associated data. import com.sun.net.httpserver.HttpServer import java.io.File import java.net.InetSocketAddress import java.nio.file.Files import java.nio.file.StandardCopyOption import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong import java.net.URLDecoder import java.security.MessageDigest import java.security.SecureRandom import java.util.Base64 import javax.crypto.Cipher import javax.crypto.Mac import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec private val rnd = SecureRandom() private val b64 = Base64.getUrlEncoder().withoutPadding() private val unb64 = Base64.getUrlDecoder() private fun hmac(key: ByteArray, data: ByteArray): ByteArray = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) }.doFinal(data) private fun bytes(n: Int) = ByteArray(n).also(rnd::nextBytes) private val ID = Regex("[A-Za-z0-9._-]{1,64}") private val BASIS = Regex("""[\p{L}\p{N} .,:/()$€£%+-]{1,80}""") private val AMOUNT = Regex("""\d{1,15}""") class Gate(private val secret: ByteArray) { init { require(secret.size == 32) } // Every purpose gets its own key, so a blob made for one step can't stand in for another. private fun sub(purpose: String) = hmac(secret, "salarybox v1 $purpose".toByteArray()) private fun verifyKeyFor(listingId: String) = hmac(sub("ticket"), listingId.toByteArray()) private fun aes(mode: Int, iv: ByteArray, aad: String) = Cipher.getInstance("AES/GCM/NoPadding").apply { init(mode, SecretKeySpec(sub("locator"), "AES"), GCMParameterSpec(128, iv)); updateAAD(aad.toByteArray()) } // A public fingerprint of the secret. It reveals nothing about the secret, and it changes if the secret does. val keyId: String = sub("key id").copyOf(8).joinToString("") { "%02x".format(it) } fun listing(listingId: String, ceiling: Long, basis: String): Pair { require(ID.matches(listingId) && BASIS.matches(basis) && ceiling > 0) val head = "$keyId.${b64.encodeToString(basis.toByteArray())}"; val iv = bytes(12) val ct = aes(Cipher.ENCRYPT_MODE, iv, head).doFinal("[\"$listingId\",$ceiling]".toByteArray()) return "$head.${b64.encodeToString(iv + ct)}" to b64.encodeToString(verifyKeyFor(listingId)) } fun bid(locator: String, minimum: Long): String { require(minimum > 0) val parts = locator.split('.'); require(parts.size == 3 && parts[0] == keyId) // a different key's locator is refused val raw = unb64.decode(parts[2]) val pt = String(aes(Cipher.DECRYPT_MODE, raw.copyOf(12), "${parts[0]}.${parts[1]}").doFinal(raw, 12, raw.size - 12)) // throws if forged val (listingId, ceiling) = Regex("""\["([A-Za-z0-9._-]+)",(\d+)]""").matchEntire(pt)!!.destructured val nonce = bytes(16) val tag = hmac(verifyKeyFor(listingId), nonce + byteArrayOf(if (minimum <= ceiling.toLong()) 1 else 0)).copyOf(16) return b64.encodeToString(nonce + tag) // the minimum is gone when this returns } } // For employers on the JVM. The server never calls this. Returns "below" (at or below the ceiling), "above" or "invalid". fun check(verifyKey: String, ticket: String): String { val raw = runCatching { unb64.decode(ticket) }.getOrNull()?.takeIf { it.size == 32 } ?: return "invalid" val k = runCatching { unb64.decode(verifyKey) }.getOrNull()?.takeIf { it.size == 32 } ?: return "invalid" val nonce = raw.copyOf(16); val tag = raw.copyOfRange(16, 32) fun tagFor(bit: Int) = hmac(k, nonce + byteArrayOf(bit.toByte())).copyOf(16) return when { MessageDigest.isEqual(tag, tagFor(1)) -> "below" MessageDigest.isEqual(tag, tagFor(0)) -> "above" else -> "invalid" } } // Stats are a running tally of demand, and they are on when STATS_FILE is set. They are published at // /api/stats only when STATS is also set to "public". The tally is two totals, one for // listings created and one for numbers compared, and it counts only requests that succeeded. That lets an operator // tell real use apart from abuse and noise, and plan for load. It records nothing about any individual request. // The file is read on start and written back every 60 s and at shutdown, so the totals survive restarts. // STATS_BASE ("l,b") is added to them, so that totals can be carried over from another host. class Stats(private val file: File, base: String?) { private val n = Array(2) { AtomicLong() } private val base = (base ?: "").split(',').map { it.trim().toLongOrNull() ?: 0L } + listOf(0L, 0L) @Volatile private var dirty = false init { if (file.exists()) file.readText().trim().split(',').take(2).forEachIndexed { i, s -> n[i].set(s.toLongOrNull() ?: 0) } Executors.newSingleThreadScheduledExecutor { Thread(it).apply { isDaemon = true } }.scheduleAtFixedRate(::save, 60, 60, TimeUnit.SECONDS) Runtime.getRuntime().addShutdownHook(Thread(::save)) } fun count(i: Int) { n[i].incrementAndGet(); dirty = true } @Synchronized fun save() { if (!dirty) return dirty = false val tmp = File("${file.path}.tmp").apply { writeText(n.joinToString(",") { it.get().toString() }) } Files.move(tmp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) } fun json() = """{"listings":${n[0].get() + base[0]},"bids":${n[1].get() + base[1]}}""" } fun main() { val gate = Gate(unb64.decode(System.getenv("GATE_SECRET") ?: error("set GATE_SECRET"))) val server = HttpServer.create(InetSocketAddress(System.getenv("PORT")?.toInt() ?: 8080), 0) fun route(path: String, fn: (Map) -> String) = server.createContext(path) { ex -> val (code, body) = runCatching { require(ex.requestMethod == "POST") val form = String(ex.requestBody.readAllBytes()).split('&').filter { '=' in it } .associate { URLDecoder.decode(it.substringBefore('='), Charsets.UTF_8) to URLDecoder.decode(it.substringAfter('='), Charsets.UTF_8) } 200 to fn(form) }.getOrElse { 400 to """{"error":"bad request"}""" } val out = body.toByteArray() ex.responseHeaders.add("Content-Type", "application/json") ex.responseHeaders.add("Cache-Control", "no-store") ex.sendResponseHeaders(code, out.size.toLong()); ex.responseBody.use { it.write(out) } } fun Map.amount(k: String) = getValue(k).also { require(AMOUNT.matches(it)) }.toLong() val stats = System.getenv("STATS_FILE")?.let { Stats(File(it), System.getenv("STATS_BASE")) } // Values are base64url or fixed words, so they can go into JSON without escaping. route("/api/listing") { val (l, v) = gate.listing(it.getValue("listingId"), it.amount("ceiling"), it.getValue("basis")); stats?.count(0); """{"locator":"$l","verifyKey":"$v"}""" } route("/api/bid") { val t = gate.bid(it.getValue("locator"), it.amount("minimum")); stats?.count(1); """{"ticket":"$t"}""" } fun get(path: String, fn: () -> Pair) = server.createContext(path) { ex -> val (code, body) = if (ex.requestMethod == "GET") fn() else 400 to """{"error":"bad request"}""" val out = body.toByteArray() ex.responseHeaders.add("Content-Type", "application/json"); ex.responseHeaders.add("Access-Control-Allow-Origin", "*") ex.sendResponseHeaders(code, out.size.toLong()); ex.responseBody.use { it.write(out) } } get("/api/key") { 200 to """{"keyId":"${gate.keyId}"}""" } get("/api/stats") { stats?.takeIf { System.getenv("STATS") == "public" }?.let { 200 to it.json() } ?: (404 to """{"error":"stats are not published"}""") } server.start() println("salary box on :${server.address.port}") }