kolo docsbeta

kolo-id

Identidad Ed25519 de nodo para Kolo, con firma, verificación, un archivo de clave privada, una frase de recuperación de 24 palabras y certificados de dispositivo.

En esta página

Un nodo de Kolo se conoce por su clave pública Ed25519. kolo-id crea y guarda ese par de claves, firma mensajes con Ed25519ctx de RFC 8032 y comprueba las firmas de otros peers. Las demás bibliotecas de Kolo toman sus identidades de aquí. No decide en qué claves confiar.

Una persona puede usar varios dispositivos. Una frase de recuperación de 24 palabras da una clave de persona (con BIP-39 y SLIP-0010), y cada dispositivo guarda su propia clave aleatoria y un certificado firmado por esa clave de persona, así que un dispositivo perdido se revoca sin perder la identidad.

Todos los pasos

Claves, firma y verificación

Solo se guarda la semilla. Una firma solo es válida con el contexto con el que se hizo.

  1. Generate toma 32 bytes aleatorios: la semilla.
  2. La semilla da la clave privada (64 bytes, en memoria) y la clave pública (32 bytes). La clave pública es la identidad, escrita como 64 caracteres hexadecimales.
  3. Sign usa Ed25519ctx: la clave privada firma el mensaje con un contexto de 1 a 255 bytes y da una firma de 64 bytes.
  4. Verify recibe la clave pública, el mismo contexto, el mensaje y la firma, y devuelve true.
  5. Devuelve false con otro contexto, con una clave pública que no tenga 32 bytes o con una clave de orden pequeño.
  6. Save escribe solo la semilla, en un archivo con modo 0600. Load la vuelve a leer y crea el mismo par de claves.

Instalación

go get github.com/ciranda-dev/kolo-id

Es Go puro, sin cgo. Sus dependencias son golang.org/x/sys, para el openat de libc en macOS, y kolo-codec, para la codificación de los certificados.

Inicio rápido

Crea una identidad, firma bajo un contexto y después guárdala y cárgala en un directorio temporal.

main.go
package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	koloid "github.com/ciranda-dev/kolo-id"
)

func main() {
	me, err := koloid.Generate()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("identity:", me)

	const ctx = "myapp/hello/v0"
	msg := []byte("hello kolo")
	sig, err := me.Sign(ctx, msg)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("valid:", koloid.Verify(me.PublicKey(), ctx, msg, sig))
	fmt.Println("other context:", koloid.Verify(me.PublicKey(), "myapp/other/v0", msg, sig))

	dir, err := os.MkdirTemp("", "koloid")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "id.key")
	if err := me.SaveNew(path); err != nil {
		log.Fatal(err)
	}
	loaded, err := koloid.Load(path)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("same key:", me.PublicKey().Equal(loaded.PublicKey()))
}

Imprime la clave pública, valid: true, other context: false y same key: true. Un nodo real llama primero a Load y, cuando el error coincide con os.ErrNotExist, llama una sola vez a Generate y SaveNew. Así conserva la misma clave pública entre reinicios.

Frase de recuperación y dispositivos

La clave de persona nunca vive en un dispositivo. Las 24 palabras dan la clave de persona, la clave de persona certifica el primer dispositivo como aprobador, y un aprobador añade dispositivos comunes sin las palabras. Quien verifica siempre indica la persona que espera. Este programa, examples/devices en el repositorio, recorre todo el flujo en un directorio temporal y nunca imprime la frase.

main.go
// Command devices shows a recovery phrase, a person key and two device certificates, all in a temporary directory.
// It never prints the phrase.
package main

import (
	"bytes"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"

	koloid "github.com/ciranda-dev/kolo-id"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

// run returns errors instead of exiting, so the deferred cleanup always runs.
func run() error {
	dir, err := os.MkdirTemp("", "koloid-devices")
	if err != nil {
		return err
	}
	defer os.RemoveAll(dir)

	// The person key comes from 24 words. An app shows them once and never stores them.
	phrase, err := koloid.GeneratePhrase()
	if err != nil {
		return err
	}
	person, err := phrase.Person()
	if err != nil {
		return err
	}
	words := phrase.Words()
	phrase.Clear()
	// Every device and verifier pins this key. It is never read out of a certificate that is being checked.
	personKey := person.PublicKey()
	fmt.Println("person:", person, "words:", len(words))

	// The first device gets an approver certificate. Each device has its own random key.
	laptop, err := koloid.Generate()
	if err != nil {
		return err
	}
	offer, err := person.OfferDeviceCert(laptop.PublicKey(), &koloid.IssueOptions{Serial: 1, Approver: true})
	if err != nil {
		return err
	}
	laptopCert, err := laptop.AcceptDeviceCert(offer, personKey)
	if err != nil {
		return err
	}
	if err := save(dir, "laptop", laptop, laptopCert); err != nil {
		return err
	}

	// The laptop adds a phone without the phrase: the offer travels to the phone, the acceptance proves the phone holds its key.
	laptop, laptopCert, err = load(dir, "laptop")
	if err != nil {
		return err
	}
	phone, err := koloid.Generate()
	if err != nil {
		return err
	}
	offer, err = laptop.OfferDeviceCert(phone.PublicKey(), &koloid.IssueOptions{Parent: laptopCert, Serial: 1})
	if err != nil {
		return err
	}
	// A real phone learns personKey from the linking exchange, not from the offer.
	phoneCert, err := phone.AcceptDeviceCert(offer, personKey)
	if err != nil {
		return err
	}
	if err := save(dir, "phone", phone, phoneCert); err != nil {
		return err
	}

	// A verifier states the person it expects. A message from the phone verifies through its certificate.
	const ctx = "kolo-id/example/v0"
	msg := []byte("hello from the phone")
	sig, err := phone.Sign(ctx, msg)
	if err != nil {
		return err
	}
	opts := &koloid.VerifyOptions{Person: personKey}
	fmt.Println("phone message:", koloid.VerifyDevice(phoneCert, opts, ctx, msg, sig))

	// The laptop revokes the phone's certificate. A verifier that holds the revocation refuses that certificate from now on; revocations are permanent, so keep them.
	rev, err := laptop.RevokeDevice(&koloid.RevokeOptions{Person: personKey, Device: phone.PublicKey(), SignerCert: laptopCert, Target: phoneCert})
	if err != nil {
		return err
	}
	opts.Revocations = []*koloid.Revocation{rev}
	err = koloid.VerifyDevice(phoneCert, opts, ctx, msg, sig)
	fmt.Println("after revoking:", errors.Is(err, koloid.ErrCertRevoked))

	// The same words give the same person key on any new install.
	again, err := koloid.ParseWords(words)
	if err != nil {
		return err
	}
	restored, err := again.Person()
	if err != nil {
		return err
	}
	fmt.Println("restored the same person:", bytes.Equal(restored.PublicKey(), personKey))
	return nil
}

func save(dir, name string, id *koloid.Identity, cert *koloid.DeviceCert) error {
	if err := id.Save(filepath.Join(dir, name+".key")); err != nil {
		return err
	}
	return koloid.SaveCert(filepath.Join(dir, name+".cert"), cert)
}

func load(dir, name string) (*koloid.Identity, *koloid.DeviceCert, error) {
	id, err := koloid.Load(filepath.Join(dir, name+".key"))
	if err != nil {
		return nil, nil, err
	}
	cert, err := koloid.LoadCert(filepath.Join(dir, name+".cert"))
	return id, cert, err
}

Imprime la clave de persona y words: 24, después phone message: <nil>, after revoking: true y restored the same person: true.

Frase de recuperación

  • GeneratePhrase crea 24 palabras de la lista inglesa de BIP-39 con crypto/rand: 256 bits de entropía y una suma de control de 8 bits. Muestra Words() una sola vez, deja que la persona las anote, y después llama a Clear() y descarta las cadenas. La biblioteca nunca guarda, imprime ni vuelve a mostrar una frase.
  • ParsePhrase lee 24 palabras separadas por espacios, tabulaciones o saltos de línea, sin distinguir mayúsculas, y ParseWords hace lo mismo con una lista ya separada. Solo se acepta ASCII, sin normalización Unicode, y se rechaza una entrada de más de 1024 bytes.
  • Phrase.Person deriva la clave de persona: la semilla BIP-39 con una passphrase vacía (2048 rondas de PBKDF2-HMAC-SHA512) y después SLIP-0010 para Ed25519 en la ruta reforzada m/1802464367'/0'/0'. La ruta nunca cambia, y las claves de dispositivo nunca se derivan de la frase. No hay passphrase de BIP-39.
  • Un error de tecleo al azar de cada 256 pasa la suma de control y da otra identidad válida, así que una pantalla de restauración debe mostrar la clave de persona (PublicKeyString) para que la persona la compruebe.
  • Un *Phrase se imprime como koloid.Phrase{redacted} con cualquier verbo de fmt y en log/slog, y nunca se codifica (ErrNotEncodable). Los errores dicen la posición de una palabra incorrecta, nunca la palabra: ErrPhraseLength, ErrUnknownWord (un *UnknownWordError), ErrPhraseChecksum y ErrInvalidPhrase.

Certificados de dispositivo

  • Una cadena es como mucho persona, aprobador, dispositivo. La clave de persona certifica dispositivos aprobadores; un aprobador certifica dispositivos comunes y no puede certificar a otro aprobador.
  • Un certificado se hace en dos pasos. Quien lo emite firma una oferta con OfferDeviceCert, y el dispositivo la completa con AcceptDeviceCert, lo que demuestra que tiene su propia clave. IssueOptions.Serial es al menos 1 y lo elige quien llama, porque la biblioteca no guarda estado.
  • DeviceCert.Person() y DeviceCert.Issuer() son afirmaciones dentro de bytes sin verificar. Fija la clave de persona en tu propio estado y nunca la tomes de un certificado que estás comprobando.
  • VerifyDevice(cert, opts, context, msg, sig) comprueba que un mensaje lo firmó un dispositivo de opts.Person: estructura, persona, caducidad, revocación y todas las firmas. No hay un modo sin certificado. DeviceCert.Verify hace las mismas comprobaciones sin mensaje.
  • Encode y DecodeCertOffer, DecodeDeviceCert y DecodeRevocation llevan los objetos por la red con la codificación de kolo-codec. Los decodificadores rechazan una entrada demasiado grande antes de analizarla y no comprueban firmas.
  • SaveCert y LoadCert guardan el certificado junto a la clave del dispositivo, por ejemplo device.key y device.cert, con modo 0600 y las mismas comprobaciones de directorio que Save y Load. Un certificado cargado es una entrada no confiable: verifícalo antes de usarlo.

Revocaciones

  • RevokeDevice tiene dos formas. La clave de persona o el propio dispositivo revocan por número de serie: todo certificado de esa clave hasta UpToSerial queda anulado, y math.MaxUint64 quema la clave para siempre. Un aprobador revoca un certificado exacto de un dispositivo común, indicado en RevokeOptions.Target; el registro firmado lleva su SHA-256 (Revocation.TargetHash), y Revocation.Signer devuelve el aprobador que lo firmó.
  • El hash cubre el cuerpo, el emisor y el padre del certificado, pero no sus firmas, porque las firmas Ed25519 no son únicas. La revocación de un aprobador no puede quemar una clave ni cubrir un certificado que todavía no existe. Para volver atrás basta un certificado nuevo para la misma clave de dispositivo con un número de serie nuevo.
  • Revocar a un aprobador, cosa que solo puede hacer la clave de persona, anula también todos los certificados que emitió.
  • Las revocaciones son permanentes. Un registro firmado por un aprobador se juzga por la estructura y las firmas de su certificado firmante, no por la caducidad de ese firmante ni por una revocación posterior suya. Guarda todo registro que haya pasado Revocation.Verify y pásalos en VerifyOptions.Revocations: quien verifica sin guardar ninguno no puede ver un dispositivo revocado.

Referencia de la API

La referencia de la API se genera a partir del código Go y está en inglés.

Paquete koloid · github.com/ciranda-dev/kolo-id · v0.1.0

Package koloid provides Ed25519 node identities for Kolo. Only the 32-byte seed is stored on disk.

A person with several devices has a recovery phrase of 24 words (BIP-39), a person key derived from it (SLIP-0010), one random key per device and a certificate for each device signed by the person key or by an approver device. A verifier states the person it expects and calls VerifyDevice; a revoked device is voided with Identity.RevokeDevice. The phrase is shown once and never stored by the library.

Experimental: the API may change before v1.0.0.

Variables

var (
	// ErrInvalidArgument is returned for bad options: a zero serial, an expiry not after the issue time, a missing or small-order key, an empty, long or reserved context.
	ErrInvalidArgument = errors.New("koloid: invalid argument")
	// ErrInvalidCert is returned for a certificate or offer that is nil, truncated, oversized, not canonical, has trailing bytes or breaks a structure rule.
	ErrInvalidCert = errors.New("koloid: invalid device certificate")
	// ErrNotApprover is returned by [Identity.OfferDeviceCert] and [Identity.RevokeDevice] when the signing certificate is not an approver certificate.
	ErrNotApprover = errors.New("koloid: signer is not an approver")
	// ErrCertSignature is returned when a certificate, offer or revocation signature, or the message signature, does not verify.
	ErrCertSignature = errors.New("koloid: device certificate signature does not verify")
	// ErrCertPerson is returned when the certificate chain does not end at the expected person key.
	ErrCertPerson = errors.New("koloid: device certificate is for another person")
	// ErrCertExpired is returned when a certificate in the chain is past its expiry.
	ErrCertExpired = errors.New("koloid: device certificate expired")
	// ErrCertRevoked is returned when a valid revocation covers a certificate in the chain.
	ErrCertRevoked = errors.New("koloid: device certificate revoked")
	// ErrInvalidRevocation is returned for a revocation that is malformed, unrelated to the expected person or not allowed to revoke its target.
	ErrInvalidRevocation = errors.New("koloid: invalid revocation")
)
var (
	// ErrInvalidKeyFile is returned by [Load] when the file is not a regular 32-byte file, and by [LoadCert] for an empty or over-514-byte file.
	ErrInvalidKeyFile = keyfile.ErrInvalid
	// ErrInsecureKeyFile is returned by [Load], [LoadCert], [SaveCert], [Identity.Save] and [Identity.SaveNew] when the key directory is a symlink
	// or others can access or another user owns the key file or its directory (see [Load]).
	ErrInsecureKeyFile = keyfile.ErrInsecure
	// ErrInvalidContext is returned by [Identity.Sign] for an empty, over-255-byte or reserved ("kolo-id/device-") context.
	ErrInvalidContext = errors.New("koloid: invalid signing context")
	// ErrInvalidIdentity is returned for a nil or zero Identity.
	ErrInvalidIdentity = errors.New("koloid: invalid identity")
	// ErrSavedNotSynced is returned by [Identity.Save] and [Identity.SaveNew] when the new key is in place but the directory sync failed.
	ErrSavedNotSynced = keyfile.ErrSavedNotSynced
	// ErrTempLeft is wrapped by [Identity.Save] and [Identity.SaveNew] when a temporary file could not be removed; the error text says whether the key was saved.
	ErrTempLeft = keyfile.ErrTempLeft
	// ErrNotDecodable is returned when decoding an Identity from text or JSON.
	ErrNotDecodable = errors.New("koloid: identities cannot be decoded; use Load or FromSeed")
)
var (
	// ErrInvalidPhrase is returned for a nil, zero or cleared Phrase.
	ErrInvalidPhrase = errors.New("koloid: invalid phrase")
	// ErrPhraseLength is returned when the input is not 24 words or is over 1024 bytes.
	ErrPhraseLength = errors.New("koloid: a phrase has 24 words")
	// ErrPhraseChecksum is returned when the 24 words are in the list but their checksum does not match.
	ErrPhraseChecksum = errors.New("koloid: phrase checksum does not match")
	// ErrUnknownWord is matched by [UnknownWordError]; no error text holds a word of the input.
	ErrUnknownWord = errors.New("koloid: unknown word in phrase")
	// ErrNotEncodable is returned when encoding or decoding a Phrase as text or JSON.
	ErrNotEncodable = errors.New("koloid: phrases cannot be encoded or decoded; use ParsePhrase")
)

Funciones

func SaveCert

func SaveCert(path string, c *DeviceCert) error

SaveCert atomically replaces path with the encoding of c, mode 0600, with the same directory checks as Identity.Save. Keep the certificate next to the device key, for example "device.cert" beside "device.key". It does not verify c.

func Verify

func Verify(pub ed25519.PublicKey, context string, msg, sig []byte) bool

Verify reports whether sig is a valid signature of msg by pub under context. It never panics on untrusted input. Verify rejects small-order public keys, for which a signature can be forged without a private key.

func VerifyDevice

func VerifyDevice(c *DeviceCert, opts *VerifyOptions, context string, msg, sig []byte) error

VerifyDevice reports nil when sig is a signature of msg under context by a device of opts.Person, after DeviceCert.Verify. A context that starts with "kolo-id/device-" is reserved and is ErrInvalidArgument.

Tipos

type CertOffer

type CertOffer struct {
	// contains filtered or unexported fields
}

CertOffer is a certificate signed by its issuer that the device has not accepted yet.

func DecodeCertOffer
func DecodeCertOffer(b []byte) (*CertOffer, error)

DecodeCertOffer decodes an offer written by CertOffer.Encode like DecodeDeviceCert; input over 450 bytes is refused.

func (CertOffer) Encode
func (o *CertOffer) Encode() []byte

Encode returns the canonical encoding of o, at most 450 bytes; nil for a nil offer.

type DeviceCert

type DeviceCert struct {
	// contains filtered or unexported fields
}

DeviceCert says that a device key belongs to a person key; it is public, immutable and trusted only after VerifyDevice or DeviceCert.Verify.

func DecodeDeviceCert
func DecodeDeviceCert(b []byte) (*DeviceCert, error)

DecodeDeviceCert decodes a certificate written by DeviceCert.Encode, checking structure but no signature. Input over 514 bytes is refused before parsing; every error wraps ErrInvalidCert.

func LoadCert
func LoadCert(path string) (*DeviceCert, error)

LoadCert reads a certificate written by SaveCert with the checks of Load; the result is untrusted until VerifyDevice or DeviceCert.Verify. An empty or over-514-byte file is ErrInvalidKeyFile; bytes that do not decode are ErrInvalidCert.

func (DeviceCert) Approver
func (c *DeviceCert) Approver() bool

Approver reports whether the device may certify and revoke ordinary devices without the phrase.

func (DeviceCert) Device
func (c *DeviceCert) Device() ed25519.PublicKey

Device returns the certified device key, or nil for a nil certificate.

func (DeviceCert) Encode
func (c *DeviceCert) Encode() []byte

Encode returns the canonical encoding of c, at most 256 bytes or 514 with a parent; nil for a nil certificate.

func (DeviceCert) ExpiresAt
func (c *DeviceCert) ExpiresAt() time.Time

ExpiresAt returns the expiry in whole seconds, or the zero time for never; a fractional expiry given to the issuer was truncated, so it came up to 1 s early.

func (DeviceCert) IssuedAt
func (c *DeviceCert) IssuedAt() time.Time

IssuedAt returns the issue time in whole seconds; it is informational, because a thief can back-date it.

func (DeviceCert) Issuer
func (c *DeviceCert) Issuer() ed25519.PublicKey

Issuer returns the key that claims to have signed the certificate, an unverified claim that is never a trust anchor; nil for a nil certificate.

func (DeviceCert) Person
func (c *DeviceCert) Person() ed25519.PublicKey

Person returns the person key the certificate claims, an unverified claim that is never a trust anchor; nil for a nil certificate.

func (DeviceCert) Serial
func (c *DeviceCert) Serial() uint64

Serial returns the serial chosen by the issuer; a revocation covers the serials up to its UpToSerial.

func (DeviceCert) Verify
func (c *DeviceCert) Verify(opts *VerifyOptions) error

Verify checks that c is valid for opts.Person at opts.Now: structure, person, expiry, revocation and every signature. It never panics.

type Identity

type Identity struct {
	// contains filtered or unexported fields
}

Identity is a Kolo node identity; hold it as *Identity. A *Identity prints and encodes as its public key; the seed never appears in any output. A plain Identity value prints an opaque code address and should not be logged; log the *Identity.

func FromSeed
func FromSeed(seed []byte) (*Identity, error)

FromSeed creates an Identity from a 32-byte Ed25519 seed. It copies what it needs and leaves seed untouched; the caller should clear seed when done.

func Generate
func Generate() (*Identity, error)

Generate creates a new random Identity.

func Load
func Load(path string) (*Identity, error)

Load reads an Identity written by Identity.Save or Identity.SaveNew. The path must end in a file name that names a regular 32-byte file, not a symlink (ErrInvalidKeyFile). It never blocks on a FIFO or device. The key file and its directory must belong to the effective user and have no group or other bits, or Load returns ErrInsecureKeyFile. The checks, which are stricter on Linux and macOS and absent on non-unix systems, are listed in docs/guide.md.

func (Identity) AcceptDeviceCert
func (i *Identity) AcceptDeviceCert(o *CertOffer, person ed25519.PublicKey) (*DeviceCert, error)

AcceptDeviceCert completes o into a certificate signed by the device key i, which proves the device holds it; person comes from the linking exchange, never from o.

func (Identity) Clear
func (i *Identity) Clear()

Clear erases the private key that i holds; i is invalid afterwards and so is every copy of it. It is not safe to call while another goroutine uses i, and it cannot erase copies made by the Go runtime or the standard library.

func (Identity) Format
func (i *Identity) Format(f fmt.State, _ rune)

Format prints Identity.String for every verb.

func (Identity) GoString
func (i *Identity) GoString() string

GoString returns the same as Identity.String.

func (Identity) LogValue
func (i *Identity) LogValue() slog.Value

LogValue makes log/slog print only the public key.

func (Identity) MarshalJSON
func (i *Identity) MarshalJSON() ([]byte, error)

MarshalJSON returns the public key as a hex JSON string.

func (Identity) MarshalText
func (i *Identity) MarshalText() ([]byte, error)

MarshalText returns the public key as hex.

func (Identity) OfferDeviceCert
func (i *Identity) OfferDeviceCert(device ed25519.PublicKey, o *IssueOptions) (*CertOffer, error)

OfferDeviceCert signs an offer that makes device a device of a person, with i as the person key (o.Parent nil) or an approver (o.Parent its certificate). The device completes the certificate with Identity.AcceptDeviceCert.

func (Identity) PublicKey
func (i *Identity) PublicKey() ed25519.PublicKey

PublicKey returns the public key, or nil for a nil or zero Identity.

func (Identity) PublicKeyString
func (i *Identity) PublicKeyString() string

PublicKeyString returns the public key as hex.

func (Identity) RevokeDevice
func (i *Identity) RevokeDevice(o *RevokeOptions) (*Revocation, error)

RevokeDevice signs a revocation of o.Device with i, the person key, the device itself or an approver device (o.SignerCert, o.Target).

func (Identity) Save
func (i *Identity) Save(path string) error

Save atomically replaces path with the 32-byte seed, mode 0600 (on Windows, the directory's access rules). A symlink at path is replaced, not followed, and a missing parent directory is created with mode 0700. The directory is checked like in Load before anything is written. If the temporary file cannot be removed, the error wraps ErrTempLeft; the key was not saved.

func (Identity) SaveNew
func (i *Identity) SaveNew(path string) error

SaveNew is like Identity.Save but never replaces anything at path, not even a dangling symlink: it returns an error wrapping io/fs.ErrExist instead. It needs a filesystem with hard links. If the temporary file cannot be removed, the error wraps ErrTempLeft and says whether the key was saved.

func (Identity) Sign
func (i *Identity) Sign(context string, msg []byte) ([]byte, error)

Sign returns the Ed25519ctx (RFC 8032) signature of msg under context; contexts that start with "kolo-id/device-" are reserved and refused.

func (Identity) String
func (i *Identity) String() string

String returns the public key, never the private key.

func (Identity) UnmarshalJSON
func (i *Identity) UnmarshalJSON([]byte) error

UnmarshalJSON always returns ErrNotDecodable, so JSON never yields an empty Identity.

func (Identity) UnmarshalText
func (i *Identity) UnmarshalText([]byte) error

UnmarshalText always returns ErrNotDecodable.

type IssueOptions

type IssueOptions struct {
	// Parent is nil when the signing identity is the person key; otherwise the signer's own approver certificate.
	Parent *DeviceCert
	// Serial is at least 1 and chosen by the caller; the library keeps no state.
	Serial uint64
	// IssuedAt is zero for now; it is truncated to whole seconds.
	IssuedAt time.Time
	// ExpiresAt is zero for never, otherwise after IssuedAt; it is truncated to whole seconds, so a fraction expires up to 1 s early.
	ExpiresAt time.Time
	// Approver gives the device the right to certify and revoke ordinary devices; only the person key may set it.
	Approver bool
}

IssueOptions are the choices of Identity.OfferDeviceCert.

type Phrase

type Phrase struct {
	// contains filtered or unexported fields
}

Phrase is a 24-word recovery phrase (BIP-39); hold it as *Phrase, which prints as redacted and never encodes.

func GeneratePhrase
func GeneratePhrase() (*Phrase, error)

GeneratePhrase creates a phrase from 256 bits of crypto/rand (BIP-39, section "Generating the mnemonic").

func ParsePhrase
func ParsePhrase(s string) (*Phrase, error)

ParsePhrase parses 24 words separated by spaces, tabs or line breaks, ignoring ASCII case; an error never holds a word.

func ParseWords
func ParseWords(words []string) (*Phrase, error)

ParseWords is like ParsePhrase for words already split; a word holding a space is unknown.

func (Phrase) Clear
func (p *Phrase) Clear()

Clear erases the entropy held by p, which is invalid afterwards; it is not safe to call while another goroutine uses p.

func (Phrase) Format
func (p *Phrase) Format(f fmt.State, _ rune)

Format prints Phrase.String for every verb.

func (Phrase) GoString
func (p *Phrase) GoString() string

GoString returns the same as Phrase.String.

func (Phrase) LogValue
func (p *Phrase) LogValue() slog.Value

LogValue makes log/slog print Phrase.String.

func (Phrase) MarshalJSON
func (p *Phrase) MarshalJSON() ([]byte, error)

MarshalJSON always returns ErrNotEncodable.

func (Phrase) MarshalText
func (p *Phrase) MarshalText() ([]byte, error)

MarshalText always returns ErrNotEncodable.

func (Phrase) Person
func (p *Phrase) Person() (*Identity, error)

Person returns the person key at m/1802464367'/0'/0' under the phrase's BIP-39 seed; it fails under GODEBUG=fips140=only.

func (Phrase) String
func (p *Phrase) String() string

String returns "koloid.Phrase{redacted}", never a word.

func (Phrase) UnmarshalJSON
func (p *Phrase) UnmarshalJSON([]byte) error

UnmarshalJSON always returns ErrNotEncodable.

func (Phrase) UnmarshalText
func (p *Phrase) UnmarshalText([]byte) error

UnmarshalText always returns ErrNotEncodable.

func (Phrase) Words
func (p *Phrase) Words() []string

Words returns the 24 words in a fresh slice, or nil for an invalid phrase; Go strings cannot be erased, so show them and drop them.

type Revocation

type Revocation struct {
	// contains filtered or unexported fields
}

Revocation is public, immutable and permanent. The person key or the device itself voids a device's certificates up to a serial; an approver voids one ordinary-device certificate, named by the hash of its body and parent.

func DecodeRevocation
func DecodeRevocation(b []byte) (*Revocation, error)

DecodeRevocation decodes a revocation written by Revocation.Encode, checking structure but no signature. Input over 472 bytes is refused before parsing; every error wraps ErrInvalidRevocation.

func (Revocation) Device
func (r *Revocation) Device() ed25519.PublicKey

Device returns the revoked device key, or nil for a nil revocation.

func (Revocation) Encode
func (r *Revocation) Encode() []byte

Encode returns the canonical encoding of r, at most 472 bytes; nil for a nil revocation.

func (Revocation) Person
func (r *Revocation) Person() ed25519.PublicKey

Person returns the person key the revocation is for, or nil for a nil revocation.

func (Revocation) Signer
func (r *Revocation) Signer() ed25519.PublicKey

Signer returns the approver device key that signed an approver-form revocation, so an application can drop the records of a retired approver; nil when the person key or the device itself signed.

func (Revocation) TargetHash
func (r *Revocation) TargetHash() []byte

TargetHash returns the hash of the body, issuer and parent of the certificate an approver revoked, never of its signatures; nil when the person key or the device itself signed.

func (Revocation) UpToSerial
func (r *Revocation) UpToSerial() uint64

UpToSerial returns the highest serial the revocation voids; for an approver it is the serial of the one certificate it names.

func (Revocation) Verify
func (r *Revocation) Verify(opts *VerifyOptions, target *DeviceCert) error

Verify checks r for opts.Person: structure, signatures and the right of the signer to revoke target, which an approver-signed r needs and must name by hash; opts.Now is not used. Errors: ErrInvalidArgument, ErrInvalidRevocation, ErrCertSignature.

type RevokeOptions

type RevokeOptions struct {
	Person ed25519.PublicKey
	Device ed25519.PublicKey
	// UpToSerial is at least 1 for the person key or the device itself, and voids the certificates of Device up to it; math.MaxUint64 burns the key.
	// An approver signs for one certificate: UpToSerial is zero or Target's serial.
	UpToSerial uint64
	// SignerCert is the signing device's approver certificate; nil when the signer is the person key or the device itself.
	SignerCert *DeviceCert
	// Target is the ordinary-device certificate an approver revokes, required with SignerCert and nil otherwise.
	Target *DeviceCert
	// At is zero for now; it is truncated to whole seconds and never decides validity.
	At time.Time
}

RevokeOptions are the choices of Identity.RevokeDevice.

type UnknownWordError

type UnknownWordError struct{ Position int }

UnknownWordError says which word of the input (1-based position) is not in the word list; it matches ErrUnknownWord.

func (UnknownWordError) Error
func (e *UnknownWordError) Error() string

Error reports the position of the unknown word and never the word.

func (UnknownWordError) Is
func (e *UnknownWordError) Is(target error) bool

Is reports whether target is ErrUnknownWord.

type VerifyOptions

type VerifyOptions struct {
	// Person is required: the person key the caller expects. A certificate never names its own trust anchor.
	Person ed25519.PublicKey
	// Now is the time for expiry checks; zero is time.Now().
	Now time.Time
	// Revocations are the records the caller holds; invalid or unrelated ones are ignored. Keep only records that passed [Revocation.Verify], and bound the slice.
	Revocations []*Revocation
}

VerifyOptions are the expectations of a verifier.

Conviene saber

Límites

  • Semilla: exactamente 32 bytes. FromSeed devuelve un error con cualquier otra longitud.
  • Archivo de clave: un archivo normal de exactamente 32 bytes; si no, Load devuelve ErrInvalidKeyFile.
  • Contexto de firma: de 1 a 255 bytes. Fuera de ese rango, Sign devuelve ErrInvalidContext y Verify devuelve false.
  • Clave pública: 32 bytes. Verify devuelve false con cualquier otro tamaño.
  • Frase: exactamente 24 palabras de la lista inglesa de BIP-39, solo ASCII. ParsePhrase rechaza más de 1024 bytes de entrada (una frase ocupa como mucho 215 bytes).
  • Tamaños codificados: un certificado como mucho 256 bytes, o 514 con un padre aprobador; una oferta como mucho 450 (192 sin padre); una revocación como mucho 472 (182 para la clave de persona o el propio dispositivo). Un archivo de certificado tiene de 1 a 514 bytes. Son los máximos reales de los formatos, y los decodificadores rechazan una entrada mayor antes de analizarla.
  • Número de serie: al menos 1. Las horas de un certificado son segundos Unix enteros, y un expiresAt de 0 significa nunca.
  • VerifyDevice comprueba como mucho 4 firmas de certificado y 1 firma de mensaje. Para las revocaciones indexa la lista una vez, así que el trabajo es lineal en la lista, que limita quien llama.
  • Save y SaveNew escriben el archivo de clave con modo 0600 y crean el directorio padre que falte con modo 0700. En Windows, el archivo toma las reglas de acceso de su directorio.

Seguridad

  • Las firmas usan Ed25519ctx (RFC 8032).
  • Verify devuelve false ante cualquier entrada incorrecta y nunca entra en pánico. Rechaza las claves públicas de orden pequeño (las 14 codificaciones que acepta Go), con las que se puede falsificar una firma sin la clave privada.
  • La semilla nunca se imprime, se registra ni se serializa. UnmarshalJSON y UnmarshalText siempre devuelven ErrNotDecodable; usa Load o FromSeed.
  • SaveNew nunca sustituye nada en la ruta, ni siquiera un symlink roto. Si un segundo proceso compite por crear la clave, o si hay un symlink roto hacia un volumen sin montar, falla en lugar de destruir una clave.
  • Save sustituye un symlink en la ruta en lugar de seguirlo. La ruta debe terminar en un nombre de archivo.
  • Load rechaza un symlink en la ruta y un archivo que no sea normal, y nunca se bloquea con un FIFO ni con un dispositivo.
  • En unix, Load devuelve ErrInsecureKeyFile cuando el archivo de clave o su directorio, y Save y SaveNew cuando el directorio, no pertenecen al usuario efectivo o tienen activados bits de modo de grupo u otros. En Linux, una ACL POSIX aparece en los bits de grupo, así que se detecta. En macOS también se rechazan las entradas ACL que permiten acceso y los volúmenes montados para ignorar la propiedad.
  • Una Identity nil o vacía hace que Sign, Save y SaveNew devuelvan ErrInvalidIdentity en lugar de entrar en pánico.
  • Los contextos que empiezan por kolo-id/device- están reservados para certificados y revocaciones (kolo-id/device-link/v0, kolo-id/device-accept/v0 y kolo-id/device-revoke/v0). Sign devuelve ErrInvalidContext con ellos y VerifyDevice los rechaza, así que ninguna firma de una aplicación puede pasar por un certificado o una revocación.
  • Un dispositivo aprobador puede certificar y revocar dispositivos comunes, pero no aprobadores; un dispositivo común solo puede firmar como él mismo y revocarse a sí mismo. Un certificado solo es público y no firma nada.
  • Una frase filtrada no se puede reparar dentro de la misma identidad: crea una frase nueva. Un aprobador robado puede seguir certificando dispositivos comunes hasta que la persona lo revoque con la frase, y revocarlo anula también los dispositivos legítimos que certificó.
  • Identity.Clear y Phrase.Clear borran el material de clave que guarda la biblioteca. Es lo mejor posible: las copias dentro del runtime de Go y de la biblioteca estándar no se pueden alcanzar.
  • La lista de palabras BIP-39 incluida está fijada por su SHA-256 y se comprueba en el primer uso, y los vectores de prueba oficiales de BIP-39 y SLIP-0010 se ejecutan con los tests. Sus fuentes, commits, hashes y licencias están en third_party/licenses/NOTICE.md.

Límites conocidos

  • Experimental. La API puede cambiar antes de v1.0.0.
  • FreeBSD e illumos: no se comprueban las ACL de NFSv4 (como en ZFS).
  • Los sistemas que no son unix no comprueban ni el propietario ni los bits de modo.
  • Los sistemas distintos de Linux y macOS vuelven a abrir el directorio de la clave por su ruta, así que un FIFO colocado justo en ese momento todavía puede bloquear, y se puede seguir un symlink dentro del directorio (Load lo rechaza después).
  • En Linux y macOS se llega al directorio a través de /proc/self/fd o /dev/fd. Si no están disponibles, Load, Save y SaveNew fallan con ErrInsecureKeyFile.
  • SaveNew necesita un sistema de archivos con enlaces duros.
  • Phrase.Person devuelve un error con GODEBUG=fips140=only, donde Go rechaza la sal que fija BIP-39 y la clave maestra de SLIP-0010.
  • La biblioteca no guarda estado: las revocaciones protegen solo a quien verifica y las tiene, así que las aplicaciones deben llevarlas a cada uno.

Errores

ErrorMensaje
ErrCertExpiredkoloid: device certificate expired
ErrCertPersonkoloid: device certificate is for another person
ErrCertRevokedkoloid: device certificate revoked
ErrCertSignaturekoloid: device certificate signature does not verify
ErrInsecureKeyFilekoloid: key file or its directory is accessible to others or owned by another user
ErrInvalidArgumentkoloid: invalid argument
ErrInvalidCertkoloid: invalid device certificate
ErrInvalidContextkoloid: invalid signing context
ErrInvalidIdentitykoloid: invalid identity
ErrInvalidKeyFilekoloid: invalid key file
ErrInvalidPhrasekoloid: invalid phrase
ErrInvalidRevocationkoloid: invalid revocation
ErrNotApproverkoloid: signer is not an approver
ErrNotDecodablekoloid: identities cannot be decoded; use Load or FromSeed
ErrNotEncodablekoloid: phrases cannot be encoded or decoded; use ParsePhrase
ErrPhraseChecksumkoloid: phrase checksum does not match
ErrPhraseLengthkoloid: a phrase has 24 words
ErrSavedNotSyncedkoloid: key file saved but directory sync failed
ErrTempLeftkoloid: temporary key file left on disk
ErrUnknownWordkoloid: unknown word in phrase

Comprueba los errores con errors.Is, porque la mayoría llegan envueltos con la ruta o una causa. SaveNew sobre una ruta existente coincide con fs.ErrExist, y Load de un archivo que no existe coincide con os.ErrNotExist. Cuando solo falla la sincronización final del directorio, el error envuelve ErrSavedNotSynced y la nueva clave ya está en su sitio. Cuando no se puede borrar un archivo temporal, el error envuelve ErrTempLeft, nombra el archivo e indica si la clave se ha guardado. Los errores de la frase y de los certificados nunca contienen bytes de la entrada, y un error de opciones de OfferDeviceCert o RevokeDevice coincide con ErrInvalidArgument y también con ErrInvalidCert o ErrInvalidRevocation.

Referencias