Skip to content
You are reading next, which describes the unreleased compiler. Khora is unstable before v1: syntax, standard-library APIs and behavior may change. The current release is documented under v0.4.

std::net::tls

TLS, over the sockets in std::net::socket.

Bound, not written. the ecosystem design note puts TLS in the short list of things Khora does not implement — “correctness is a specialist matter and a bug is a breach” — so this is rustls, reached through the runtime that every Khora executable already links. Nothing here is cryptography; it is a handshake, two buffers and a lifetime.

No new type crossed the compiler for this. A configuration and a connection are opaque machine addresses, the way an open file is in std::fs, and their lifetimes are tied to a scope with acquire. The code generator did not have to learn a thing.

What it does: both ends. A server takes a certificate chain and a key in PEM and secures accepted sockets. A client trusts the machine’s own root certificates and connects by name, verifying that the certificate says so. Reads and writes look like the plain ones on either side.

What it does not: client certificates, ALPN, session resumption, and choosing a cipher suite. Deliberate, all of them — rustls picks safe defaults, and a knob that lets somebody pick worse ones is not a feature.

Types: TlsError · TlsServer · TlsConnection · TlsClient · Refusal

Methods: Refusal

Functions: server · secure · secured · receive · receive_now · transmit · transmit_bytes · set_receive_timeout · set_deadline · expired · timed_out · shut · client · trusting · connect · connect_by · upgrade · upgrade_by · upgrade_saying

derive(Show, Eq)
pub type TlsError =
| BadCertificate
| BadKey
| Handshake
| Unreachable(host: String)
| TimedOut
| Denied(host: String);

Why a TLS server could not start, or a connection could not be secured.

Five cases, and only Unreachable carries anything. A rustls diagnostic is written for somebody debugging a handshake; what a Khora program can do about a failure is fix the certificate, fix the key, drop the client, or give up on the host – and only that last one needs to say which host.

${e} prints a case as TlsError::Unreachable(example.com), and == compares cases and what they carry.

| BadCertificate

The certificate chain was not readable PEM, or was empty.

| BadKey

The key was not readable PEM, or does not match the certificate.

| Handshake

A client failed the handshake. Ordinary: a port scan, a plain-HTTP request to an HTTPS port, or a client with no cipher in common.

| Unreachable(host: String)

A connection could not be made, or the server it reached did not present a certificate this client trusts for that name.

One case rather than three. “Could not resolve”, “refused” and “wrong name” are different to somebody debugging and identical to a program: it does not have the connection, and what it does next is retry or give up. Telling them apart wants an error that carries text, which is a separate piece of work.

| TimedOut

The deadline given to connect_by passed before the session was up.

Separate from Unreachable because it is the one a caller acts on differently: a host that refused may refuse again, while a call that ran out of time mostly wants a longer budget.

| Denied(host: String)

[permissions] network does not grant host on this port, so nothing was looked up or dialed.

Its own case rather than Unreachable, for the reason IoError::Denied is: Unreachable sends the reader to DNS or a firewall, and this one is a line in khora.toml. host is name:port, which is what a grant is written against.

pub type TlsServer = { settings: Ptr };

A configured server, ready to secure accepted sockets.

Holds a machine address rather than being one, so that a signature can say what it wants. The address is rustls’s and Khora never looks inside it.

The field is not called handle, and neither is TlsConnection’s: two records with one field of one type are the same shape, and a literal for either fits both. The checker says so rather than guessing, which is the right answer and a good reason to name a field after what it holds.

pub type TlsConnection = { session: Ptr };

One secured connection, and the socket underneath it.

pub type TlsClient = { trust: Ptr };

What a client trusts.

The field is trust and the server’s is settings, which is not only for reading: two records of one Ptr are the same shape, so a bare literal fits both and the checker asks which was meant. Distinct names answer it without an annotation — and an annotation on the let would not have, because a type hint does not currently reach inside the branches of an if.

pub type Refusal =
| Failed
| RanOut
| Untrusted
| WrongName;

Which of the ways upgrade_saying can fail it was.

For the message a person reads, which is where the cases differ: an authority to trust, a name to connect by, a budget to raise. A program decides the same thing for all of them, which is why TlsError does not split Unreachable.

| Failed

The peer did not complete a TLS handshake, or the fiber was canceled.

| RanOut

The deadline passed first.

| Untrusted

The certificate does not chain to any root the client trusts.

| WrongName

The certificate is not for the host name given.

impl Refusal
pub fn of(why: Array<Int>) -> Refusal

The refusal why, as upgrade_saying filled it, says.

pub fn server(certificate: String, key: String) -> TlsServer with { scope: Scope } raises TlsError

A server from a certificate chain and a private key, both PEM.

Released when the enclosing scope ends, like an open file: the configuration is registered with acquire, so it goes however the scope goes, including through a raise. A server usually lives as long as the program, which means the scope to open it in is usually the root one.

PEM rather than DER because that is the shape a certificate arrives in — from a file, a secret store, or an ACME client — and converting is work every caller would repeat.

import std::core::{Scope, scoped};
import std::fs::{FsRead, read_text};
import std::net::tls::{server};
fn settings() -> TlsServer
with { scope: Scope, reads: FsRead }
raises TlsError + IoError
{
server(read_text("cert.pem")!, read_text("key.pem")!)!
}

scope is in the row because the settings own a handle the runtime has to close: acquire registers that with the enclosing scoped, so it goes back on every way out including a cancellation.

pub fn secure(server: TlsServer, socket: Int) -> TlsConnection raises TlsError

Completes a handshake over an accepted socket.

Takes the socket. shut below closes it, and the caller must not close it as well: a second close lands on a descriptor the operating system is free to have reissued, which shows up much later as one connection reading another’s bytes. This is why there is no TlsConnection::socket.

A failed handshake has already closed the socket, so a caller that raises and moves on has leaked nothing.

pub fn secured(server: TlsServer, socket: Int) -> Option<TlsConnection>

secure, answering None for a failed handshake instead of raising.

For a caller that registers the session’s close itself. The socket is the session’s from the moment this is called, so the caller has to stop treating it as its own before the call and start holding the session the moment it returns, with nothing between that can stop. secure cannot give it that: the ! its raise needs is a cancellation check, and a fiber canceled there has the socket in neither hand. This has no check but the one the handshake makes when a cancel cuts it short, and that one answers with no session and the socket already closed.

pub fn receive(connection: TlsConnection, into: Array<U8>) -> Int

Plaintext bytes into into: how many, 0 when the peer has closed, or -1.

The same three answers receive gives on a plain socket, so a reader that already handles a socket handles this.

pub fn receive_now(connection: TlsConnection, into: Array<U8>) -> Int

Plaintext that has already arrived, into into, without waiting: how many bytes, 0 when the peer has closed, -1 when nothing has arrived yet, or -2 when the read failed. std::net::socket::receive_now, for a session.

For a check that must not wait, such as a pool asking whether an idle connection is still open. Records the peer sends that carry no plaintext – the session tickets a TLS 1.3 server sends after the handshake – are taken in here and answer -1, so a quiet session reads as quiet.

pub fn transmit(connection: TlsConnection, text: String) -> Int

Sends text, all of it, or -1.

All or nothing, unlike socket::transmit, which answers how many bytes went: a partial write of an encrypted record is not something a caller can resume, so the runtime finishes it or fails.

pub fn transmit_bytes(connection: TlsConnection, bytes: Array<U8>) -> Int

Sends bytes, all of them, or -1: transmit for a protocol framed in bytes rather than text, as std::net::socket::transmit_bytes is.

pub fn set_receive_timeout(connection: TlsConnection, millis: Int) -> Bool

How long a read on this connection may wait before it gives up.

The https half of set_receive_timeout. The plain path sets a deadline on the socket; a TLS session owns its socket rather than handing it back, so until this existed a secured connection had no deadline at all and a peer that accepted and then said nothing held a fiber until the process ended. That is the shape of a slowloris, and it worked over https and not over http.

It is set on the socket underneath, where the reactor’s timer lives; TLS never learns about it. A read that runs out fails, which every caller here already treats as a connection to give up on.

pub fn set_deadline(connection: TlsConnection, deadline: Int) -> Bool

Holds every later read and write on this connection to clock.monotonic_millis() reaching deadline. Negative clears it.

std::net::socket::set_deadline, for a session: one bound for a whole exchange, beside set_receive_timeout’s bound on each read.

pub fn expired(connection: TlsConnection) -> Bool

Whether the deadline from set_deadline is what ended a read or write on this connection: std::net::socket::expired, for a session.

pub fn timed_out(connection: TlsConnection) -> Bool

Whether a limit is what ended a read or write on this connection, the per-read limit from set_receive_timeout or the deadline from set_deadline: std::net::socket::timed_out, for a session.

pub fn shut(connection: TlsConnection) ->()

Says goodbye properly, then closes the socket.

The close_notify is not politeness. Without it a peer cannot tell a closed connection from a cut one, which is the truncation attack TLS closes by having an end-of-stream that is signed.

pub fn client() -> TlsClient with { scope: Scope } raises TlsError

A client trusting the certificates this machine trusts.

The operating system’s store, not a list compiled into Khora. A program should trust what its machine trusts: a corporate CA is the ordinary case rather than an exotic one, and a bundled root list is a snapshot that goes stale between releases without telling anybody.

Released when the enclosing scope ends, like a server.

import std::core::{Scope};
import std::net::tls::{client, connect, transmit};
fn ask(host: String) -> Int with { scope: Scope } raises TlsError {
let caller = client()!;
let session = connect(caller, host, 443)!;
transmit(session, "GET / HTTP/1.1\r\nHost: " + host + "\r\n\r\n")
}

Verifies against the machine’s own trust store, which is what a client talking to the public internet wants. trusting is the one for a private certificate authority.

pub fn trusting(extra: String) -> TlsClient with { scope: Scope } raises TlsError

The same, trusting one more certificate chain as a root.

For an internal CA the machine has not been told about, and for a test against a self-signed server. There is deliberately no way to turn verification off: every library offers one, and it is how verification comes to be off in production. Naming the certificate you mean to trust is the same amount of typing and leaves a reviewer something to look at.

import std::fs::{FsRead, read_text};
import std::net::tls::{trusting};
fn internal() -> TlsClient
with { scope: Scope, reads: FsRead }
raises TlsError + IoError
{
trusting(read_text("internal-ca.pem")!)!
}

In addition to the machine’s trust store, not instead of it. A client that had to choose would make talking to an internal service and talking to the public internet mutually exclusive.

pub fn connect(client: TlsClient, host: String, port: Int) -> TlsConnection raises TlsError

Connects to host on port and completes a handshake.

The name matters twice: it is what gets resolved, and it is what the certificate has to be for. Connecting to an address and hoping is the thing certificate verification exists to prevent, so there is no overload that takes one.

The socket is made here rather than passed in, because resolving a name needs getaddrinfo and a struct addrinfo cannot cross the C ABI. The runtime already has a resolver worth using.

A cancellation point, from the lookup to the end of the handshake, as std::net::socket::connect_to is.

pub fn connect_by(client: TlsClient, host: String, port: Int, deadline: Int) -> TlsConnection raises TlsError

connect, giving up once clock.monotonic_millis() reaches deadline. Negative means none.

The deadline covers the lookup, the TCP connect and the handshake, and expiring is TlsError::TimedOut: only when the deadline was what ended it, so a refusal that arrives in its last millisecond is still Unreachable. The session that comes back carries no deadline; set_deadline puts one on it.

[permissions] network is checked first, against host:port, as std::net::socket::connect_to checks it: a host it does not grant is TlsError::Denied, and is neither looked up nor dialed.

pub fn upgrade(client: TlsClient, socket: Int, host: String) -> TlsConnection raises TlsError

Completes a client handshake over socket, a connection already open, verifying that the certificate is for host.

For a protocol that agrees to TLS in the clear first: PostgreSQL’s SSLRequest, SMTP’s and IMAP’s STARTTLS. The plain exchange happens on the socket, and this secures the same socket where it left off. Trust and verification are connect’s: the client’s roots, and a certificate that must name host. host is not resolved; it is only what the certificate has to say.

Who closes the socket. Once this returns a session, the session owns the socket: shut closes it, and the caller must not. When it raises, the socket is still the caller’s, open, with whatever deadline the caller had put on it, so a caller that arranged to close it closes it exactly once. A canceled caller gets no session either, and keeps the socket.

A cancellation point, for the whole of the handshake. Raises Unreachable(host) when the certificate does not verify or the peer does not complete a handshake.

pub fn upgrade_by(client: TlsClient, socket: Int, host: String, deadline: Int) -> TlsConnection raises TlsError

upgrade, giving up once clock.monotonic_millis() reaches deadline. Negative means none.

Expiring is TlsError::TimedOut, and only when the deadline is what ended the handshake, as for connect_by. The session that comes back carries no deadline; set_deadline puts one on it.

pub fn upgrade_saying(client: TlsClient, socket: Int, host: String, deadline: Int, why: Array<Int>) -> Option<TlsConnection>

upgrade_by, answering None rather than raising, with the cause left in why’s one element for Refusal::of.

The same handshake and the same rule about who closes the socket. A cancellation point for the whole of the handshake.

Khora 0.4.0built fromee766ae43388on 2026-11-26 22:56ZVersioningSecurityContributingReleasesSource