lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

Smoke.kt (12022B)


      1 import kotlinx.coroutines.*
      2 import uniffi.radroots_ffi.*
      3 import uniffi.radroots_ffi.Exception as RadrootsException
      4 import uniffi.radroots_native_binding_fixture.*
      5 
      6 private fun request(host: Host, id: String, seconds: Long = 120) = CommandRequest(
      7     id.repeat(32), (host.unixSeconds().toLong() + seconds).toString(), "Kotlin actual calls")
      8 
      9 private fun listing(host: Host, id: String): ListingInput {
     10     val option = "02".repeat(32)
     11     val json = """{"id":"${id.repeat(16)}","title":"  Kotlin carrots 🥕  ","summary":"Quote required","description_markdown":"Exact native terms","published_at":"${host.unixSeconds()}","profile":{"profile":"radroots.listing","version":1,"state":"active","product":{"name":"Carrots","description":"Fresh carrots","producer":null,"origin_summary":null},"default_option":"$option","options":[{"id":"$option","label":"Bunch","unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}},"increment":"1","minimum":"1","price":{"type":"quote_required"},"supply":{"type":"available","amount":"10"},"lead_seconds":"0"}],"fulfillment":{"modes":["pickup"],"area":"Example","lead_seconds":"0"},"authority":null,"media":[]}}"""
     12     return ListingInput.parse(json.toByteArray(Charsets.UTF_8))
     13 }
     14 
     15 private suspend fun close(host: Host, session: Session) {
     16     val callbacks = host.measurements().closedCallbacks.toLong()
     17     session.client.close()
     18     check(session.client.state() == SessionState.CLOSED)
     19     check(host.measurements().closedCallbacks.toLong() == callbacks + 1)
     20     host.cleanup()
     21     // Only after actual resource closure release the language's references.
     22     session.workspace.destroy()
     23     session.client.destroy()
     24     host.destroy()
     25 }
     26 
     27 private suspend fun publicFlow() {
     28     val host = Host.open(true, false, false)
     29     val first = host.session()
     30     check(first.client.state() == SessionState.READY)
     31     first.client.start(StartMode.ONLINE)
     32     host.setAccepting(false)
     33     val context = request(host, "31", 10)
     34     val input = listing(host, "31")
     35     val receipt = first.client.publishListing(first.workspace, context, input)
     36     check(receipt.kind == OperationKind.LISTING && receipt.admission == Admission.CONFIRMED)
     37     check(receipt.businessInstallation == BusinessInstallation.INSTALLED && receipt.issuance == Issuance.OBTAINED)
     38     val value = (receipt.businessResult as Value.Listing).listing
     39     check(value.title() == "  Kotlin carrots 🥕  ")
     40     check(receipt.messageId == null && receipt.artifacts.all { it.recipient == null })
     41     check(receipt.deliveryObservations.single().outcome == TargetObservation.REJECTED)
     42     val before = host.measurements()
     43     check(before.signingCalls == "1" && before.legacySigningCalls == "0" && before.relayReads == "0")
     44     check(before.originalSignedEvents.single().contains(value.revision()))
     45     val replay = first.client.publishListing(first.workspace, context, input)
     46     check(replay.operationCheckpoint == receipt.operationCheckpoint)
     47     check(host.measurements().originalSignedEvents == before.originalSignedEvents)
     48     first.client.close()
     49     val next = host.reopen()
     50     next.client.start(StartMode.ONLINE)
     51     val query = next.client.operation(next.workspace, receipt.operationId, receipt.commandDigest)
     52     check(query?.operationCheckpoint == receipt.operationCheckpoint)
     53     check(host.measurements().originalSignedEvents == before.originalSignedEvents)
     54     while (host.unixSeconds().toLong() <= receipt.firstIssueNotAfter.toLong()) delay(100)
     55     host.setAccepting(true)
     56     val resumed = next.client.resume(next.workspace, receipt.operationId, receipt.commandDigest)
     57     check(resumed.firstIssueNotAfter == receipt.firstIssueNotAfter)
     58     check(resumed.deliveryAttempts.size == 2)
     59     check(resumed.deliveryAttempts.map { it.targetOrdinals.toList() }.toSet() == setOf(listOf(1.toByte()), listOf(2.toByte())))
     60     check(resumed.deliveryAttempts[0].originalBytesDigest == resumed.deliveryAttempts[1].originalBytesDigest)
     61     check(resumed.deliveryAttempts[0].publicationPolicyDigest == resumed.deliveryAttempts[1].publicationPolicyDigest)
     62     check(resumed.deliveryObservations.any { it.outcome == TargetObservation.ACCEPTED })
     63     val after = host.measurements()
     64     check(after.signingCalls == "1" && after.originalSignedEvents == List(2) { before.originalSignedEvents.single() })
     65     close(host, next)
     66 }
     67 
     68 private suspend fun privateFlowAndErrors() {
     69     val host = Host.open(false, false, false)
     70     val session = host.session()
     71     session.client.start(StartMode.ONLINE)
     72     val peer = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"
     73     val text = "\uFEFF  Cafe\u0301 / Café Kotlin inquiry 🥕\nExact text\u0000  "
     74     val input = InquiryInput("32".repeat(32), peer, null, text)
     75     val receipt = session.client.inquire(session.workspace, request(host, "32"), input)
     76     val message = (receipt.businessResult as Value.Chat).message
     77     check(receipt.kind == OperationKind.CHAT && message.text().toByteArray().contentEquals(text.toByteArray()) && message.peer() == peer)
     78     check(receipt.artifacts.size == 2 && receipt.artifacts.all { it.recipient != null })
     79     val before = host.measurements()
     80     check(before.signingCalls == "2" && before.relayReads != "0")
     81     try {
     82         InquiryInput("32".repeat(32), peer.uppercase(), null, "must not enter error details")
     83         error("uppercase key accepted")
     84     } catch (e: RadrootsException.InvalidInput) { check(e.field == "peer") }
     85     try {
     86         ListingInput.parse("{}".toByteArray())
     87         error("invalid listing accepted")
     88     } catch (e: RadrootsException.InvalidInput) { check(e.field == "listing_input") }
     89     try {
     90         ListingInput.parse("""{"profile":{"version":2}}""".toByteArray())
     91         error("unsupported profile accepted")
     92     } catch (e: RadrootsException.CommandInput) { check(e.kind == InputFailure.UNSUPPORTED_PROFILE) }
     93     try {
     94         ListingInput.parse(ByteArray(65_537) { 32 })
     95         error("oversize input accepted")
     96     } catch (e: RadrootsException.CommandInput) { check(e.kind == InputFailure.LIMIT_EXCEEDED) }
     97     val foreign = Host.open(false, false, false)
     98     val other = foreign.session()
     99     other.client.start(StartMode.ONLINE)
    100     val context = request(host, "33")
    101     try {
    102         session.client.inquire(other.workspace, context, input)
    103         error("foreign scope accepted")
    104     } catch (e: RadrootsException.Operation) {
    105         check(e.admission == Admission.NOT_ADMITTED && e.operationId == context.operationId)
    106     }
    107     check(host.measurements().signingCalls == before.signingCalls)
    108     check(foreign.measurements().signingCalls == "0")
    109     session.workspace.close()
    110     check(!session.workspace.uniffiIsDestroyed)
    111     try {
    112         session.client.inquire(session.workspace, request(host, "36"), input)
    113         error("closed attachment accepted")
    114     } catch (e: RadrootsException.Operation) { check(e.admission == Admission.NOT_ADMITTED) }
    115     check(host.measurements().signingCalls == before.signingCalls)
    116     close(foreign, other)
    117     close(host, session)
    118 }
    119 
    120 private suspend fun unknownFlow() {
    121     val host = Host.open(true, true, false)
    122     val session = host.session()
    123     session.client.start(StartMode.ONLINE)
    124     val receipt = session.client.publishListing(session.workspace, request(host, "34"), listing(host, "34"))
    125     check(receipt.issuance == Issuance.UNKNOWN && receipt.businessResult == null)
    126     session.client.close()
    127     host.setUnknownSigning(false)
    128     val next = host.reopen()
    129     next.client.start(StartMode.ONLINE)
    130     val resumed = next.client.resume(next.workspace, receipt.operationId, receipt.commandDigest)
    131     check(resumed.issuance == Issuance.UNKNOWN && resumed.businessResult == null)
    132     val measured = host.measurements()
    133     check(measured.signingCalls == "1" && measured.originalSignedEvents.isEmpty())
    134     close(host, next)
    135 }
    136 
    137 private suspend fun cancelledObservers() = coroutineScope {
    138     val host = Host.open(true, false, true)
    139     val session = host.session()
    140     session.client.start(StartMode.ONLINE)
    141     val context = request(host, "35")
    142     val input = listing(host, "35")
    143     val observer = async { session.client.publishListing(session.workspace, context, input) }
    144     host.waitUntilSignerPaused()
    145     observer.cancelAndJoin()
    146     val closing = async { session.client.close() }
    147     withTimeout(5_000) {
    148         while (session.client.state() != SessionState.CLOSING) delay(5)
    149     }
    150     closing.cancelAndJoin()
    151     host.releaseSigner()
    152     session.client.close()
    153     val next = host.reopen()
    154     next.client.start(StartMode.ONLINE)
    155     val recovered = next.client.resume(next.workspace, context.operationId, null)
    156     check(recovered.issuance == Issuance.OBTAINED && recovered.businessInstallation == BusinessInstallation.INSTALLED)
    157     check(host.measurements().signingCalls == "1")
    158     close(host, next)
    159 }
    160 
    161 
    162 private suspend fun rejectedSignerFlow() {
    163     data class Case(val mode: FixtureRejection, val reason: SignerRejectionReason, val covered: String?, val total: String?, val digest: String?)
    164     val cases = listOf(
    165         Case(FixtureRejection.MALFORMED, SignerRejectionReason.INVALID_ARTIFACT,
    166             "synthetic private rejection canary".toByteArray().size.toString(), "synthetic private rejection canary".toByteArray().size.toString(),
    167             "ba883ea08dff4c078672a055dd2be042d9debb5b22c66527e4499c068011879d"),
    168         Case(FixtureRejection.OVERSIZED, SignerRejectionReason.TOO_LARGE,
    169             "65536", "65537", "d2d5af5c0316f5c2b119635386239edc87abce035f851c3f6ee127e6c3cbf435"),
    170         Case(FixtureRejection.FOREIGN, SignerRejectionReason.BINDING_MISMATCH, null, null, null)
    171     )
    172     for (case in cases) {
    173         val host = Host.open(seller = true, unknownSigning = false, pauseAfterSigning = false)
    174         host.setRejectedSigning(case.mode)
    175         val session = host.session(); session.client.start(StartMode.ONLINE)
    176         val context = request(host, "18")
    177         var refused = false
    178         try {
    179             session.client.publishListing(session.workspace, context, listing(host, "18"))
    180         } catch (error: RadrootsException.Operation) {
    181             refused = true
    182             check(error.code == "signer_tampering" && error.retry == "manual_reconciliation")
    183             check(error.operationId == context.operationId && error.admission == Admission.CONFIRMED)
    184             val diagnostic = checkNotNull(error.signerRejection)
    185             check(diagnostic.reason == case.reason)
    186             val fingerprint = diagnostic.fingerprint
    187             if (fingerprint != null) {
    188                 check(fingerprint.coveredBytes == case.covered && fingerprint.totalBytes == case.total)
    189                 check(fingerprint.sha256.size == 32)
    190                 check(fingerprint.sha256.joinToString("") { "%02x".format(it.toInt() and 255) } == case.digest)
    191             } else {
    192                 check(case.digest == null)
    193             }
    194         }
    195         check(refused)
    196         val facts = session.client.operation(session.workspace, context.operationId, null)
    197         check(facts?.businessInstallation == BusinessInstallation.NOT_INSTALLED)
    198         val measured = host.measurements()
    199         check(measured.signingCalls == "1" && measured.legacySigningCalls == "0" && measured.originalSignedEvents.isEmpty())
    200         close(host, session)
    201     }
    202 }
    203 
    204 
    205 fun main(args: Array<String>) = runBlocking {
    206     if ("--plain-panic" in args) {
    207         var caught = false
    208         try { fixturePanicProbe() } catch (_: uniffi.radroots_native_binding_fixture.InternalException) { caught = true }
    209         check(caught)
    210         println("{\"language\":\"kotlin\",\"plain_panic_caught\":true}")
    211         return@runBlocking
    212     }
    213     var caught = false
    214     try { fixtureResultPanicProbe() } catch (_: uniffi.radroots_native_binding_fixture.InternalException) { caught = true }
    215     check(caught)
    216     publicFlow()
    217     privateFlowAndErrors()
    218     unknownFlow()
    219     cancelledObservers()
    220     rejectedSignerFlow()
    221     println("{\"language\":\"kotlin\",\"state\":\"passed\",\"actual_workflows\":5,\"result_panic_caught\":true}")
    222 }