kolo docsbeta

kolo-id

Identidade Ed25519 do nó para o Kolo, com assinatura, verificação, um arquivo de chave privada, uma frase de recuperação de 24 palavras e certificados de dispositivo.

Nesta página

Um nó do Kolo é identificado pela sua chave pública Ed25519. A kolo-id cria e guarda esse par de chaves, assina mensagens com Ed25519ctx da RFC 8032 e verifica assinaturas de outros peers. Todas as outras bibliotecas do Kolo pegam suas identidades daqui. Ela não decide em quais chaves confiar.

Uma pessoa pode usar vários dispositivos. Uma frase de recuperação de 24 palavras dá uma chave de pessoa (com BIP-39 e SLIP-0010), e cada dispositivo guarda a sua própria chave aleatória e um certificado assinado por essa chave de pessoa, então um dispositivo perdido é revogado sem perder a identidade.

Todos os passos

Chaves, assinatura e verificação

Só a semente é guardada. Uma assinatura só confere com o contexto em que foi feita.

  1. Generate pega 32 bytes aleatórios: a semente.
  2. A semente dá a chave privada (64 bytes, na memória) e a chave pública (32 bytes). A chave pública é a identidade, escrita como 64 caracteres hexadecimais.
  3. Sign usa Ed25519ctx: a chave privada assina a mensagem com um contexto de 1 a 255 bytes e dá uma assinatura de 64 bytes.
  4. Verify recebe a chave pública, o mesmo contexto, a mensagem e a assinatura, e retorna true.
  5. Retorna false com outro contexto, com uma chave pública que não tenha 32 bytes ou com uma chave de ordem pequena.
  6. Save grava só a semente, em um arquivo com modo 0600. Load a lê de volta e gera o mesmo par de chaves.

Instalação

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

É Go puro, sem cgo. As dependências são golang.org/x/sys, para o openat via libc no macOS, e a kolo-codec, para a codificação dos certificados.

Início rápido

Crie uma identidade, assine sob um contexto e depois salve e carregue essa identidade em um diretório temporário.

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()))
}

O programa imprime a chave pública, valid: true, other context: false e same key: true. Um nó real chama Load primeiro e, quando o erro corresponde a os.ErrNotExist, chama Generate e SaveNew uma única vez. Assim ele mantém a mesma chave pública entre reinicializações.

Frase de recuperação e dispositivos

A chave de pessoa nunca fica em um dispositivo. As 24 palavras dão a chave de pessoa, a chave de pessoa certifica o primeiro dispositivo como aprovador, e um aprovador adiciona dispositivos comuns sem as palavras. Quem verifica sempre informa a pessoa que espera. Este programa, examples/devices no repositório, percorre o fluxo inteiro em um diretório temporário e nunca imprime a 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
}

O programa imprime a chave de pessoa e words: 24, depois phone message: <nil>, after revoking: true e restored the same person: true.

Frase de recuperação

  • GeneratePhrase cria 24 palavras da lista em inglês do BIP-39 com crypto/rand: 256 bits de entropia e um checksum de 8 bits. Mostre Words() uma única vez, deixe a pessoa anotar as palavras, depois chame Clear() e descarte as strings. A biblioteca nunca guarda, imprime nem mostra uma frase de novo.
  • ParsePhrase lê 24 palavras separadas por espaços, tabs ou quebras de linha, sem diferenciar maiúsculas, e ParseWords faz o mesmo com uma lista já separada. Só ASCII é aceito, sem normalização Unicode, e uma entrada com mais de 1024 bytes é recusada.
  • Phrase.Person deriva a chave de pessoa: a seed BIP-39 com passphrase vazia (2048 rodadas de PBKDF2-HMAC-SHA512) e depois SLIP-0010 para Ed25519 no caminho endurecido m/1802464367'/0'/0'. O caminho nunca muda, e as chaves de dispositivo nunca são derivadas da frase. Não existe passphrase do BIP-39.
  • Um erro de digitação aleatório em cada 256 passa no checksum e dá outra identidade válida, então uma tela de restauração deve mostrar a chave de pessoa (PublicKeyString) para a pessoa conferir.
  • Um *Phrase é impresso como koloid.Phrase{redacted} com qualquer verbo do fmt e no log/slog, e nunca é codificado (ErrNotEncodable). Os erros dizem a posição de uma palavra errada, nunca a palavra: ErrPhraseLength, ErrUnknownWord (um *UnknownWordError), ErrPhraseChecksum e ErrInvalidPhrase.

Certificados de dispositivo

  • Uma cadeia é no máximo pessoa, aprovador, dispositivo. A chave de pessoa certifica dispositivos aprovadores; um aprovador certifica dispositivos comuns e não pode certificar outro aprovador.
  • Um certificado é feito em dois passos. Quem emite assina uma oferta com OfferDeviceCert, e o dispositivo a completa com AcceptDeviceCert, o que prova que ele tem a própria chave. IssueOptions.Serial é pelo menos 1 e é escolhido por quem chama, porque a biblioteca não guarda estado.
  • DeviceCert.Person() e DeviceCert.Issuer() são afirmações dentro de bytes não verificados. Fixe a chave de pessoa no seu próprio estado e nunca a tire de um certificado que você está verificando.
  • VerifyDevice(cert, opts, context, msg, sig) verifica que uma mensagem foi assinada por um dispositivo de opts.Person: estrutura, pessoa, validade, revogação e todas as assinaturas. Não existe modo sem certificado. DeviceCert.Verify faz as mesmas verificações sem mensagem.
  • Encode e DecodeCertOffer, DecodeDeviceCert e DecodeRevocation levam os objetos pela rede na codificação da kolo-codec. Os decodificadores recusam uma entrada grande demais antes de analisá-la e não verificam assinaturas.
  • SaveCert e LoadCert guardam o certificado ao lado da chave do dispositivo, por exemplo device.key e device.cert, com modo 0600 e as mesmas verificações de diretório de Save e Load. Um certificado carregado é uma entrada não confiável: verifique-o antes de usar.

Revogações

  • RevokeDevice tem duas formas. A chave de pessoa ou o próprio dispositivo revogam por número de série: todo certificado dessa chave até UpToSerial fica anulado, e math.MaxUint64 queima a chave para sempre. Um aprovador revoga um certificado exato de um dispositivo comum, indicado em RevokeOptions.Target; o registro assinado leva o SHA-256 dele (Revocation.TargetHash), e Revocation.Signer devolve o aprovador que o assinou.
  • O hash cobre o corpo, o emissor e o pai do certificado, mas não as assinaturas, porque assinaturas Ed25519 não são únicas. A revogação de um aprovador não pode queimar uma chave nem cobrir um certificado que ainda não existe. Para voltar atrás, basta um certificado novo para a mesma chave de dispositivo com um número de série novo.
  • Revogar um aprovador, o que só a chave de pessoa pode fazer, também anula todos os certificados que ele emitiu.
  • As revogações são permanentes. Um registro assinado por um aprovador é julgado pela estrutura e pelas assinaturas do certificado do signatário, não pela validade desse signatário nem por uma revogação posterior dele. Guarde todo registro que passou em Revocation.Verify e passe-os em VerifyOptions.Revocations: quem verifica sem guardar nenhum não enxerga um dispositivo revogado.

Referência da API

A referência da API é gerada a partir do código Go e está em inglês.

Pacote 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.

Variáveis

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")
)

Funções

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.

Bom saber

Limites

  • Seed: exatamente 32 bytes. FromSeed retorna um erro para qualquer outro tamanho.
  • Arquivo de chave: um arquivo regular de exatamente 32 bytes, senão Load retorna ErrInvalidKeyFile.
  • Contexto de assinatura: de 1 a 255 bytes. Fora dessa faixa, Sign retorna ErrInvalidContext e Verify retorna false.
  • Chave pública: 32 bytes. Verify retorna false para qualquer outro tamanho.
  • Frase: exatamente 24 palavras da lista em inglês do BIP-39, só ASCII. ParsePhrase recusa mais de 1024 bytes de entrada (uma frase tem no máximo 215 bytes).
  • Tamanhos codificados: um certificado no máximo 256 bytes, ou 514 com um pai aprovador; uma oferta no máximo 450 (192 sem pai); uma revogação no máximo 472 (182 para a chave de pessoa ou o próprio dispositivo). Um arquivo de certificado tem de 1 a 514 bytes. São os máximos reais dos formatos, e os decodificadores recusam uma entrada maior antes de analisá-la.
  • Número de série: pelo menos 1. Os horários de um certificado são segundos Unix inteiros, e um expiresAt igual a 0 significa nunca.
  • VerifyDevice verifica no máximo 4 assinaturas de certificado e 1 assinatura de mensagem. Para as revogações ela indexa a lista uma vez, então o trabalho é linear na lista, que quem chama limita.
  • Save e SaveNew gravam o arquivo de chave com modo 0600 e criam o diretório pai, se ele não existir, com modo 0700. No Windows o arquivo herda as regras de acesso do seu diretório.

Segurança

  • As assinaturas usam Ed25519ctx (RFC 8032).
  • Verify retorna false para qualquer entrada inválida e nunca entra em pânico. Ela rejeita chaves públicas de ordem pequena (todas as 14 codificações que o Go aceita), para as quais dá para forjar uma assinatura sem a chave privada.
  • A seed nunca é impressa, registrada em log nem serializada. UnmarshalJSON e UnmarshalText sempre retornam ErrNotDecodable; use Load ou FromSeed.
  • SaveNew nunca substitui nada no caminho, nem mesmo um symlink quebrado. Se um segundo processo disputar a criação da chave, ou se houver um symlink quebrado para um volume não montado, a função falha em vez de destruir uma chave.
  • Save substitui um symlink no caminho em vez de segui-lo. O caminho precisa terminar em um nome de arquivo.
  • Load recusa um symlink no caminho e um arquivo que não seja regular, e nunca fica bloqueada em um FIFO ou em um dispositivo.
  • Em sistemas unix, Load retorna ErrInsecureKeyFile quando o arquivo de chave ou o seu diretório, e Save e SaveNew quando o diretório, não pertence ao usuário efetivo ou tem bits de permissão de grupo ou de outros ativados. No Linux uma ACL POSIX aparece nos bits de grupo, então ela é detectada. No macOS, entradas de ACL que liberam acesso e volumes montados para ignorar o dono também são recusados.
  • Uma Identity nil ou zerada faz Sign, Save e SaveNew retornarem ErrInvalidIdentity em vez de entrar em pânico.
  • Os contextos que começam com kolo-id/device- são reservados para certificados e revogações (kolo-id/device-link/v0, kolo-id/device-accept/v0 e kolo-id/device-revoke/v0). Sign retorna ErrInvalidContext para eles e VerifyDevice os recusa, então nenhuma assinatura de uma aplicação pode se passar por um certificado ou uma revogação.
  • Um dispositivo aprovador pode certificar e revogar dispositivos comuns, mas não aprovadores; um dispositivo comum só pode assinar como ele mesmo e revogar a si mesmo. Um certificado sozinho é público e não assina nada.
  • Uma frase vazada não pode ser consertada dentro da mesma identidade: crie uma frase nova. Um aprovador roubado continua podendo certificar dispositivos comuns até a pessoa revogá-lo com a frase, e revogá-lo também anula os dispositivos legítimos que ele certificou.
  • Identity.Clear e Phrase.Clear apagam o material de chave que a biblioteca guarda. É o melhor possível: cópias dentro do runtime do Go e da biblioteca padrão não podem ser alcançadas.
  • A lista de palavras do BIP-39 embutida é fixada pelo seu SHA-256 e verificada no primeiro uso, e os vetores de teste oficiais do BIP-39 e do SLIP-0010 rodam com os testes. Fontes, commits, hashes e licenças estão em third_party/licenses/NOTICE.md.

Limites conhecidos

  • Experimental. A API pode mudar antes da v1.0.0.
  • FreeBSD e illumos: ACLs NFSv4 (como no ZFS) não são verificadas.
  • Sistemas que não são unix não verificam nem o dono nem os bits de permissão.
  • Sistemas que não são Linux nem macOS reabrem o diretório da chave pelo caminho. Assim, um FIFO trocado nesse instante ainda pode bloquear, e um symlink dentro do diretório pode ser seguido (Load então o rejeita).
  • No Linux e no macOS o diretório é acessado por /proc/self/fd ou /dev/fd. Se eles não estiverem disponíveis, Load, Save e SaveNew falham com ErrInsecureKeyFile.
  • SaveNew precisa de um sistema de arquivos com hard links.
  • Phrase.Person retorna um erro com GODEBUG=fips140=only, em que o Go recusa o salt que o BIP-39 fixa e a chave mestra do SLIP-0010.
  • A biblioteca não guarda estado: as revogações protegem só quem verifica e as tem, então as aplicações precisam levá-las a cada um.

Erros

ErroMensagem
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

Teste os erros com errors.Is, porque a maioria vem envolvida com o caminho ou com uma causa. SaveNew em um caminho que já existe corresponde a fs.ErrExist, e Load de um arquivo que não existe corresponde a os.ErrNotExist. Quando só a sincronização final do diretório falha, o erro envolve ErrSavedNotSynced e a nova chave já está no lugar. Quando um arquivo temporário não pode ser removido, o erro envolve ErrTempLeft, informa o nome do arquivo e diz se a chave foi salva. Os erros da frase e dos certificados nunca contêm bytes da entrada, e um erro de opção de OfferDeviceCert ou RevokeDevice corresponde a ErrInvalidArgument e também a ErrInvalidCert ou ErrInvalidRevocation.

Referências