Kotlin/JVM bindings for the SLIM data plane, generated using UniFFI.
This package provides Kotlin bindings for SLIM, enabling secure messaging with:
- Point-to-point messaging: Direct communication between two parties
- Group messaging: Multi-party communication with MLS encryption support
- Identity management: Support for shared secrets, JWT, and SPIRE authentication
- Coroutine support: Idiomatic async/await using Kotlin coroutines
- slimrpc support: Protocol Buffers RPC over SLIM - see SLIMRPC.md for details
- JDK 17 or higher
- Gradle 8.5+ (wrapper included)
- Rust toolchain (for building native library)
- uniffi-bindgen-cli CLI tool (installed automatically via Taskfile)
- Task (for running build tasks) - Install from taskfile.dev
kotlin/
├── Taskfile.yaml # Build automation tasks
├── uniffi.toml # UniFFI configuration (package name)
├── patch-bindings.py # Post-generation patches
├── build.gradle.kts # Gradle build configuration
├── settings.gradle.kts # Gradle settings
├── gradle.properties # Build properties
├── detekt.yml # Detekt linter rules (used by `task lint`)
├── examples/
│ ├── kotlin/
│ │ ├── common/ # Shared utilities
│ │ │ ├── Config.kt # Configuration data classes
│ │ │ ├── Common.kt # Helper functions
│ │ │ └── Colors.kt # Terminal formatting
│ │ ├── PointToPoint.kt # P2P messaging example
│ │ ├── Group.kt # Group messaging example
│ │ └── Server.kt # SLIM server example
│ └── slimrpc/simple/ # slimrpc example (see SLIMRPC.md)
└── generated/ # UniFFI-generated code (gitignored)
└── io/agntcy/slim/bindings/
└── slim_bindings.kt
The first step is to build the Rust library and generate Kotlin bindings:
task generateThis will:
- Build the Rust
slim_bindingslibrary - Run
uniffi-bindgen-cliwithuniffi.tomlconfig to generate Kotlin code in theio.agntcy.slim.bindingspackage - Apply compatibility patches (exception message parameters, wait() method conflicts)
- Copy the native library to
generated/jniLibs/
Build the Kotlin examples:
task buildStart a SLIM server:
task examples:serverOr with custom address:
task examples:server CLI_ARGS='--args="--slim 127.0.0.1:8080"'Run Alice (receiver) in one terminal:
task examples:p2p:aliceRun Bob (sender) in another terminal:
task examples:p2p:no-mls:bobWith MLS encryption:
task examples:p2p:mls:bobRun the moderator in one terminal:
task examples:group:moderatorRun clients in separate terminals:
task examples:group:client-1
task examples:group:client-2Sender Mode (sends messages to a specific peer):
import io.agntcy.slim.examples.common.*
import io.agntcy.slim.bindings.*
import kotlinx.coroutines.*
suspend fun main() = coroutineScope {
val config = PointToPointConfig(
local = "org/alice/app",
remote = "org/bob/app",
message = "Hello, Bob!",
iterations = 5,
enableMls = true
)
val (app, connId) = createLocalApp(config)
val remoteName = Name.fromString(config.remote!!)
app.setRouteAsync(remoteName, connId)
val sessionConfig = SessionConfig(
sessionType = SessionType.POINT_TO_POINT,
maxRetries = 5u,
interval = Duration.ofSeconds(5),
metadata = emptyMap(),
mlsSettings = if (config.enableMls) MlsSettings(100u, null) else null
)
val sessionContext = app.createSessionAsync(sessionConfig, remoteName)
sessionContext.completion.waitAsync()
val session = sessionContext.session
repeat(config.iterations) {
session.publishAsync(config.message!!.toByteArray(), null, null)
val reply = session.getMessageAsync(Duration.ofSeconds(30))
println("Received: ${String(reply.payload)}")
}
}Receiver Mode (listens for incoming sessions):
suspend fun main() = coroutineScope {
val config = PointToPointConfig(local = "org/bob/app")
val (app, _) = createLocalApp(config)
while (true) {
val session = app.listenForSessionAsync(null)
launch {
while (true) {
val msg = session.getMessageAsync(Duration.ofSeconds(30))
println("Received: ${String(msg.payload)}")
session.publishAsync("Echo: ${String(msg.payload)}".toByteArray(), null, null)
}
}
}
}Moderator (creates group and invites participants):
suspend fun main() = coroutineScope {
val config = GroupConfig(
local = "org/moderator/app",
remote = "org/default/chat-room",
invites = listOf("org/alice/app", "org/bob/app"),
enableMls = true
)
val (app, connId) = createLocalApp(config)
val channelName = Name.fromString(config.remote!!)
val sessionConfig = SessionConfig(
sessionType = SessionType.GROUP,
maxRetries = 5u,
interval = Duration.ofSeconds(5),
metadata = emptyMap(),
mlsSettings = if (config.enableMls) MlsSettings(100u, null) else null
)
val sessionContext = app.createSession(sessionConfig, channelName)
sessionContext.completion.waitAsync()
val session = sessionContext.session
config.invites!!.forEach { invite ->
val inviteName = Name.fromString(invite)
app.setRouteAsync(inviteName, connId)
session.inviteAsync(inviteName).waitAsync()
}
// Now send/receive messages
session.publishAsync("Hello, everyone!".toByteArray(), null, null)
}Participant (waits for invitation):
suspend fun main() = coroutineScope {
val config = GroupConfig(local = "org/alice/app")
val (app, _) = createLocalApp(config)
val session = app.listenForSessionAsync(null)
launch {
while (true) {
val msg = session.getMessageAsync(Duration.ofSeconds(30))
println("${msg.context.sourceName} > ${String(msg.payload)}")
}
}
// Interactive message sending
while (true) {
val input = readlnOrNull() ?: break
session.publishAsync(input.toByteArray(), null, null)
}
}suspend fun main() {
val service = setupService(enableOpentelemetry = false)
val serverConfig = newInsecureServerConfig("127.0.0.1:46357")
service.runServerAsync(serverConfig)
println("Server started on 127.0.0.1:46357")
awaitCancellation()
}All examples support the following common arguments:
--local <id>- Local ID (org/namespace/app) - REQUIRED--remote <id>- Remote ID (org/namespace/app-or-channel)--slim <url>- SLIM server endpoint (default:http://127.0.0.1:46357)--shared-secret <secret>- Shared secret for authentication--enable-mls- Enable MLS encryption for sessions--enable-opentelemetry- Enable OpenTelemetry tracing
Point-to-Point specific:
--message <text>- Message to send (activates sender mode)--iterations <n>- Number of request/reply cycles (default: 10)
Group specific:
--invites <id>- Invite participant (can be specified multiple times)
Server specific:
--slim, -s <address>- Server address (host:port)
Some defaults can also be provided via environment variables with the SLIM_ prefix
(--local and --enable-mls have no environment equivalent):
SLIM_ENDPOINT- Server endpointSLIM_SHARED_SECRET- Shared secretSLIM_ENABLE_OPENTELEMETRY- Enable OpenTelemetry (true/false)SLIM_JWT,SLIM_SPIRE_TRUST_BUNDLE,SLIM_AUDIENCE- JWT identity settingsSLIM_SPIRE_SOCKET_PATH,SLIM_SPIRE_TARGET_SPIFFE_ID,SLIM_SPIRE_JWT_AUDIENCE- SPIRE identity settingsSLIM_CLIENT_CONFIG- Path to a JSON file holding the full gRPC client config (see Transport Authentication); overridesSLIM_ENDPOINT
These modes set the application identity — who this app claims to be inside SLIM. They are independent of transport authentication, which secures the gRPC connection to the SLIM node.
The bindings support three authentication modes:
-
Shared Secret (default, for development):
val config = BaseConfig( local = "org/alice/app", sharedSecret = "my-shared-secret-at-least-32-bytes-long" )
-
JWT with JWKS:
val config = BaseConfig( local = "org/alice/app", jwt = "/path/to/jwt.pem", spireTrustBundle = "/path/to/bundle.json", audience = listOf("slim-service") )
-
SPIRE (dynamic identity):
val config = BaseConfig( local = "org/alice/app", spireSocketPath = "/tmp/spire-agent/public/api.sock", spireTargetSpiffeId = "spiffe://example.org/alice", spireJwtAudience = listOf("slim-service") )
Separate from application identity, the gRPC connection to a SLIM node can carry its own
credentials via ClientConfig.auth (and ServerConfig.auth when hosting). Supported modes
are Basic, StaticJwt, Jwt, Spire, and Oidc.
OIDC from Kotlin, client side (client-credentials flow):
val clientConfig = newInsecureClientConfig("http://127.0.0.1:46357").apply {
auth = ClientAuthenticationConfig.Oidc(
OidcConfig(
issuerUrl = "https://auth.example.com",
clientId = "my-client",
clientSecret = "s3cr3t",
audience = null,
refreshToken = null,
refreshTokenFile = null,
accessTokenFile = null,
scope = "openid profile",
timeout = Duration.ofSeconds(30),
jwksTtl = null,
claimCacheTtl = null,
policy = null,
)
)
}
val connId = service.connectAsync(clientConfig)For the refresh-token flow set refreshToken (or refreshTokenFile, which is rewritten
in place as tokens rotate) instead of clientSecret.
Server side, verifying incoming JWTs against the issuer's JWKS endpoint, optionally restricting access by claim:
val serverConfig = newInsecureServerConfig("127.0.0.1:46357").apply {
auth = ServerAuthenticationConfig.Oidc(
OidcConfig(
issuerUrl = "https://auth.example.com",
clientId = null, clientSecret = null,
audience = "slim", // required for verification
refreshToken = null, refreshTokenFile = null, accessTokenFile = null,
scope = null,
timeout = null,
jwksTtl = Duration.ofHours(1),
claimCacheTtl = Duration.ofMinutes(1),
policy = OidcPolicyConfig.Cel(""""admin" in claims.groups"""),
)
)
}policy accepts OidcPolicyConfig.Cel(expression), OidcPolicyConfig.Rego(text) (which must
define package slim.auth with default allow = false), or OidcPolicyConfig.RegoFile(path).
Client-only fields (scope, timeout) and server-only fields (jwksTtl, claimCacheTtl,
policy) are ignored by the other side.
From a config file — the examples read SLIM_CLIENT_CONFIG (or --slim-config <path>),
which covers every auth mode plus TLS material and backoff without any code change:
{
"endpoint": "http://127.0.0.1:46357",
"tls": { "insecure": true },
"auth": {
"type": "oidc",
"issuer_url": "https://auth.example.com",
"client_id": "my-client",
"client_secret": "s3cr3t",
"audience": "slim",
"policy": { "cel": "\"admin\" in claims.groups" }
}
}The schema matches crates/config/src/schema/client-config.schema.json in the
slim repo. To load one yourself, call newConfigFromJson(json).
The project uses Task for build automation:
task generate- Generate Kotlin bindings from Rust librarytask build- Build Kotlin code and create JARstask clean- Remove build artifacts and generated codetask examples:server- Run the server exampletask examples:p2p:alice- Run Alice (P2P receiver)task examples:p2p:no-mls:bob- Run Bob (P2P sender, without encryption)task examples:p2p:mls:bob- Run Bob with MLS encryptiontask examples:group:moderator- Run group moderatortask examples:group:client-1- Run group participant 1task examples:group:client-2- Run group participant 2
- JNA 5.14.0+ - Native library loading via Java Native Access
- kotlinx-coroutines-core 1.8.1+ - Coroutine support for async operations
- Clikt 4.2.2 - Command-line interface parsing
The Kotlin bindings are generated from the Rust slim_bindings crate using UniFFI:
- Rust code uses
#[uniffi::export]macros to mark public APIs uniffi-bindgen-clireads the compiled library and generates Kotlin code- Generated code uses JNA to call native functions
- Native library is packaged in
generated/jniLibs/for runtime loading
Rust async functions are exposed as Kotlin suspend functions:
// Rust
#[uniffi::export]
pub async fn connect_async(&self, config: ClientConfig) -> Result<u64, SlimError>// Generated Kotlin
suspend fun connectAsync(config: ClientConfig): ULongRust Result<T, E> types are converted to Kotlin exceptions:
// Rust
pub enum SlimError {
ServiceError { message: String },
SessionError { message: String },
SendError { message: String },
Timeout,
// ... ReceiveError, AuthError, ConfigError, RpcError, InvalidArgument, InternalError
}// Kotlin
try {
session.publishAsync(data, null, null)
} catch (e: SlimException.SessionException) {
println("Session error: ${e.message}")
} catch (e: SlimException.Timeout) {
println("Timed out")
}examples/kotlin/common/- Shared utilities and configurationexamples/kotlin/*.kt- Example applicationsexamples/slimrpc/simple/- slimrpc examplegenerated/- UniFFI-generated Kotlin code (not in git)build.gradle.kts- Gradle build configurationdetekt.yml— Static analysis rules (task lintin this directory)Taskfile.yaml- Task automation
Apache 2.0 - See LICENSE for details
See CONTRIBUTING.md for contribution guidelines