Types, patterns and valuesSlide 27 of 86
27SecretTypes, patterns and values

Secrets

A Secret<T> holds a value that must not leak — a password, a key, a token, or a record of them — and the compiler enforces it:

  • echo, panic, interpolation and writing JSON all refuse a Secret, and anything that holds one: a field, an element, a Result. reveal(secret) is the only way back to the T.
  • T is plain data: text, numbers, vectors, maps, results and declared types made of them. A Secret of a function, an address, a library handle or another Secret is a compile error, and so is a bare Secret that does not say what it holds. The library's secrets are text, so they are Secret<Str>.
  • The value is kept as bytes in memory the operating system is told never to swap to disk, and is cleared once nothing holds it.
  • == compares two in constant time, so the time it takes says nothing about where they differ. A map is kept in key order, so two holding the same pairs are equal. A Secret has no order.

Locked memory is finite, so hide(value) answers a Result<Secret<T>, SecretError>: SecretError.LimitExceeded when the limit is used up, and SecretError.Unsupported where the platform cannot lock memory at all, each with a message. bypass(value) makes a Secret<T> that cannot fail, in ordinary memory that may be swapped out — for a value that was never really secret on the way in, like a literal, which the executable holds anyway. Two library calls have the same kind of twin: hive.term.readSecretBypass() and hive.crypto.decryptBypass(ciphertext, password) are readSecret and decrypt into ordinary memory, so neither stops at the limit.

A program that declares its own Secret still reaches the builtin as hive.Secret<T>, and its error as hive.SecretError.

Kept, compared, never shown
type Login {
	user:     Str
	password: Secret<Str>
}

proc main(): void {
	typed := hide("hunter2")
	if typed is Result.Error(why) {
		echo why
	} else if typed is Result.Ok(password) {
		echo reveal(password)                // hunter2
		echo password == bypass("hunter2")   // true
		echo Login("ada", password).user     // ada
		// echo password                      — a compile error
		// echo Login("ada", password)        — and so is this
	}
}
Any plain value
type Card {
	number: Str
	pin:    Int
}

proc main(): void {
	card := bypass(Card("4111 1111 1111 1111", 1234))
	echo reveal(card).pin                 // 1234
	codes := bypass([93, 17, 42])
	echo len(reveal(codes))               // 3
	echo codes == bypass([93, 17, 42])    // true
	// Secret<Str> s = codes              — a compile error: it holds Int[3]
}