kolo docsbeta

kolo-mls

Criptografia de ponta a ponta para grupos pelo padrão MLS (RFC 9420), com um membro por dispositivo e cada época decidida pelos admins por meio da kolo-braid.

Nesta página

A kolo-mls dá aos grupos criptografia de ponta a ponta pelo protocolo Messaging Layer Security (RFC 9420, com a arquitetura no RFC 9750) para a suíte de cifragem 0x0001 (X25519, AES-128-GCM, SHA-256, Ed25519), escrita só sobre a biblioteca padrão do Go. Só os membros atuais de um grupo conseguem ler as suas mensagens: o histórico de um grupo é uma cadeia de épocas, e cada época começa com um commit que dá segredos novos só aos membros dessa época. Cada dispositivo é um membro (uma folha, ou leaf, da árvore do grupo), e a sua identidade é uma cadeia de certificados de dispositivo da kolo-id. Os dispositivos admin do grupo decidem o commit de cada época por meio da kolo-braid, e a aplicação leva os commits (por exemplo pela kolo-gossip) e os guarda em pins (kolo-pin), para que um dispositivo que ficou offline possa se atualizar. A aplicação também entrega o welcome de um membro novo; a kolo-mls não o liga a nenhuma biblioteca de transporte. Os formatos próprios do Kolo em volta do MLS usam a kolo-codec.

O pacote raiz kolomls é o núcleo MLS, com o estado do grupo guardado em um Store que você fornece. Um grupo do Kolo acrescenta os pacotes cred (a credencial de um dispositivo da kolo-id), settle (as regras de um dispositivo membro: um commit só é aplicado com assinaturas de um quórum de settlers) e braid (o lado dos admins sobre a kolo-braid), e o backendstore guarda os grupos em um backend da kolo-store.

A aplicação fornece cinco coisas: um Authenticator que confere as credenciais (em um grupo do Kolo, cred.Authenticator, cuja função Expect é a verificação de se uma pessoa pode estar no grupo; sem ela, qualquer pessoa que os admins adicionem é aceita), uma Policy com as regras da aplicação (em um grupo do Kolo, settle.Policy), um Store que guarda o estado do grupo (MemStore em memória, ou backendstore.New sobre um backend da kolo-store), um relógio e as chamadas que a biblioteca pede nos momentos que ela devolve (ela não tem timers), e pelo menos dois dispositivos admin.

Todos os passos

Uma mudança de época, assentada pelos admins

O braid só contém os dispositivos admin, e cada membro aplica um Commit só com um quórum de assinaturas de settlers.

  1. Na época n cada dispositivo membro é uma folha da ratchet tree do grupo. O braid do grupo só contém os dispositivos admin, e os settlers estão entre eles.
  2. Um admin cria um Commit, aqui para remover o dispositivo D. Ele guarda os bytes do Commit nos pins e escreve uma referência a eles no braid dos admins: o grupo, a época e o hash do Commit.
  3. Os settlers votam a partir da ordem assentada do braid: a primeira referência ainda não decidida vence com um quórum de votos a favor. Três settlers com a regra da maioria precisam de dois.
  4. Os settlers assinam o Commit decidido sob o contexto kolo-mls/commit-settled/v0. Um quórum dessas assinaturas forma o commit assentado, que um admin guarda nos pins.
  5. A aplicação leva o Commit e as assinaturas aos membros. Cada membro aplica o Commit só com assinaturas de um quórum dos settlers da época, e passa à época n + 1 com segredos novos. O dispositivo removido D não consegue calculá-los.
  6. Quando um Commit adiciona um membro, o seu welcome só é enviado depois que as assinaturas dos settlers existem. A aplicação o entrega a esse membro, que entra com o welcome, o commit assentado e a árvore cifrada dos pins.

Instalação

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

Ela precisa do Go 1.26 ou mais novo e é Go puro: sem cgo e sem nada para instalar. O pacote raiz importa só a biblioteca padrão; cred, settle, braid e backendstore trazem também módulos do Kolo (kolo-id, kolo-codec, kolo-braid, kolo-store). Um dispositivo membro (settle, com cred e o núcleo) só precisa do núcleo, da kolo-id e da kolo-codec. O lado admin (braid) roda sobre a kolo-braid e o backendstore sobre um backend da kolo-store; o backend em disco da kolo-store compila com CGO_ENABLED=0 (com o cgo ativo, ele liga uma biblioteca de compressão em C). A kolo-mls está etiquetada como v0.1.0: para fixá-la, rode go get github.com/ciranda-dev/kolo-mls@v0.1.0.

Início rápido

Dois membros em memória: alice cria um grupo com um KeyPackage próprio, adiciona o bob com o KeyPackage dele, o ratchet tree chega a ele junto com o Welcome, e ela lhe envia uma mensagem. As credenciais são básicas e conferidas por um pequeno diretório que liga cada nome a uma chave (um Authenticator), um envelope (Envelope) amarra a geração de cada mensagem aos seus dados autenticados (RFC 9750, seção 8.6), e a Policy não acrescenta nenhuma regra além das do RFC 9420. Este é o examples/basic do repositório; rode-o com go run ./examples/basic em um clone.

main.go
// Command basic creates an MLS group of two members in memory: alice creates it,
// adds bob with his KeyPackage and a Welcome, and sends him one message.
package main

import (
	"bytes"
	"crypto/ed25519"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"log"
	"os"

	kolomls "github.com/ciranda-dev/kolo-mls"
)

// directory is a small Authentication Service: it accepts a basic credential
// only with the signature key registered for its identity.
type directory map[string]ed25519.PublicKey

func (d directory) Validate(c kolomls.Credential, signatureKey []byte, _ kolomls.Event) error {
	key, ok := d[string(c.Identity)]
	if c.Type != kolomls.CredentialBasic || !ok || !bytes.Equal(key, signatureKey) {
		return errors.New("basic: unknown identity or signature key")
	}
	return nil
}

func (d directory) Successor(prev, next kolomls.Credential) error {
	if !bytes.Equal(prev.Identity, next.Identity) {
		return errors.New("basic: identity changed")
	}
	return nil
}

func (d directory) ClientID(c kolomls.Credential) ([]byte, error) { return c.Identity, nil }

// generation binds the generation of each PrivateMessage into its signed
// authenticated data, so a member cannot replay another member's message
// under a later generation (RFC 9750 section 8.6). Kolo groups use
// settle.Envelope.
type generation struct{}

func (generation) Wrap(gen uint32, aad []byte) ([]byte, error) {
	return append(binary.BigEndian.AppendUint32(nil, gen), aad...), nil
}

func (generation) Unwrap(gen uint32, ad []byte) ([]byte, error) {
	if len(ad) < 4 || binary.BigEndian.Uint32(ad) != gen {
		return nil, errors.New("basic: authenticated data of another generation")
	}
	return ad[4:], nil
}

// rfcOnly adds no rule to those of RFC 9420.
type rfcOnly struct{}

func (rfcOnly) CheckProposal(kolomls.ProposalView) error { return nil }
func (rfcOnly) CheckCommit(kolomls.CommitView) error     { return nil }
func (rfcOnly) CheckJoin(kolomls.JoinView) error         { return nil }

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

// keyPackage registers a new signature key for name in d, which binds a
// name to one key, and returns a KeyPackage whose private keys go in st.
func keyPackage(st kolomls.Store, d directory, name string) ([]byte, error) {
	if _, ok := d[name]; ok {
		return nil, fmt.Errorf("basic: %s is already registered", name)
	}
	pub, priv, err := ed25519.GenerateKey(nil)
	if err != nil {
		return nil, err
	}
	d[name] = pub
	c := kolomls.Credential{Type: kolomls.CredentialBasic, Identity: []byte(name)}
	return kolomls.NewKeyPackage(st, kolomls.KeyPackageOptions{Credential: c, SignatureKey: priv})
}

// config is the Config of the groups, with d as their Authentication
// Service.
func config(d directory) kolomls.Config {
	return kolomls.Config{Authenticator: d, Policy: rfcOnly{}, Envelope: generation{}}
}

func run(w io.Writer) error {
	d := directory{}
	cfg := config(d)
	aliceStore, bobStore := kolomls.NewMemStore(), kolomls.NewMemStore()

	aliceKP, err := keyPackage(aliceStore, d, "alice")
	if err != nil {
		return err
	}
	alice, err := kolomls.Create(aliceStore, kolomls.CreateOptions{Config: cfg, KeyPackage: aliceKP})
	if err != nil {
		return err
	}
	defer alice.Close()

	bobKP, err := keyPackage(bobStore, d, "bob")
	if err != nil {
		return err
	}
	pc, err := alice.Commit(kolomls.CommitOptions{Add: [][]byte{bobKP}})
	if err != nil {
		return err
	}
	tree, err := pc.RatchetTree()
	if err != nil {
		return err
	}
	if err := alice.ApplyPending(); err != nil {
		return err
	}
	bob, err := kolomls.Join(bobStore, pc.Welcome(), tree, kolomls.JoinOptions{Config: cfg})
	if err != nil {
		return err
	}
	defer bob.Close()

	msg, err := alice.Encrypt([]byte("hello, bob"), nil)
	if err != nil {
		return err
	}
	res, err := bob.Process(msg)
	if err != nil {
		return err
	}
	ea, err := alice.EpochAuthenticator()
	if err != nil {
		return err
	}
	eb, err := bob.EpochAuthenticator()
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "bob read %q in epoch %d\n", res.Application, res.Epoch)
	fmt.Fprintf(w, "members: %d\n", len(bob.Tree().Members()))
	fmt.Fprintf(w, "same epoch authenticator: %t\n", bytes.Equal(ea, eb))
	return nil
}

Ele imprime:

Texto
$ go run ./examples/basic
bob read "hello, bob" in epoch 1
members: 2
same epoch authenticator: true

Um grupo do Kolo usa no lugar cred, settle e braid: a credencial é um certificado de dispositivo da kolo-id, um commit só é aplicado com assinaturas de um quórum de settlers, e os admins decidem cada época por meio da kolo-braid. Bom saber explica as épocas, os commits, os admins e os settlers.

Formatos

As mensagens MLS usam a codificação do RFC 9420, cuja notação é a linguagem de apresentação da seção 3 do RFC 9846, e não a kolo-codec. É uma exceção deliberada à regra de que os formatos de rede do Kolo usam a kolo-codec: os vetores de teste oficiais e outras implementações exigem a codificação do RFC. Os envelopes próprios do Kolo em volta das mensagens MLS usam a kolo-codec. A única suíte de cifragem é a 0x0001, MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519, construída sobre crypto/hpke, crypto/ecdh, crypto/hkdf, crypto/ed25519, crypto/aes, crypto/cipher, crypto/sha256 e crypto/hmac, sem nenhuma primitiva nova. Os commits externos, as propostas externas e o ReInit são analisados e têm a sintaxe verificada, e depois a política os recusa com um erro tipado.

FormatoOndeConteúdo, em kolo-codec
Credencial do Kolo, tipo 0xF001 (cred)a credencial de uma folhaum uvarint de versão (0), o certificado de dispositivo da kolo-id como bytes e a assinatura de 64 bytes do dispositivo sobre o binding
Extensão de papéis, tipo 0xF002 (settle)uma extensão do GroupContextum uvarint de versão (0), o ID de grupo de 32 bytes do braid dos admins, um uvarint com a regra de quórum (1 Majority, 2 TwoThirds), e depois as chaves dos dispositivos admin e as dos dispositivos settler, cada uma com um contador e chaves de 32 bytes em ordem estritamente crescente
Envelope de geração (settle)os dados autenticados de cada PrivateMessage de um grupo do Koloum uvarint de versão (0), a geração como uvarint e os dados autenticados da aplicação como bytes
Commit assentado (settle)levado pela aplicação, e pinsa string kolo-mls/settled-commit/v0, a parte assinada descrita abaixo, um uvarint com o número de assinaturas e, para cada uma, a chave de dispositivo de 32 bytes do settler e a sua assinatura de 64 bytes, com as chaves em ordem estritamente crescente
Entradas do braid (braid)o braid dos adminsuma referência a um commit, um voto e uma parte de assinatura, abaixo

O binding que um dispositivo assina é um uvarint de versão (0), a suíte de cifragem como uvarint, a chave de assinatura MLS de 32 bytes da folha e o SHA-256 do certificado de dispositivo. A credencial tem no máximo 581 bytes (cred.MaxBody): uma versão (1), o tamanho do certificado (2), o maior certificado com o seu pai aprovador (514) e a assinatura (64). A chave do dispositivo nunca assina bytes do MLS por conta própria: cada folha tem a sua própria chave de assinatura MLS.

A parte assinada de um commit assentado é um uvarint de versão (0), o ID de grupo de 32 bytes como bytes, a época como uvarint, quatro valores de 32 bytes (o SHA-256 do MLSMessage do Commit, o do GroupContext da época, o do GroupContext da época seguinte e o ID de grupo do braid) e a posição assentada da referência do commit como uvarint. Cada settler a assina com a chave do seu dispositivo, e um membro aplica o commit só com assinaturas válidas de um quórum dos settlers da época.

As três entradas do braid começam com as strings kolo-mls/commit-ref/v0, kolo-mls/commit-vote/v0 e kolo-mls/commit-sig/v0 e levam como bytes o certificado de dispositivo de quem as escreve. Uma referência acrescenta o ID de grupo, a época e o SHA-256 do Commit. Um voto acrescenta o mesmo, o SHA-256 do contexto anterior, um bool (aceitar ou rejeitar) e um uvarint com o motivo. Uma parte de assinatura acrescenta a parte assinada acima e a assinatura de 64 bytes do settler. A kolo-log assina as entradas, como em qualquer entrada de um braid.

Nos pins, as chaves (settle.ObjectKey, SettledKey, TreeKey e ArchiveKey) começam com kolo-mls/object/ (um Commit, sob o SHA-256 em hexadecimal do seu MLSMessage), kolo-mls/settled/ e kolo-mls/tree/ (um commit assentado e um ratchet tree cifrado, cada um sob o ID de grupo em hexadecimal e a época) e kolo-mls/archive/ (as mensagens arquivadas de uma época, sob o ID de grupo em hexadecimal, a época e o SHA-256 em hexadecimal da mensagem). A árvore cifrada (settle.SealTree e settle.OpenTree) usa AES-128-GCM: a chave e o nonce são exportados da época (RFC 9420, seção 8.5) com os rótulos kolo-mls/ratchet-tree/v0 e kolo-mls/ratchet-tree-nonce/v0 e com a chave do dispositivo do admin que a cifra como contexto, o ID de grupo e a época são os dados adicionais, e o resultado é essa chave de dispositivo de 32 bytes seguida do texto cifrado.

Duas assinaturas são próprias do Kolo, cada uma com a sua própria string de contexto Ed25519ctx, então uma assinatura feita para um fim nunca é válida para outro: kolo-mls/leaf-key/v0 (cred.LeafKeyContext, a assinatura do dispositivo sobre o binding) e kolo-mls/commit-settled/v0 (settle.SettledContext, a assinatura de um settler sobre um commit assentado). Este esquema de assinaturas é design próprio do Kolo e não está em nenhum RFC.

As mensagens cifradas são preenchidas até o tamanho Padmé, no máximo cerca de 12% maiores (RFC 9420, seções 6.3 e 15.1).

Os key packages, as suas folhas e os welcomes levam valores GREASE aleatórios (RFC 9420, seção 13.5), para que os peers que recusam valores desconhecidos apareçam cedo, e os valores desconhecidos recebidos são ignorados onde a seção 13.4 manda. Uma implementação independente recusa uma extensão GREASE em uma folha, em um KeyPackage ou em um GroupInfo, contra as seções 13.4, 13.5 e 17.3 do RFC 9420, e por isso recusa estes key packages e welcomes. A kolo-mls segue o RFC.

Referência da API

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

Pacote kolomls · github.com/ciranda-dev/kolo-mls · v0.1.0

Package kolomls is group end-to-end encryption by the MLS standard (RFC 9420) for cipher suite 0x0001, on the Go standard library only. Packages cred, settle and braid add the Kolo credential, the rules of a Kolo group's member devices and its admins' side over kolo-braid; backendstore keeps groups in a kolo-store Backend.

A member makes a KeyPackage with NewKeyPackage and starts a group with Create. Group.Commit adds members, ApplyPending makes the Commit the new epoch, and each added member enters with Join from the Welcome and the ratchet tree. Group.Encrypt and Group.Process carry the messages. State lives in a Store the caller provides; NewMemStore is the in-memory one.

Experimental. The API may change before v1.0.0.

Constantes

const (
	// CredentialBasic is the type of a basic credential (RFC 9420 section 5.3).
	CredentialBasic = tree.CredentialBasic
	// CredentialX509 is the type of an x509 credential (RFC 9420 section 5.3).
	CredentialX509 = tree.CredentialX509
	// PSKExternal is the type of an external PSK (RFC 9420 section 8.4).
	PSKExternal = schedule.PSKExternal
	// PSKResumption is the type of a resumption PSK (RFC 9420 section 8.4).
	PSKResumption = schedule.PSKResumption
	// UsageApplication is the resumption usage for an application (RFC 9420 section 8.4).
	UsageApplication = schedule.UsageApplication
	// UsageBranch is the resumption usage for a branch (RFC 9420 section 8.4).
	UsageBranch = schedule.UsageBranch
	// DefaultOutOfOrderTolerance is the Config default for OutOfOrderTolerance.
	DefaultOutOfOrderTolerance = secrettree.DefaultOutOfOrderTolerance
	// DefaultMaxForwardDistance is the Config default for MaxForwardDistance.
	DefaultMaxForwardDistance = secrettree.DefaultMaxForwardDistance
)
const DefaultKeyPackageLifetime = 84 * 24 * time.Hour

DefaultKeyPackageLifetime is the default lifetime of a new KeyPackage, which starts one hour before its creation.

const DefaultMaxLeafLifetime = 84*24*time.Hour + time.Hour

DefaultMaxLeafLifetime is the default bound on not_after - not_before of a key_package leaf: 84 days and one hour.

const DefaultMaxTreeBytes = 128 << 20

DefaultMaxTreeBytes is the default bound on a ratchet tree a joiner accepts.

const DefaultPastEpochWindow = 10 * time.Second

DefaultPastEpochWindow is how long the previous epoch stays readable for late application messages after a Commit is applied.

Variáveis

var (
	// ErrMalformed reports input that is not the canonical encoding.
	ErrMalformed = errs.ErrMalformed
	// ErrTooLong reports a vector longer than a variable-size length can hold.
	ErrTooLong = errs.ErrTooLong
	// ErrInvalidArgument reports a key, size, index or count out of range.
	ErrInvalidArgument = errs.ErrInvalidArgument
	// ErrUnsupported reports a valid value this implementation does not support.
	ErrUnsupported = errs.ErrUnsupported
	// ErrDecrypt reports a failed decryption.
	ErrDecrypt = errs.ErrDecrypt
	// ErrInvalidTree reports a ratchet tree that breaks a rule of RFC 9420.
	ErrInvalidTree = errs.ErrInvalidTree
	// ErrInvalidCommit reports an UpdatePath or Commit that breaks a rule of RFC 9420.
	ErrInvalidCommit = errs.ErrInvalidCommit
	// ErrTooFarAhead reports a generation beyond the forward bound of a ratchet.
	ErrTooFarAhead = errs.ErrTooFarAhead
	// ErrTooOld reports a generation below the out-of-order window of a ratchet.
	ErrTooOld = errs.ErrTooOld
	// ErrReplay reports a generation whose key was already used.
	ErrReplay = errs.ErrReplay
	// ErrGenerationExhausted reports a ratchet that has used every generation.
	ErrGenerationExhausted = errs.ErrGenerationExhausted
	// ErrWrongGroup reports a message for another group.
	ErrWrongGroup = errs.ErrWrongGroup
	// ErrWrongEpoch reports a message for a past epoch.
	ErrWrongEpoch = errs.ErrWrongEpoch
	// ErrFutureEpoch reports a message for an epoch the group has not reached.
	ErrFutureEpoch = errs.ErrFutureEpoch
	// ErrSignature reports a signature that does not verify.
	ErrSignature = errs.ErrSignature
	// ErrMembershipTag reports a PublicMessage whose membership tag does not verify.
	ErrMembershipTag = errs.ErrMembershipTag
	// ErrConfirmationTag reports a confirmation tag that does not match.
	ErrConfirmationTag = errs.ErrConfirmationTag
	// ErrInvalidLeaf reports a LeafNode that breaks a rule of RFC 9420 section 7.3.
	ErrInvalidLeaf = errs.ErrInvalidLeaf
	// ErrInvalidKeyPackage reports a KeyPackage that breaks a rule of RFC 9420 section 10.1.
	ErrInvalidKeyPackage = errs.ErrInvalidKeyPackage
	// ErrInvalidProposal reports a proposal that breaks a rule of RFC 9420 section 12.1.
	ErrInvalidProposal = errs.ErrInvalidProposal
	// ErrInvalidWelcome reports a Welcome or GroupInfo that breaks a rule of RFC 9420 section 12.4.3.
	ErrInvalidWelcome = errs.ErrInvalidWelcome
	// ErrUnknownProposal reports a Commit that references a proposal this member does not hold.
	ErrUnknownProposal = errs.ErrUnknownProposal
	// ErrPSKNotFound reports a pre-shared key this member does not hold.
	ErrPSKNotFound = errs.ErrPSKNotFound
	// ErrKeyPackageNotFound reports a Welcome for none of this client's key packages.
	ErrKeyPackageNotFound = errs.ErrKeyPackageNotFound
	// ErrCredential wraps an error of the Authenticator.
	ErrCredential = errs.ErrCredential
	// ErrPolicy wraps an error of the Policy.
	ErrPolicy = errs.ErrPolicy
	// ErrPendingProposals reports application data sent while proposals are
	// cached: a Commit must come first (RFC 9420 section 12.4).
	ErrPendingProposals = errs.ErrPendingProposals
	// ErrPendingCommit reports a second pending Commit, or none where one is needed.
	ErrPendingCommit = errs.ErrPendingCommit
	// ErrRemoved reports a group this member was removed from.
	ErrRemoved = errs.ErrRemoved
	// ErrNotFound is what a Store returns for an absent key.
	ErrNotFound = errs.ErrNotFound
	// ErrStore wraps an error of the Store.
	ErrStore = errs.ErrStore
	// ErrGroupExists reports a group id this client already uses.
	ErrGroupExists = errs.ErrGroupExists
	// ErrUnknownSender reports a message from a leaf that is blank.
	ErrUnknownSender = errs.ErrUnknownSender
	// ErrClosed reports a Group used after Close.
	ErrClosed = errs.ErrClosed
)

Funções

func DeleteKeyPackage

func DeleteKeyPackage(st Store, keyPackage []byte) error

DeleteKeyPackage deletes the private keys of an unused KeyPackage of this client, given as an encoded MLSMessage.

func NewKeyPackage

func NewKeyPackage(st Store, o KeyPackageOptions) ([]byte, error)

NewKeyPackage creates a KeyPackage with fresh init and leaf keys, stores its private keys in st for Join, and returns it as an encoded MLSMessage (RFC 9420 section 10). It seeds one group: Create and Join that use it must not run concurrently.

Tipos

type Authenticator

type Authenticator interface {
	// Validate checks that c is valid and binds signatureKey, a copy.
	Validate(c Credential, signatureKey []byte, ev Event) error
	// Successor checks that next may replace prev in a member's leaf.
	Successor(prev, next Credential) error
	// ClientID returns the identity of the client c presents; two leaves
	// with equal ids are the same client (RFC 9420 section 12.2).
	ClientID(c Credential) ([]byte, error)
}

Authenticator is the application's Authentication Service (RFC 9420 section 5.3.1). Its answers must be the same on every member, since members that decide differently split the group (RFC 9750 section 6.5).

type Batch

type Batch struct {
	Put    []KV
	Delete [][]byte
}

Batch is a set of writes that a Store applies atomically: the deletes, then the puts. No key is in both.

type Capabilities

type Capabilities = tree.Capabilities

Capabilities are the versions, cipher suites, extensions, proposals and credential types a leaf supports (RFC 9420 section 7.2).

type CommitOptions

type CommitOptions struct {
	// Add are the KeyPackages to add, each an encoded KeyPackage.
	Add [][]byte
	// Remove are the leaf indices to remove.
	Remove []uint32
	// PSKs are pre-shared keys to inject; a nil nonce means 32 random bytes.
	PSKs []*PSKID
	// Extensions are the new GroupContext extensions when SetExtensions is
	// set.
	Extensions []Extension
	// SetExtensions adds a GroupContextExtensions proposal with Extensions,
	// which may be empty.
	SetExtensions bool
	// References are the ProposalRefs of cached proposals to include.
	References [][]byte
	// NoPath omits the UpdatePath where RFC 9420 section 12.4 allows it; it
	// excludes Leaf and SignatureKey.
	NoPath bool
	// Leaf is a template for the committer's new leaf (credential,
	// capabilities, extensions, signature key); nil keeps the current one.
	Leaf *LeafNode
	// SignatureKey is the private key of Leaf.SignatureKey when it changes.
	SignatureKey ed25519.PrivateKey
	// RatchetTree puts the ratchet_tree extension in the GroupInfo.
	RatchetTree bool
	// AuthenticatedData is the Commit's authenticated_data.
	AuthenticatedData []byte
}

CommitOptions say what a Commit carries besides the cached proposals it includes by reference.

type CommitView

type CommitView struct {
	// Committer is the leaf index of the committer.
	Committer uint32
	// CommitterLeaf is the committer's current leaf.
	CommitterLeaf *LeafNode
	// Proposals are the committed proposals in order.
	Proposals []ProposalView
	// Path is the committer's new leaf, nil without a path.
	Path *LeafNode
	// Context is the GroupContext of the epoch the Commit is sent in.
	Context *GroupContext
	// Tree is the tree of that epoch.
	Tree TreeView
}

CommitView is a Commit as the Policy sees it, before it is applied; every field is a copy or a read-only view.

type Config

type Config struct {
	// Authenticator validates credentials; it is required.
	Authenticator Authenticator
	// Policy adds the application's rules; it is required.
	Policy Policy
	// PSKs returns pre-shared keys; nil means none is available.
	PSKs PSKStore
	// MaxLeafLifetime bounds the lifetime of key_package leaves; zero means
	// DefaultMaxLeafLifetime and a negative value no bound.
	MaxLeafLifetime time.Duration
	// Now gives the time for the lifetime check of leaves this member sends
	// and for the previous-epoch window; nil means time.Now.
	Now func() time.Time
	// ResumptionPSKs is the number of past epochs whose resumption PSK is
	// kept besides the current one; zero keeps the current one only and a
	// negative value is refused.
	ResumptionPSKs int
	// OutOfOrderTolerance is the size of the window of generations a
	// receiver keeps per sender and ratchet, the newest one read included,
	// so OutOfOrderTolerance - 1 older generations stay readable (RFC 9420
	// section 15.3); zero means DefaultOutOfOrderTolerance, 1
	// reads messages in order only, and values above 65536 (1 << 16) are
	// refused.
	OutOfOrderTolerance uint32
	// MaxForwardDistance is how many generations one message may move a
	// sender's ratchet forward (RFC 9420 section 15.3); zero means
	// DefaultMaxForwardDistance, so the smallest bound is 1, and values above
	// 65536 (1 << 16) are refused.
	MaxForwardDistance uint32
	// PastEpochWindow is how long the previous epoch stays readable for late
	// application messages of members that stay, after a Commit is applied
	// (RFC 9420 section 12.4.2); zero means DefaultPastEpochWindow and a
	// negative value keeps no previous epoch. Now is its clock; the caller
	// calls Group.ExpirePastEpoch when the window ends.
	PastEpochWindow time.Duration
	// PrivateHandshakes sends proposals and Commits as PrivateMessage and
	// refuses those of other members sent as PublicMessage; otherwise they
	// are sent as PublicMessage and both are accepted.
	PrivateHandshakes bool
	// Envelope wraps and checks the authenticated data of every
	// PrivateMessage. Nil leaves it unchanged, as the RFC test vectors
	// need, and then a member can replay another member's signed content
	// under a later generation and use up that generation (RFC 9750 section
	// 8.6); applications set one.
	Envelope Envelope
}

Config holds the parameters every operation of a group uses. For the bounds, zero means the default and a negative value no bound.

type CreateOptions

type CreateOptions struct {
	Config
	// GroupID is the new group's id; nil means 32 random bytes (RFC 9420
	// section 11).
	GroupID []byte
	// KeyPackage is a KeyPackage of this client made by NewKeyPackage on the
	// same Store; its leaf becomes the creator's leaf and Create deletes its
	// private keys, as Join does, so no Join may use it at the same time.
	KeyPackage []byte
	// Extensions are the GroupContext extensions of epoch 0.
	Extensions []Extension
}

CreateOptions are the parameters of Create.

type Credential

type Credential = tree.Credential

Credential is an MLS Credential (RFC 9420 section 5.3): Type, with Identity for a basic or Kolo credential and Certificates for an x509 chain.

type Envelope

type Envelope interface {
	// Wrap returns the authenticated data to send at generation gen for the
	// application's aad.
	Wrap(gen uint32, aad []byte) ([]byte, error)
	// Unwrap checks the authenticated data of a PrivateMessage received at
	// generation gen, before its key is consumed, and returns the
	// application's aad.
	Unwrap(gen uint32, authenticatedData []byte) ([]byte, error)
}

Envelope binds the generation of a PrivateMessage into its signed authenticated data (RFC 9750 section 8.6: the signature does not cover the generation, so a member could re-encrypt another member's content under a new one).

type Event

type Event uint8

Event names the moment a credential is checked (RFC 9420 section 5.3.1).

const (
	// EventKeyPackage is a KeyPackage's leaf, checked before this member
	// adds it or creates a group with it.
	EventKeyPackage Event = iota + 1
	// EventJoin is a leaf of the tree of a group this member joins.
	EventJoin
	// EventAdd is a leaf added by another member's Commit.
	EventAdd
	// EventUpdate is a leaf in an Update proposal.
	EventUpdate
	// EventCommitPath is the leaf of a Commit's UpdatePath.
	EventCommitPath
)

Credential events.

type Extension

type Extension = tls.Extension

Extension is an MLS Extension (RFC 9420 section 13.4): Type and Data.

type Group

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

Group is one member's view of an MLS group. It is not safe for concurrent use, and at most one Group per group id may be open on a Store; every change is one Store batch.

func Create
func Create(st Store, o CreateOptions) (*Group, error)

Create starts a group with this member alone at epoch 0 (RFC 9420 section 11). Create of one group id must not run concurrently with another Create, Join or Open of it on the same Store, nor with a Create or Join that uses the same KeyPackage, or both may seed a group with it.

func Join
func Join(st Store, welcomeMsg, ratchetTree []byte, o JoinOptions) (*Group, error)

Join processes a Welcome with this client's stored KeyPackage and joins the group (RFC 9420 section 12.4.3.1). ratchetTree is the encoded tree when the Welcome's GroupInfo does not carry it. Join of one group id must not run concurrently with another Create, Join or Open of it on the same Store, nor with a Create or Join that uses the same KeyPackage.

func Open
func Open(st Store, gid []byte, cfg Config) (*Group, error)

Open loads group gid from st. Only one Group per group id may be open at a time; after a failed write, Open reads what the Store holds.

func (Group) Apply
func (g *Group) Apply(sc *StagedCommit) error

Apply makes a staged Commit the current epoch in one Store batch that also deletes the old epoch and any pending Commit (RFC 9420 sections 9.2, 14). A Commit that removes this member deletes the group's records instead: Apply returns nil, Removed reports true and every later call returns ErrRemoved. A Commit that is not applied is discarded.

func (Group) ApplyPending
func (g *Group) ApplyPending() error

ApplyPending makes this member's pending Commit the current epoch, once the Delivery Service has chosen it (RFC 9420 section 14).

func (Group) BranchPSK
func (g *Group) BranchPSK() (*PSKID, []byte, error)

BranchPSK returns the id and value of the resumption PSK of the current epoch with usage branch and a fresh nonce, for the first Commit of a successor group and its joiners (RFC 9420 section 11.3).

func (Group) CachedProposals
func (g *Group) CachedProposals() [][]byte

CachedProposals returns the references of the proposals cached in this epoch, this member's own included, in the order they arrived.

func (Group) Close
func (g *Group) Close()

Close zeroes the secrets this Group holds in memory. Later calls that use a secret or change the group (Process, Apply, Commit, the Propose calls, Encrypt, Export, EpochAuthenticator, RatchetTree, ApplyPending, DiscardPending) return ErrClosed; GroupID, Epoch, OwnLeaf, GroupContext, Extensions and Tree, which hold no secret, keep returning the last epoch's values, CachedProposals is empty and Pending is nil.

func (Group) Commit
func (g *Group) Commit(o CommitOptions) (*PendingCommit, error)

Commit creates a Commit of o and its Welcome (RFC 9420 section 12.4.1), stored apart until ApplyPending or DiscardPending; the group's state does not change.

func (Group) DiscardPending
func (g *Group) DiscardPending() error

DiscardPending deletes this member's pending Commit, when the Delivery Service chose another one (RFC 9420 section 14).

func (Group) Encrypt
func (g *Group) Encrypt(data, aad []byte) ([]byte, error)

Encrypt protects application data as a PrivateMessage of the current epoch, with aad as its authenticated data (RFC 9420 section 6.3). It is refused while proposals are cached: a Commit comes first (RFC 9420 section 12.4).

func (Group) Epoch
func (g *Group) Epoch() uint64

Epoch returns the current epoch.

func (Group) EpochAuthenticator
func (g *Group) EpochAuthenticator() ([]byte, error)

EpochAuthenticator returns the epoch authenticator (RFC 9420 section 8.7).

func (Group) ExpirePastEpoch
func (g *Group) ExpirePastEpoch() (time.Time, error)

ExpirePastEpoch deletes the previous epoch once its window has ended at Config.Now, and returns when the window of the one still kept ends, the zero time when none is kept. The library has no timers: the caller calls it again at that time.

func (Group) Export
func (g *Group) Export(label string, context []byte, length int) ([]byte, error)

Export derives an exported secret (RFC 9420 section 8.5).

func (Group) Extensions
func (g *Group) Extensions() []Extension

Extensions returns a copy of the GroupContext extensions of the current epoch.

func (Group) GroupContext
func (g *Group) GroupContext() []byte

GroupContext returns the encoded GroupContext of the current epoch.

func (Group) GroupID
func (g *Group) GroupID() []byte

GroupID returns the group id.

func (Group) OwnLeaf
func (g *Group) OwnLeaf() uint32

OwnLeaf returns this member's leaf index.

func (Group) PeekSender
func (g *Group) PeekSender(msg []byte) (leaf, generation uint32, err error)

PeekSender returns the sender's leaf and generation named in the sender data of a PrivateMessage of the current epoch, which uses up no key and proves nothing: anyone who holds the epoch's secrets can write it. Catch-up reads archived messages in this order.

func (Group) Pending
func (g *Group) Pending() *PendingCommit

Pending returns the stored pending Commit, nil when there is none.

func (Group) PendingLeaves
func (g *Group) PendingLeaves() []*LeafNode

PendingLeaves returns copies of the leaves that the pending Commit adds or replaces, nil when there is no pending Commit.

func (Group) Process
func (g *Group) Process(msg []byte) (*Result, error)

Process verifies a message of the current epoch: a proposal is cached, a Commit is staged and changes nothing until Apply, and application data is returned. A PrivateMessage uses up its key only once its signature and the Envelope accepted it, in the same Store batch as the proposal; a Commit's key is deleted with its epoch by Apply.

func (Group) ProposeAdd
func (g *Group) ProposeAdd(keyPackage []byte) ([]byte, error)

ProposeAdd proposes to add the client of an encoded KeyPackage.

func (Group) ProposeGroupContextExtensions
func (g *Group) ProposeGroupContextExtensions(exts []Extension) ([]byte, error)

ProposeGroupContextExtensions proposes to replace the GroupContext extensions.

func (Group) ProposePSK
func (g *Group) ProposePSK(id *PSKID) ([]byte, error)

ProposePSK proposes to inject a pre-shared key; nonce nil means 32 random bytes (RFC 9420 section 12.1.4).

func (Group) ProposeRemove
func (g *Group) ProposeRemove(leaf uint32) ([]byte, error)

ProposeRemove proposes to remove the member at leaf.

func (Group) ProposeUpdate
func (g *Group) ProposeUpdate(template *LeafNode) ([]byte, error)

ProposeUpdate proposes to replace this member's leaf with a fresh encryption key; template, when not nil, gives a new credential, capabilities or extensions with the same signature key.

func (Group) RatchetTree
func (g *Group) RatchetTree() ([]byte, error)

RatchetTree returns the encoded ratchet tree of the current epoch.

func (Group) Removed
func (g *Group) Removed() bool

Removed reports whether an applied Commit removed this member.

func (Group) Tree
func (g *Group) Tree() TreeView

Tree returns a read-only view of the ratchet tree of the current epoch.

type GroupContext

type GroupContext = schedule.GroupContext

GroupContext is the decoded GroupContext of an epoch (RFC 9420 section 8.1).

type JoinOptions

type JoinOptions struct {
	Config
	// MaxTreeBytes bounds the encoded ratchet tree, from the Welcome or
	// given; zero means DefaultMaxTreeBytes and a negative value no bound.
	MaxTreeBytes int
	// Tree, when Join is given no tree and the Welcome carries none, returns
	// the encoded ratchet tree; export derives a secret of the new epoch
	// (RFC 9420 section 8.5), for a tree kept encrypted under it.
	Tree func(export func(label string, context []byte, length int) ([]byte, error)) ([]byte, error)
}

JoinOptions are the parameters of Join.

type JoinView

type JoinView struct {
	// Context is the GroupContext of the group joined.
	Context *GroupContext
	// Tree is the group's tree.
	Tree TreeView
	// Signer is the leaf index of the member that signed the GroupInfo.
	Signer uint32
	// PSKs are the pre-shared keys of the Welcome.
	PSKs []*PSKID
	// InfoExtensions are the GroupInfo's extensions.
	InfoExtensions []Extension
}

JoinView is a group as the Policy sees it before a member joins it; every field is a copy or a read-only view.

type KV

type KV struct {
	Key, Value []byte
}

KV is one key and value of a Batch.

type KeyPackageOptions

type KeyPackageOptions struct {
	// Credential is the client's credential.
	Credential Credential
	// SignatureKey signs the KeyPackage; its public key goes in the leaf.
	SignatureKey ed25519.PrivateKey
	// Capabilities of the leaf; version mls10, the cipher suite and the
	// credential's type are added when missing.
	Capabilities Capabilities
	// LeafExtensions and Extensions are the leaf's and the KeyPackage's.
	LeafExtensions []Extension
	Extensions     []Extension
	// Lifetime is the time from now to the end of validity, which starts one
	// hour before now; zero means DefaultKeyPackageLifetime.
	Lifetime time.Duration
	// Now gives the current time; nil means time.Now.
	Now func() time.Time
}

KeyPackageOptions are the parameters of NewKeyPackage.

type LeafNode

type LeafNode = tree.LeafNode

LeafNode is a member's leaf in the ratchet tree (RFC 9420 section 7.2).

type MemStore

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

MemStore is a Store in memory, the reference for the Store contract and for tests; it copies every key and value, zeroes what it drops, and is safe for concurrent use.

func NewMemStore
func NewMemStore() *MemStore

NewMemStore returns an empty MemStore.

func (MemStore) Apply
func (s *MemStore) Apply(b Batch) error

Apply applies the deletes, then the puts, of b; it refuses a batch with a key in both, which the Batch contract forbids.

func (MemStore) Clone
func (s *MemStore) Clone() *MemStore

Clone returns a copy of s, as a disk image of it would hold.

func (MemStore) Get
func (s *MemStore) Get(key []byte) ([]byte, error)

Get returns a copy of the value of key, or ErrNotFound.

type PSKID

type PSKID = schedule.PSKID

PSKID is a PreSharedKeyID (RFC 9420 section 8.4): ID for an external PSK; Usage, GroupID and Epoch for a resumption PSK.

type PSKStore

type PSKStore interface {
	// PSK returns a copy of the value of id, which the caller owns and
	// zeroes, or ErrNotFound.
	PSK(id *PSKID) ([]byte, error)
}

PSKStore holds the external and resumption pre-shared keys the application provides.

type PendingCommit

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

PendingCommit is this member's Commit, stored apart from the group's state until ApplyPending or DiscardPending (RFC 9420 section 14).

func (PendingCommit) Commit
func (pc *PendingCommit) Commit() []byte

Commit returns the Commit as an encoded MLSMessage.

func (PendingCommit) GroupContext
func (pc *PendingCommit) GroupContext() []byte

GroupContext returns the encoded GroupContext of the epoch the Commit starts.

func (PendingCommit) RatchetTree
func (pc *PendingCommit) RatchetTree() ([]byte, error)

RatchetTree returns the encoded ratchet tree of the epoch the Commit starts, for a Welcome whose tree goes out of band (RFC 9420 section 12.4.3.3).

func (PendingCommit) Welcome
func (pc *PendingCommit) Welcome() []byte

Welcome returns the Welcome for the added members as an encoded MLSMessage, nil when the Commit adds nobody.

type Policy

type Policy interface {
	// CheckProposal decides whether a received proposal is cached.
	CheckProposal(v ProposalView) error
	// CheckCommit decides whether a Commit is acceptable.
	CheckCommit(v CommitView) error
	// CheckJoin decides whether a Welcome is accepted, including the
	// membership checks of a branch (RFC 9420 section 12.4.3.1).
	CheckJoin(v JoinView) error
}

Policy holds the application's rules on top of RFC 9420 (section 12.2: "An application may extend the above procedure by additional rules"). Like the Authenticator, it must decide the same way on every member.

type Proposal

type Proposal = message.Proposal

Proposal is a decoded proposal (RFC 9420 section 12.1); the field of its Type is set.

type ProposalView

type ProposalView struct {
	// Sender is the leaf index of the proposer.
	Sender uint32
	// SenderLeaf is the proposer's current leaf.
	SenderLeaf *LeafNode
	// Proposal is the proposal itself.
	Proposal *Proposal
	// ByReference is set for a proposal a Commit includes by reference.
	ByReference bool
	// Cached is the number of proposals already cached in the epoch, so a
	// Policy can bound the cache; it is zero inside a CommitView.
	Cached int
	// Tree is the tree of the epoch the proposal is sent in.
	Tree TreeView
	// FromSender is the number of proposals of the same sender already
	// cached; zero inside a CommitView.
	FromSender int
	// Extensions are the GroupContext extensions of the epoch.
	Extensions []Extension
}

ProposalView is a proposal as the Policy sees it; every field is a copy.

type Result

type Result struct {
	// Epoch is the epoch of the message: the current one, or the previous
	// one for a late application message read inside the window.
	Epoch uint64
	// Sender is the leaf index of the sender.
	Sender uint32
	// ProposalRef is the reference of a proposal now cached.
	ProposalRef []byte
	// Commit is a Commit ready to Apply.
	Commit *StagedCommit
	// Application is the data of an application message.
	Application []byte
	// AuthenticatedData is the authenticated data of an application
	// message, as the Envelope returns it when one is set.
	AuthenticatedData []byte
}

Result is what Process found in a message: a cached proposal, a staged Commit or application data.

type StagedCommit

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

StagedCommit is another member's verified Commit; nothing changes until Apply (RFC 9420 section 14).

func (StagedCommit) Added
func (sc *StagedCommit) Added() []uint32

Added returns the leaf indices the Commit adds.

func (StagedCommit) Committer
func (sc *StagedCommit) Committer() uint32

Committer returns the committer's leaf index.

func (StagedCommit) Discard
func (sc *StagedCommit) Discard()

Discard zeroes the secrets of a Commit that will not be applied.

func (StagedCommit) Extensions
func (sc *StagedCommit) Extensions() []Extension

Extensions returns the GroupContext extensions of the new epoch, also when the Commit removes this member.

func (StagedCommit) GroupContext
func (sc *StagedCommit) GroupContext() []byte

GroupContext returns the encoded GroupContext of the new epoch, nil when this member is removed.

func (StagedCommit) Leaves
func (sc *StagedCommit) Leaves() []*LeafNode

Leaves returns copies of the leaves of the new tree that the Commit adds or replaces, nil when it removes this member.

func (StagedCommit) Removed
func (sc *StagedCommit) Removed() []uint32

Removed returns the leaf indices the Commit removes, in increasing order.

func (StagedCommit) RemovesSelf
func (sc *StagedCommit) RemovesSelf() bool

RemovesSelf reports whether the Commit removes this member.

type Store

type Store interface {
	// Get returns a copy of the value of key, which the caller owns, or
	// ErrNotFound.
	Get(key []byte) ([]byte, error)
	// Apply writes b atomically and durably and keeps none of its slices:
	// the library zeroes the values after Apply returns.
	Apply(b Batch) error
}

Store persists the state of groups and KeyPackages. Every consumed secret is deleted in the same write that records the advance (RFC 9420 section 9.2).

Apply must be atomic and durable: all of a batch or nothing. An error from Apply may still mean the batch was written (an acknowledgement lost), so a Group whose write failed refuses every later call, and the caller opens the group again to read what the Store holds. After a failed Create or Join, the caller opens the group id to learn whether it exists.

A Store serves several groups and goroutines and must be safe for concurrent use (MemStore is). At most one Group may be open per group id, since two would write diverging secret trees, and Create, Join and Open of one group id, or Create and Join that use one KeyPackage, must not run concurrently on one Store.

type TreeView

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

TreeView reads a ratchet tree without changing it.

func (TreeView) Leaf
func (v TreeView) Leaf(l uint32) *LeafNode

Leaf returns a copy of the leaf at index l, nil when it is blank or past the tree.

func (TreeView) Members
func (v TreeView) Members() []uint32

Members returns the indices of the non-blank leaves in increasing order.

Pacote cred

github.com/ciranda-dev/kolo-mls/cred

Package cred is the Kolo credential of an MLS leaf: credential type 0xF001 with a kolo-id device certificate and the device's signature over the leaf's MLS signature key, and the Authenticator that checks it (RFC 9420 section 5.3).

Constantes

const DefaultMaxCached = 1 << 19

DefaultMaxCached is the default bound on the client ids an Authenticator caches: more than the leaves of the largest tree a joiner accepts by default (kolomls.DefaultMaxTreeBytes over the smallest Kolo leaf, measured by TestCacheBound).

const LeafKeyContext = "kolo-mls/leaf-key/v0"

LeafKeyContext is the context of the device's signature over a leaf's MLS signature key.

const MaxBody = 1 + 2 + maxCert + ed25519.SignatureSize

MaxBody is the largest credential body: version, the certificate with its length and the signature.

const Type = tree.CredentialKoloDevice

Type is the credential type 0xF001 of a Kolo device, from the private-use range of RFC 9420 section 17.5.

Variáveis

var ErrCredential = errors.New("kolomls: invalid Kolo credential")

ErrCredential reports a Kolo credential that does not decode or verify; kolo-id's errors are wrapped.

Funções

func Binding
func Binding(signatureKey []byte, cert *koloid.DeviceCert) []byte

Binding returns the bytes the device signs for a leaf: the version, the cipher suite, the MLS signature key and the hash of the certificate, so a signature cannot move to another certificate of the same device key.

func New
func New(device *koloid.Identity, cert *koloid.DeviceCert, signatureKey ed25519.PublicKey) (kolomls.Credential, error)

New returns the credential of device, certified by cert, for a leaf with signatureKey, signed by the device key.

func Revoked
func Revoked(c kolomls.Credential, revs []*koloid.Revocation) error

Revoked returns an error wrapping koloid.ErrCertRevoked when one of revs covers the certificate chain of c, nil otherwise; it does not check expiry. Settlers call it with the revocations at a settled position, so they decide alike (RFC 9750 section 6.5).

Tipos

type Authenticator
type Authenticator struct {
	// Expect is the application's check of the person and device a leaf
	// presents (the reference identifier of RFC 9420 section 5.3.1); nil
	// accepts any person. It must answer the same on every member.
	Expect func(person, device ed25519.PublicKey, ev kolomls.Event) error
	// Revocations returns the revocations held for device of person, checked
	// when this member adds a KeyPackage (kolomls.EventKeyPackage); nil holds
	// none. Receivers do not check them in Validate, so that every member
	// decides alike; see Revoked.
	Revocations func(person, device ed25519.PublicKey) []*koloid.Revocation
	// Now is the clock of the expiry check when this member adds a
	// KeyPackage; required for that check.
	Now func() time.Time
	// MaxCached bounds the client ids kept; zero means DefaultMaxCached. The
	// cache is emptied when it is full.
	MaxCached int
	// contains filtered or unexported fields
}

Authenticator checks Kolo credentials for the core (RFC 9420 section 5.3.1). Its fields are set before first use; it is safe for concurrent use.

func (Authenticator) ClientID
func (a *Authenticator) ClientID(c kolomls.Credential) ([]byte, error)

ClientID returns the device key: two leaves of one device are the same client.

func (Authenticator) Successor
func (a *Authenticator) Successor(prev, next kolomls.Credential) error

Successor checks that next keeps the person and the device of prev; the certificate and the MLS signature key may change (RFC 9420 section 5.3.1).

func (Authenticator) Validate
func (a *Authenticator) Validate(c kolomls.Credential, signatureKey []byte, ev kolomls.Event) error

Validate checks that c is a Kolo credential of a valid certificate chain whose device signed signatureKey for this cipher suite, and asks Expect.

type Credential
type Credential struct {
	// Cert is the device certificate; trusted only after Validate.
	Cert *koloid.DeviceCert
	// Signature is the device's signature over the binding.
	Signature []byte
}

Credential is a decoded Kolo credential.

func Decode
func Decode(c kolomls.Credential) (*Credential, error)

Decode decodes a Kolo credential, checking its structure but no signature.

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

Device returns the certified device key, nil without a certificate.

func (Credential) Encode
func (c *Credential) Encode() kolomls.Credential

Encode returns c as an MLS Credential, an empty one without a certificate.

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

Person returns the person key the certificate names, an unverified claim; nil without a certificate.

Pacote settle

github.com/ciranda-dev/kolo-mls/settle

Package settle holds the Kolo rules every member device of a Kolo group needs: the roles extension, the commit Policy, the authenticated data envelope, the settled-commit signatures and the decision of each epoch's Commit over the settled order of the admins' braid.

Constantes

const (
	DefaultMaxBufferedBytes = 16 << 20
	DefaultMaxCatchUpBytes  = 16 << 20
	DefaultMaxCommitBytes   = kolomls.DefaultMaxTreeBytes
)

Default bounds of a Member: 16 MiB, the bound the admins' braid puts on entries that wait for an earlier one; a Commit at most the tree bound, since the KeyPackages it adds become the tree's leaves.

const RolesExtension uint16 = 0xF002

RolesExtension is the GroupContext extension type of the roles, from the private-use range of RFC 9420 section 17.3.

const SettledContext = "kolo-mls/commit-settled/v0"

SettledContext is the context of a settler's signature over a decided Commit.

Variáveis

var (
	// ErrBuffered reports a message of the next epoch, kept until the
	// Commit that starts that epoch is applied.
	ErrBuffered = errors.New("kolomls: message of the next epoch kept for later")
	// ErrRevokedSender reports an application message of a leaf whose
	// certificate this device holds a revocation for; it is dropped.
	ErrRevokedSender = errors.New("kolomls: message of a revoked device dropped")
	// ErrHalted reports a Member that stopped on an equivocation; it stays
	// stopped after it is opened again.
	ErrHalted = errors.New("kolomls: member halted")
	// ErrCatchUp reports archived messages of an epoch that catch-up could
	// not read: a value past the bound, one that does not match its key or
	// does not open, or a listing that pins got wrong. The epoch is still
	// applied.
	ErrCatchUp = errors.New("kolomls: epoch archive refused")
	// ErrNotHeld reports a leave request received by a device that is not
	// an admin; it is dropped, as only admins commit it.
	ErrNotHeld = errors.New("kolomls: leave requests are held by admins only")
)
var (
	// ErrMissing reports a value that Pins does not hold.
	ErrMissing = errors.New("kolomls: not on pins")
	// ErrPinTooLarge reports a value on pins past the bound asked for.
	ErrPinTooLarge = errors.New("kolomls: pinned data past the bound")
)
var (
	// ErrNotSettled reports a SettledCommit that does not settle the Commit
	// given in this member's epoch: malformed, for another group, epoch,
	// context or Commit, or with fewer than q valid settler signatures.
	ErrNotSettled = errors.New("kolomls: commit not settled")
	// ErrSettledMismatch reports a settled Commit that this member cannot
	// follow: it fails MLS processing or leads to another GroupContext than
	// the settlers signed. The member keeps its state.
	ErrSettledMismatch = errors.New("kolomls: settled commit does not match")
	// ErrEquivocation reports two settled Commits for one epoch.
	ErrEquivocation = errors.New("kolomls: two settled commits for one epoch")
)
var ErrEnvelope = errors.New("kolomls: invalid authenticated data envelope")

ErrEnvelope reports authenticated data that is not a Kolo envelope of the message's generation.

var ErrRoles = errors.New("kolomls: invalid roles extension")

ErrRoles reports a roles extension that does not decode or breaks a rule.

var ErrRule = errors.New("kolomls: Kolo group rule")

ErrRule reports a proposal, Commit or Welcome that breaks a rule of Kolo groups (RFC 9420 section 12.2: "An application may extend the above procedure by additional rules").

var ErrSealedTree = errors.New("kolomls: encrypted tree does not open")

ErrSealedTree reports an encrypted tree that does not open.

Funções

func ArchiveKey
func ArchiveKey(gid []byte, epoch uint64, msg []byte) string

ArchiveKey is the key of an archived message of epoch of group gid.

func ArchivePrefix
func ArchivePrefix(gid []byte, epoch uint64) string

ArchivePrefix is the prefix of the archived messages of epoch of group gid: the messages sent in it.

func Capabilities
func Capabilities() kolomls.Capabilities

Capabilities returns the capabilities every Kolo leaf lists besides the version and the cipher suite.

func GetObject
func GetObject(ctx context.Context, p Pins, h [32]byte, max int) ([]byte, error)

GetObject returns the MLSMessage with SHA-256 h, at most max bytes, from pins, checking the hash.

func GroupExtensions
func GroupExtensions(r *Roles) ([]kolomls.Extension, error)

GroupExtensions returns the GroupContext extensions of a Kolo group: required_capabilities naming the Kolo credential and the roles extension (RFC 9420 section 11.1), and the roles.

func NewConfig
func NewConfig(a *cred.Authenticator, p *Policy, now func() time.Time) kolomls.Config

NewConfig returns the configuration of a Kolo group with a and p: the Kolo credential and Policy, handshakes as PrivateMessage, the envelope, and the clock now, which the Kolo layer requires.

func ObjectKey
func ObjectKey(h [32]byte) string

ObjectKey is the key of a Commit MLSMessage with SHA-256 h.

func OpenTree
func OpenTree(export func(label string, context []byte, length int) ([]byte, error), gid []byte, epoch uint64, sealed []byte) ([]byte, error)

OpenTree decrypts a tree sealed by SealTree for epoch of group gid with the exporter of that epoch.

func PutObject
func PutObject(ctx context.Context, p Pins, msg []byte) ([32]byte, error)

PutObject keeps an MLSMessage under its hash and returns the hash.

func Seal
func Seal(export func(label string, context []byte, length int) ([]byte, error), gid []byte, epoch uint64, sealer [32]byte, tree []byte) ([]byte, error)

Seal is SealTree for a tree of epoch of group gid, sealed by device sealer with the epoch's exporter.

func SealTree
func SealTree(m *Member) ([]byte, error)

SealTree returns the ratchet tree of m's epoch encrypted with AES-128-GCM (docs/design.md, "The Kolo layer"): the key and nonce are exported from the epoch (RFC 9420 section 8.5) for this sealer's device key, which leads the result, and the group id and epoch are the additional data. Two sealers never share a key, so a sealer that seals another tree reuses only its own nonce.

func SettledKey
func SettledKey(gid []byte, epoch uint64) string

SettledKey is the key of the SettledCommit of epoch of group gid.

func TreeKey
func TreeKey(gid []byte, epoch uint64) string

TreeKey is the key of the encrypted ratchet tree of epoch of group gid.

Tipos

type BranchPSK
type BranchPSK struct {
	GroupID []byte
	Epoch   uint64
	Value   []byte
	// contains filtered or unexported fields
}

BranchPSK serves the resumption PSK of a group's last epoch, with usage branch, to the first Commit of its successor group and to its joiners (RFC 9420 section 11.3).

func (BranchPSK) ID
func (b *BranchPSK) ID() *kolomls.PSKID

ID returns the PSK id with its nonce, for the successor's first Commit; nil for a BranchPSK not made by Member.BranchPSK.

func (BranchPSK) PSK
func (b *BranchPSK) PSK(id *kolomls.PSKID) ([]byte, error)

PSK returns a copy of the value for the branch PSK of GroupID and Epoch.

type Envelope
type Envelope struct{}

Envelope binds the generation of every PrivateMessage into its signed authenticated data: uvarint version 0, uvarint generation, bytes(aad) (RFC 9750 section 8.6: a member cannot replay another member's content under a new generation).

func (Envelope) Unwrap
func (Envelope) Unwrap(gen uint32, ad []byte) ([]byte, error)

Unwrap checks that ad is the envelope of generation gen and returns the application's aad.

func (Envelope) Wrap
func (Envelope) Wrap(gen uint32, aad []byte) ([]byte, error)

Wrap returns the authenticated data of generation gen for aad.

type Limits
type Limits struct {
	MaxAdmins, MaxSettlers int
}

Limits cap what a roles extension may hold; zero or less is no cap, and then only the size of the extension bounds the counts.

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

Member is one device's side of a Kolo group: it applies only settled Commits (docs/design.md, "The Kolo layer"). It is not safe for concurrent use.

func CreateMember
func CreateMember(st kolomls.Store, co kolomls.CreateOptions, mo MemberOptions) (*Member, error)

CreateMember creates a Kolo group; co.KeyPackage is made on st and co.Extensions must be GroupExtensions of the group's roles.

func JoinMember
func JoinMember(st kolomls.Store, welcome, settled []byte, sealedTree func(gid []byte, epoch uint64, max int) ([]byte, error), o kolomls.JoinOptions, mo MemberOptions) (*Member, error)

JoinMember joins with a Welcome and the SettledCommit of its Commit; sealedTree returns the epoch's encrypted tree (SealTree).

func OpenMember
func OpenMember(st kolomls.Store, gid []byte, cfg kolomls.Config, o MemberOptions) (*Member, error)

OpenMember opens the stored group gid with a configuration made by NewConfig; a Member that halted is refused with ErrHalted.

func (Member) AppliedLeaves
func (m *Member) AppliedLeaves() []*kolomls.LeafNode

AppliedLeaves returns copies of the leaves that the Commit this Member applied last added or replaced, with their credentials and signature keys; it is nil before the first Commit and when that Commit removed this device. A Commit is a PrivateMessage, so these leaves can be read only while their epoch is the current one (in OnEpoch or right after ApplySettled) and are not kept across OpenMember.

func (Member) ApplySettled
func (m *Member) ApplySettled(settled, commit []byte) ([]*kolomls.Result, error)

ApplySettled applies the Commit that settled names for the current epoch (docs/design.md, "The Kolo layer") and returns the kept messages of the new epoch, now read.

func (Member) BranchPSK
func (m *Member) BranchPSK() (*BranchPSK, error)

BranchPSK returns the branch PSK of the current epoch for a successor group (RFC 9420 section 11.3).

func (Member) CatchUp
func (m *Member) CatchUp(ctx context.Context, pins Pins) ([]*kolomls.Result, error)

CatchUp applies, one epoch at a time, the settled Commits pins hold after the current epoch, reading each epoch's archive before its Commit, each sender's messages in order; archived messages it could not read are reported with ErrCatchUp at the end. MemberOptions.OnEpoch is called after each epoch.

func (Member) Close
func (m *Member) Close()

Close closes the group.

func (Member) Commit
func (m *Member) Commit(o kolomls.CommitOptions) (*kolomls.PendingCommit, error)

Commit makes a pending Commit of o; Kolo Welcomes never carry the tree.

func (Member) Device
func (m *Member) Device() ([32]byte, error)

Device returns this device's key, as its own leaf names it.

func (Member) DiscardPending
func (m *Member) DiscardPending() error

DiscardPending drops this device's pending Commit.

func (Member) Encrypt
func (m *Member) Encrypt(data, aad []byte) ([]byte, error)

Encrypt protects application data for the current epoch.

func (Member) Epoch
func (m *Member) Epoch() uint64

Epoch returns the current epoch.

func (Member) EpochAuthenticator
func (m *Member) EpochAuthenticator() ([]byte, error)

EpochAuthenticator returns the epoch authenticator (RFC 9420 section 8.7).

func (Member) ExpirePastEpoch
func (m *Member) ExpirePastEpoch() (time.Time, error)

ExpirePastEpoch deletes the previous epoch once its window ended and returns when the window still kept ends, the zero time when none is; the caller calls it again then.

func (Member) Export
func (m *Member) Export(label string, context []byte, length int) ([]byte, error)

Export derives an exported secret (RFC 9420 section 8.5).

func (Member) Extensions
func (m *Member) Extensions() []kolomls.Extension

Extensions returns the GroupContext extensions of the current epoch.

func (Member) GroupContext
func (m *Member) GroupContext() []byte

GroupContext returns the encoded GroupContext of the current epoch.

func (Member) GroupID
func (m *Member) GroupID() []byte

GroupID returns the group id.

func (Member) Halted
func (m *Member) Halted() error

Halted returns the error that stopped this Member for good, nil while it runs.

func (Member) Leave
func (m *Member) Leave() ([]byte, error)

Leave returns this device's proposal to remove itself; an admin commits the removal by value.

func (Member) Limits
func (m *Member) Limits() Limits

Limits returns the roles bounds of the group's Policy.

func (Member) MaxCommitBytes
func (m *Member) MaxCommitBytes() int

MaxCommitBytes returns the bound on a Commit read from pins.

func (Member) OwnLeaf
func (m *Member) OwnLeaf() uint32

OwnLeaf returns this device's leaf index.

func (Member) Pending
func (m *Member) Pending() *kolomls.PendingCommit

Pending returns this device's pending Commit, nil when there is none.

func (Member) PendingLeaves
func (m *Member) PendingLeaves() []*kolomls.LeafNode

PendingLeaves returns the leaves that this device's pending Commit adds or replaces.

func (Member) Receive
func (m *Member) Receive(msg []byte) (*kolomls.Result, error)

Receive processes an application message or a proposal. A message of the next epoch is kept (ErrBuffered) until ApplySettled starts that epoch; a Commit is refused.

func (Member) Removed
func (m *Member) Removed() bool

Removed reports whether a settled Commit removed this device.

func (Member) RevokedLeaves
func (m *Member) RevokedLeaves() []uint32

RevokedLeaves returns the leaves this device holds a revocation for, so the application asks an admin to commit their removal.

func (Member) SelfUpdate
func (m *Member) SelfUpdate() ([]byte, error)

SelfUpdate makes this device's key update, an empty Commit with a path, kept pending until a settled Commit decides the epoch; an admin references it with Admin.Refer.

func (Member) Stage
func (m *Member) Stage(commit []byte) (*kolomls.StagedCommit, error)

Stage processes a Commit without applying it, for a settler's check; the caller discards the result.

func (Member) Store
func (m *Member) Store() kolomls.Store

Store returns the Store the group lives in.

func (Member) Tree
func (m *Member) Tree() kolomls.TreeView

Tree returns a read-only view of the current tree.

type MemberOptions
type MemberOptions struct {
	// MaxBufferedBytes bounds the next-epoch messages kept, the oldest
	// dropped first; zero means DefaultMaxBufferedBytes and a negative value
	// keeps none.
	MaxBufferedBytes int
	// MaxCatchUpBytes bounds the memory that reading one epoch's archive
	// holds, not the epoch: it sets the keys listed and indexed at a time
	// (the bytes of a key and of its index entry, at least one) and the
	// size of one message, and an epoch with more messages is read in
	// several passes. The Results CatchUp returns are not counted. Zero
	// means DefaultMaxCatchUpBytes and a negative value no bound.
	MaxCatchUpBytes int
	// OnEpoch is called by CatchUp after each epoch it applies, with the
	// Member in the new epoch, so the caller can read what only that epoch
	// holds (Export, EpochAuthenticator). An error stops CatchUp and is
	// returned wrapped. It is not called for the epoch that removes this
	// device, and it must not call CatchUp or ApplySettled. Nil does nothing.
	OnEpoch func(*Member) error
	// MaxCommitBytes bounds a Commit read from pins; zero means
	// DefaultMaxCommitBytes and a negative value no bound.
	MaxCommitBytes int
	// Revocations returns the revocations this device holds for device of
	// person: messages of such leaves are dropped and RevokedLeaves lists
	// them; settled Commits are still applied (RFC 9750 section 6.5).
	Revocations func(person, device ed25519.PublicKey) []*koloid.Revocation
}

MemberOptions are a Member's choices.

type Pins
type Pins interface {
	// Put keeps value under key.
	Put(ctx context.Context, key string, value []byte) error
	// Get returns the value of key, an error wrapping ErrMissing when there
	// is none, or one wrapping ErrPinTooLarge, before more than max bytes
	// are read, when it is longer than max; max 0 or less is no bound.
	Get(ctx context.Context, key string, max int) ([]byte, error)
	// List returns the first max keys that start with prefix and sort after
	// the key after (all of them when after is empty), in increasing order;
	// max 0 or less is no bound. A caller reads on from the last key it got
	// until an empty list.
	List(ctx context.Context, prefix, after string, max int) ([]string, error)
	// Delete removes key; a key that is not there is not an error.
	Delete(ctx context.Context, key string) error
}

Pins keeps what a Kolo group's devices fetch while they catch up: Commits by hash, SettledCommits by epoch and each epoch's archived messages for the life of the group, and encrypted trees by epoch while the latest or a Welcome that is not used yet names them (braid.Admin).

type Policy
type Policy struct {
	// Limits bound the roles extension; the Member and the Admin of the
	// group use these.
	Limits Limits
	// Predecessor, when set, allows joining a successor group of it with a
	// branch PSK; nil refuses every branch.
	Predecessor *Predecessor
	// contains filtered or unexported fields
}

Policy is the commit rule of Kolo groups (docs/design.md, "The Kolo layer"); NewConfig puts it in a group's Config. One Policy serves one group.

func (Policy) CheckCommit
func (p *Policy) CheckCommit(v kolomls.CommitView) error

CheckCommit applies the commit rule.

func (Policy) CheckJoin
func (p *Policy) CheckJoin(v kolomls.JoinView) error

CheckJoin checks a Welcome's SettledCommit and extensions, and allows a branch PSK only for a successor of Predecessor.

func (Policy) CheckProposal
func (p *Policy) CheckProposal(v kolomls.ProposalView) error

CheckProposal accepts only a member's own Remove, at most one cached per member, and only at admins, which commit the removal by value.

type Predecessor
type Predecessor struct {
	// GroupID and Epoch name the old group's last epoch.
	GroupID []byte
	Epoch   uint64
	// Devices are the device keys of the old group's leaves.
	Devices map[[32]byte]bool
	// Roles are the old group's roles in that epoch.
	Roles *Roles
	// Braid is the group id of the successor braid; zero, for a device that
	// is not in the braid, is not checked.
	Braid [32]byte
	// Revocations returns the revocations this device holds for device of
	// person; a creator they cover is refused. Nil holds none.
	Revocations func(person, device ed25519.PublicKey) []*koloid.Revocation
}

Predecessor describes the group a successor group branches from (RFC 9420 section 11.3), as a member of it saw its last epoch.

func PredecessorOf
func PredecessorOf(m *Member, braid [32]byte) (*Predecessor, error)

PredecessorOf describes m's current epoch for a successor group whose braid is braid. Set it in a Policy only once the old group's settler quorum is known to be lost for good.

type Quorum
type Quorum uint8

Quorum is the rule that sets how many settlers must agree.

const (
	// Majority needs floor(s/2) + 1 of s settlers.
	Majority Quorum = 1
	// TwoThirds needs floor(2s/3) + 1 of s settlers.
	TwoThirds Quorum = 2
)

Quorum rules, as the braid's.

type Roles
type Roles struct {
	// Braid is the group id of the admins' braid.
	Braid [32]byte
	// Quorum is the settlers' quorum rule.
	Quorum Quorum
	// Admins and Settlers are device keys in strictly increasing order;
	// Settlers is a non-empty subset of Admins.
	Admins, Settlers [][32]byte
}

Roles names the group's braid, its admin devices and its settler devices.

func DecodeRoles
func DecodeRoles(b []byte, l Limits) (*Roles, error)

DecodeRoles decodes and checks the data of a roles extension.

func NewRoles
func NewRoles(braid [32]byte, q Quorum, admins, settlers []ed25519.PublicKey, l Limits) (*Roles, error)

NewRoles returns the roles of a braid with admins and settlers in any order, checked as DecodeRoles checks them.

func RolesOf
func RolesOf(exts []kolomls.Extension, l Limits) (*Roles, error)

RolesOf returns the roles extension of a GroupContext extension list.

func (Roles) Admin
func (r *Roles) Admin(device []byte) bool

Admin reports whether device is an admin.

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

Encode returns the extension data of r.

func (Roles) Extension
func (r *Roles) Extension() kolomls.Extension

Extension returns r as a GroupContext extension.

func (Roles) Q
func (r *Roles) Q() int

Q returns how many settlers a settled Commit needs.

func (Roles) RejectQuorum
func (r *Roles) RejectQuorum() int

RejectQuorum returns how many reject votes decide a reference: s - q + 1, so that one of the two outcomes is always reachable by s honest votes.

func (Roles) Settler
func (r *Roles) Settler(device []byte) bool

Settler reports whether device is a settler.

type Settled
type Settled struct {
	TBS    TBS
	Shares []Share
}

Settled is a SettledCommit: the TBS and the settlers' signatures, signers in strictly increasing order.

func DecodeSettled
func DecodeSettled(b []byte, maxShares int) (*Settled, error)

DecodeSettled decodes a SettledCommit with at most maxShares signatures, the settlers of the group; zero or less leaves only the size of b as the bound.

func (Settled) Check
func (s *Settled) Check(context, commit []byte, gid []byte, epoch uint64, roles *Roles, member func(device [32]byte) bool) error

Check verifies that s settles commit in the epoch with the encoded GroupContext context and roles (docs/design.md, "The Kolo layer").

func (Settled) Encode
func (s *Settled) Encode() []byte

Encode returns the SettledCommit that admins put on pins and gossip.

func (Settled) Valid
func (s *Settled) Valid(roles *Roles, member func(device [32]byte) bool) int

Valid returns the number of distinct settlers of roles whose signature verifies and that member reports as the device of a current leaf; signatures of other keys and invalid ones do not count.

type Share
type Share struct {
	Signer    [32]byte
	Signature [64]byte
}

Share is one settler's signature.

type TBS
type TBS struct {
	// GroupID and Epoch name the epoch the Commit was sent in.
	GroupID []byte
	Epoch   uint64
	// Commit is the SHA-256 of the Commit's MLSMessage.
	Commit [32]byte
	// ContextBefore and ContextAfter are the SHA-256 of the encoded
	// GroupContext of the epoch and of the next one.
	ContextBefore, ContextAfter [32]byte
	// Braid is the group id of the admins' braid.
	Braid [32]byte
	// RefPosition is the settled position of the Commit's reference.
	RefPosition uint64
}

TBS is what each settler signs for the decided Commit of an epoch.

func DecodeTBS
func DecodeTBS(b []byte) (*TBS, error)

DecodeTBS decodes the bytes a settler signs.

func (TBS) Encode
func (t *TBS) Encode() []byte

Encode returns the bytes a settler signs.

Pacote braid

github.com/ciranda-dev/kolo-mls/braid

Package braid is the admin side of a Kolo group over the admins' braid: references, votes and signature shares, the decision of each epoch's Commit, tree serving and the successor group.

Constantes

const DefaultFetchTimeout = 60 * time.Second

DefaultFetchTimeout is how long a settler waits for a candidate Commit on pins before it votes reject: 60 s, the message timeout of the stream layer the braid syncs on.

Variáveis

var (
	// ErrRoster reports a roles change that does not match the braid's
	// settled admins, settlers and quorum.
	ErrRoster = errors.New("kolomls: roles do not match the braid")
	// ErrNotApproved reports a roles change that adds a settler, changes
	// the quorum rule or drops a device that is not revoked, without the
	// application's approval.
	ErrNotApproved = errors.New("kolomls: roles change not approved")
	// ErrDecision reports a settled order whose decision is not the one
	// this settler signed for the epoch.
	ErrDecision = errors.New("kolomls: decision differs from the signed one")
)
var ErrEntry = errors.New("kolomls: invalid braid entry")

ErrEntry reports a braid entry body of kolo-mls that does not decode.

Funções

func Assemble
func Assemble(t *settle.TBS, shares []settle.Share, roles *settle.Roles) *settle.Settled

Assemble returns the SettledCommit of t from shares, keeping one valid share per settler of roles, in signer order.

func Sign
func Sign(id *koloid.Identity, t *settle.TBS) ([]byte, error)

Sign returns a settler's signature over t with its device identity.

Tipos

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

Admin runs an admin device of a Kolo group over the admins' braid (docs/design.md, "The Kolo layer"). It is not safe for concurrent use.

func NewAdmin
func NewAdmin(id *koloid.Identity, b Order, m *settle.Member, o Options) (*Admin, error)

NewAdmin runs the admin device id, the device of m's own leaf, over b; votes and shares are recorded in m's Store before they are written.

func (Admin) Commit
func (a *Admin) Commit(ctx context.Context, o kolomls.CommitOptions) ([]byte, error)

Commit creates this admin's Commit of o, keeps it on pins and writes its reference. It returns the Welcome of the members it adds, to deliver with the SettledCommit once pins hold one for this Commit (RFC 9750 section 5.2.3). A failed write keeps the Commit pending: call Reference again.

func (Admin) Evidence
func (a *Admin) Evidence() [][32]byte

Evidence returns the settlers this admin saw vote twice on one Commit or sign two TBS for one epoch, in key order.

func (Admin) Member
func (a *Admin) Member() *settle.Member

Member returns the admin's Member.

func (Admin) NextDeadline
func (a *Admin) NextDeadline() (time.Time, error)

NextDeadline returns when the candidate this settler waits for on pins times out, the zero time when it waits for none; the caller calls Step then, also on an idle braid.

func (Admin) Refer
func (a *Admin) Refer(ctx context.Context, commit []byte) error

Refer keeps a member's own key update, an empty Commit with a path of the current epoch, on pins and writes its reference.

func (Admin) Reference
func (a *Admin) Reference(ctx context.Context) error

Reference writes the reference of this admin's pending Commit again; a second reference to one Commit counts once. A Commit that adds members first marks its Welcome as unused on pins, which keeps the tree it names there (ReleaseWelcome).

func (Admin) ReleaseWelcome
func (a *Admin) ReleaseWelcome(ctx context.Context, epoch uint64) error

ReleaseWelcome reports that the Welcome of this admin's Commit sent in epoch is used or will not be: the tree it names leaves pins unless it is the latest or another admin's unused Welcome names it. Call it for a Commit that was not decided too.

func (Admin) Step
func (a *Admin) Step(ctx context.Context) (*Applied, error)

Step does what the braid's settled order asks of this admin in the current epoch (vote, sign, assemble and apply) and returns the change once applied. After an epoch change it keeps the new tree on pins and drops the previous one; if only that drop failed it returns the change with the error.

func (Admin) Succeed
func (a *Admin) Succeed(ctx context.Context, nb Order, st kolomls.Store, so SucceedOptions) (*Admin, []byte, error)

Succeed starts the successor of a's group once its settlers are lost for good (RFC 9420 section 11.3), under nb with this admin as its only admin and settler, on st. It returns the new Admin, whose Step settles the first Commit, and that Commit's Welcome.

type Applied
type Applied struct {
	// Epoch is the epoch the Commit was sent in.
	Epoch uint64
	// Settled and Commit are what members apply with ApplySettled.
	Settled, Commit []byte
	// Results are the kept messages of the new epoch, now read.
	Results []*kolomls.Result
}

Applied is the epoch change an Admin made.

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

BraidOrder is the Order of a kolo-braid braid whose apply function feeds an Index, with the devices roster in the same view.

func NewBraidOrder
func NewBraidOrder(b *kolobraid.Braid, idx *Index, roster *devices.Store) *BraidOrder

NewBraidOrder returns the Order of b; b and idx are required, roster nil holds no revocation.

func (BraidOrder) Append
func (o *BraidOrder) Append(ctx context.Context, body []byte) error

Append writes a data entry.

func (BraidOrder) Entries
func (o *BraidOrder) Entries(gid []byte, epoch uint64) ([]Ref, []Vote, []Sig, error)

Entries reads the settled view.

func (BraidOrder) ID
func (o *BraidOrder) ID() [32]byte

ID returns the braid's group id.

func (BraidOrder) Own
func (o *BraidOrder) Own(gid []byte, epoch uint64) ([]Vote, []Sig, error)

Own reads the whole view, settled and tentative.

func (BraidOrder) Revocations
func (o *BraidOrder) Revocations(cert *koloid.DeviceCert) ([]*koloid.Revocation, error)

Revocations reads what voids cert in the settled roster: the device's revocations and its issuer's.

func (BraidOrder) RevocationsAt
func (o *BraidOrder) RevocationsAt(ctx context.Context, position uint64, cert *koloid.DeviceCert) ([]*koloid.Revocation, error)

RevocationsAt reads what voids cert in the roster right after the settled entry at position. Each call replays the braid from its last such read to position (kolo-braid's SettledAt), so callers keep the answers.

func (BraidOrder) Roster
func (o *BraidOrder) Roster() (admins, settlers [][32]byte, q int, err error)

Roster reads the settled membership in one snapshot: the admins, and the seats and quorum of the settler config that settled it.

type Decision
type Decision struct {
	// Decided is the epoch's Commit, nil while none is decided.
	Decided *Ref
	// Candidate is the first reference not yet decided, nil when there is
	// none or once one is decided.
	Candidate *Ref
	// Voted holds the settlers whose vote on the candidate counted.
	Voted map[[32]byte]bool
	// Rejected are the Commits rejected before the candidate or decision.
	Rejected [][32]byte
	// Equivocators are the settlers that cast both an accept and a reject
	// vote on one Commit, in key order.
	Equivocators [][32]byte
}

Decision is the state of an epoch's decision over its settled entries.

func Decide
func Decide(refs []Ref, votes []Vote, roles *settle.Roles, contextBefore [32]byte) Decision

Decide computes an epoch's decision from its settled references and votes in settled order; the rules are in docs/design.md, "The Kolo layer".

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

Index keeps the kolo-mls entries of a braid in its view, by group, epoch and position, for the decision; it never touches MLS state, as a braid's apply function must not.

func NewIndex
func NewIndex(prefix []byte, roster *devices.Store) *Index

NewIndex returns an Index whose records live in the view under prefix; no other view key may start with it. Entries of a writer whose certificate roster revokes at the entry's position are rejected; a nil roster holds no revocation.

func (Index) Apply
func (x *Index) Apply(tx *kolobraid.Tx, e *kolobraid.Entry) (bool, error)

Apply records e when it is a kolo-mls entry and reports false for every other entry. A body with a kolo-mls tag that does not decode, or whose writer's certificate is not valid or revoked at e's position, is rejected on every peer.

func (Index) Entries
func (x *Index) Entries(s *kolobraid.Snapshot, gid []byte, epoch uint64) (refs []Ref, votes []Vote, sigs []Sig, err error)

Entries returns the kolo-mls entries of group gid and epoch in s, in the braid's order, or the storage error that cut the read short.

type Options
type Options struct {
	// Pins keeps Commits, SettledCommits and trees; required.
	Pins settle.Pins
	// FetchTimeout is how long a settler waits for a candidate on pins;
	// zero means DefaultFetchTimeout, a negative value is refused.
	FetchTimeout time.Duration
	// Now is the clock of FetchTimeout; required.
	Now func() time.Time
	// ApproveRoles is this settler's application deciding a roles change
	// that adds a settler, changes the quorum rule or drops an admin or
	// settler that is not revoked; nil refuses every such change.
	ApproveRoles func(current, next *settle.Roles) bool
}

Options are an Admin's choices.

type Order
type Order interface {
	// ID returns the braid's group id, which the roles name.
	ID() [32]byte
	// Append writes body as this admin's next entry.
	Append(ctx context.Context, body []byte) error
	// Entries returns the settled kolo-mls entries of group gid and epoch
	// in the braid's order.
	Entries(gid []byte, epoch uint64) ([]Ref, []Vote, []Sig, error)
	// Own returns this admin's votes and shares of group gid and epoch in
	// the order, settled or not.
	Own(gid []byte, epoch uint64) ([]Vote, []Sig, error)
	// Revocations returns what voids cert in the settled roster.
	Revocations(cert *koloid.DeviceCert) ([]*koloid.Revocation, error)
	// RevocationsAt returns what voids cert in the roster right after the
	// settled entry at position.
	RevocationsAt(ctx context.Context, position uint64, cert *koloid.DeviceCert) ([]*koloid.Revocation, error)
	// Roster returns the settled admins and settler seats, each in
	// increasing order, and the settlers' quorum.
	Roster() (admins, settlers [][32]byte, q int, err error)
}

Order is the admins' braid as an Admin uses it. The read methods read local state and do not block.

type Reason
type Reason uint8

Reason says why a settler votes against a Commit.

const (
	ReasonNone        Reason = 0
	ReasonInvalid     Reason = 1
	ReasonUnavailable Reason = 2
)

Vote reasons; an accept vote has none.

type Ref
type Ref struct {
	// Position is the entry's settled position in the braid.
	Position uint64
	// Writer is the admin device that wrote it.
	Writer [32]byte
	// Commit is the SHA-256 of the Commit's MLSMessage.
	Commit [32]byte
	// Cert is the SHA-256 of the writer's device certificate the entry
	// carries.
	Cert [32]byte
}

Ref is a settled commit-ref entry of one epoch: an admin's reference to a Commit kept on pins.

type Sig
type Sig struct {
	Position  uint64
	Writer    [32]byte
	TBS       settle.TBS
	Signature [64]byte
	// Cert is the SHA-256 of the writer's device certificate the entry
	// carries.
	Cert [32]byte
}

Sig is a settled commit-sig entry: one settler's signature share.

type SucceedOptions
type SucceedOptions struct {
	// Create is the creator's group options, with Create.KeyPackage made on the
	// Store given to Succeed; its Extensions and Config.PSKs are set by Succeed
	// and must be empty.
	Create kolomls.CreateOptions
	// KeyPackages are the members' fresh KeyPackages.
	KeyPackages [][]byte
	// Member and Admin are the new group's options.
	Member settle.MemberOptions
	Admin  Options
}

SucceedOptions are the parts of a successor group that its creator gives.

type Vote
type Vote struct {
	Position      uint64
	Writer        [32]byte
	Commit        [32]byte
	ContextBefore [32]byte
	Accept        bool
	Reason        Reason
	Cert          [32]byte
}

Vote is a settled commit-vote entry of one epoch.

Pacote backendstore

github.com/ciranda-dev/kolo-mls/backendstore

Package backendstore keeps the state of kolo-mls groups in a kolo-store Backend, such as its on-disk backend, under a key prefix: each group change is one atomic, durable Backend batch.

Tipos

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

Store is a kolomls.Store on a kolo-store Backend. Deletion on disk is best effort: the Backend removes a key in the batch, but backups, snapshots and freed blocks may keep its bytes.

func New
func New(b kolostore.Backend, prefix []byte) *Store

New returns a Store whose keys live in b under prefix; no other user of b may write keys that start with it.

func (Store) Apply
func (s *Store) Apply(b kolomls.Batch) error

Apply writes the deletes and puts of b in one atomic, durable Backend batch, which keeps its own copies of the values.

func (Store) Get
func (s *Store) Get(key []byte) ([]byte, error)

Get returns a copy of the value of key, or kolomls.ErrNotFound.

Bom saber

Épocas e commits

  • Cada época nova começa com um commit que dá segredos novos só aos membros dessa época, então um membro removido não consegue calcular os segredos de nenhuma época posterior. O custo de um commit cresce com o logaritmo do tamanho do grupo, não com o tamanho em si.
  • Os admins fazem commit das mudanças de associação e de grupo. Um membro faz commit só da sua própria atualização de chave, e pede para sair com uma proposta da sua própria remoção, da qual um admin faz commit. Só os admins guardam um pedido desses, no máximo um por membro, porque uma proposta guardada impede um dispositivo de enviar até haver um commit (RFC 9420, seção 12.4).
  • Um commit leva as suas propostas por valor. Um commit que nomeia qualquer proposta por referência é recusado, então todo dispositivo tem o que um commit precisa, quaisquer que sejam as propostas que leu.
  • Um membro aplica um commit só com assinaturas de um quórum dos settlers da época, depois de conferir o grupo, a época, o braid, o contexto anterior, o hash do commit e o contexto a que o commit leva. Um welcome para um membro novo só é enviado depois que as assinaturas dos settlers existem.
  • Um segundo commit assentado para a época que um membro deixou interrompe esse membro de vez (settle.ErrHalted), também depois de um reinício. Um membro que não consegue seguir um commit assentado mantém o seu estado e o relata (settle.ErrSettledMismatch); a biblioteca não adiciona esses membros de novo.
  • Um membro que guarda propostas faz commit delas antes de enviar dados da aplicação.
  • Os commits externos, as propostas externas e o ReInit são recusados.

Chaves das mensagens

  • Nos grupos do Kolo, as propostas, os commits e as mensagens de aplicação viajam sempre cifrados (MLS PrivateMessage). O núcleo também pode enviar propostas e commits em claro (PublicMessage), como o RFC permite; os dados da aplicação vão sempre cifrados.
  • Uma mensagem recebida só gasta a sua chave depois que a assinatura é verificada. Um membro pode construir um texto cifrado válido sob a chave de outro membro, porque cada membro deriva todas as chaves da época, mas não pode assinar como esse membro. Um commit mantém a sua chave até ser aplicado, então um dispositivo que para no meio pode ler o commit de novo.
  • O Kolo amarra a geração da mensagem à parte assinada de cada mensagem cifrada (o envelope de geração), então alguém de dentro não consegue reenviar uma mensagem assinada de outro membro sob uma geração posterior e gastar essa geração (RFC 9750, seção 8.6). O núcleo deixa esse vínculo para a aplicação (Config.Envelope), e os grupos do Kolo sempre o ativam (settle.Envelope): sem ele, esse reenvio funciona.
  • Cada chave é apagada na mesma gravação de armazenamento que a registra como usada, e as chaves de uma época são apagadas com a época, exceto que a época anterior continua legível por 10 segundos depois de um commit, para as mensagens de aplicação atrasadas dos membros que ficam. O relógio da aplicação encerra essa janela (Config.PastEpochWindow).
  • Um receptor guarda uma janela de 5 gerações por remetente, incluindo a mais nova lida, então uma mensagem pode chegar até 4 gerações atrás da mais nova. Uma mensagem pode adiantar um remetente no máximo 1.000 gerações. Os dois valores são configuráveis até 65.536 (Config.OutOfOrderTolerance, Config.MaxForwardDistance).
  • Se uma gravação de armazenamento falha, o grupo recusa toda chamada até ser aberto de novo a partir do armazenamento, porque a gravação pode ter acontecido.

Identidade e dispositivos

  • Um dispositivo é uma folha da árvore do grupo. A credencial é uma credencial do Kolo (cred): a cadeia de certificados de dispositivo da kolo-id mais a assinatura do dispositivo sobre a chave de assinatura MLS da folha.
  • A verificação da folha confere a cadeia de certificados para a pessoa que o certificado nomeia, recusa uma chave de assinatura de ordem pequena, e depois a aplicação decide se essa pessoa pode estar aqui (cred.Authenticator.Expect). Sem uma verificação própria da aplicação (Expect é nil), qualquer pessoa é aceita: os admins decidiram adicionar o dispositivo e os settlers assinaram o commit.
  • Só o admin que adiciona um dispositivo confere a validade do certificado e as suas revogações (cred.Authenticator.Now e Revocations). Os settlers conferem as revogações contra o registro de dispositivos do braid como ele estava logo depois da posição assentada da referência do commit, sempre que o leem, então decidem do mesmo jeito. Um membro que tem uma revogação (settle.MemberOptions.Revocations) descarta as mensagens desse dispositivo mas continua aplicando os commits assentados. Todo receptor aceita um certificado expirado, como recomenda a seção 5.3.2 do RFC 9420.
  • Um dispositivo novo da mesma pessoa entra como uma folha nova. Um dispositivo revogado é removido do grupo por um commit. Remover uma pessoa remove todos os dispositivos dela em um único commit.

Admins e settlers

As mesmas regras valem para um grupo de três e para um grupo de trinta mil.

  • O braid do grupo contém só os dispositivos admin, e os settlers estão entre eles. Os membros comuns nunca são membros do braid. O conjunto de settlers vai dentro do próprio grupo, na extensão de papéis (settle.Roles), que só os admins podem mudar.
  • A ordem assentada do braid decide o único commit de cada época. O braid contém só uma referência pequena ao commit (grupo, época e o hash dos bytes do commit), um voto e uma parte de assinatura. A aplicação leva os bytes do commit e as assinaturas dos settlers (por exemplo pela kolo-gossip) e os guarda em pins.
  • A primeira referência ainda não decidida vence com um quórum q de votos a favor, ou perde com s - q + 1 votos contra (s settlers), então o grupo segue em frente quando os settlers discordam sobre um commit estar disponível. A próxima referência de um admin só conta depois que a anterior foi rejeitada, então um admin atrasa o grupo no máximo um tempo limite de busca por vez.
  • Um settler vota contra um commit que não conseguiu buscar em um minuto (em qualquer erro de busca). Ele aceita uma mudança de papéis só quando ela nomeia os admins, as vagas de settler e o quórum do próprio braid, e só com a aprovação da sua própria aplicação (braid.Options.ApproveRoles; sem ela, toda mudança assim é recusada) quando a mudança adiciona um settler, muda a regra de quórum ou remove um admin ou settler que não está revogado; adicionar um admin ou remover um dispositivo revogado não precisa dela.
  • Cada entrada do braid leva o certificado de dispositivo de quem a escreve, e o apply do braid rejeita uma entrada cujo escritor o registro de dispositivos revoga na posição dessa mesma entrada, então um admin ou settler revogado perde as suas referências, votos e partes de assinatura em uma única posição para todos os peers, sem precisar removê-lo do braid.
  • Um settler registra cada voto, parte de assinatura e primeira busca que falhou antes de gravar, então um reinício nunca emite um voto diferente nem zera o tempo limite, e uma vez que assinou em uma época ele nunca mais vota nem assina nela.
  • Depois de cada commit, um admin guarda o ratchet tree nos pins, cifrado com uma chave exportada da época nova para o dispositivo desse admin, com o ID de grupo e a época amarrados. Os admins que rodam sobre a kolo-braid o servem a quem entra.
  • Quando os settlers se perdem de vez, um settler da última época inicia um grupo sucessor (braid.Admin.Succeed) cujo primeiro commit leva uma chave de ramo dessa época (RFC 9420, seção 11.3). Um membro só entra quando quem o criou era um settler do grupo antigo, não está revogado até onde o membro sabe, e todo dispositivo que ele contém era membro dele. A aplicação só deixa um membro aceitar um sucessor quando se sabe que o quórum antigo foi perdido (settle.Policy.Predecessor; sem ele, todo sucessor é recusado).

O que este design não impede:

  • s - q + 1 settlers que votam contra tudo param todos os commits, inclusive a sua própria remoção (com quatro settlers e a regra de maioria, dois).
  • Um admin cuja referência é ordenada primeiro pode vencer épocas com commits que não mudam nada, até que outro admin o remova do braid.
  • Um admin pode remover do braid settlers honestos e parar o grupo.
  • Com um ou dois settlers, um dispositivo settler roubado pode parar o grupo até que um grupo novo seja criado.

Recuperar o atraso e o histórico

  • Uma pessoa que entra em um grupo mais tarde lê só as mensagens a partir do momento em que entrou. Não há histórico para ela, e a biblioteca não tem nenhuma interface de histórico.
  • O novo dispositivo de uma mesma pessoa só lê a partir do momento em que entra. A kolo-mls não tem nenhuma transferência do histórico vinda de outro dispositivo dessa pessoa; a aplicação precisa mover o histórico por conta própria. Se todos os dispositivos de uma pessoa se perdem, a frase de recuperação restaura a identidade, não as mensagens.
  • Os dispositivos que estavam no grupo mas offline se atualizam a partir dos pins: buscam os commits posteriores à sua última época com as assinaturas dos seus settlers (settle.Member.CatchUp), e o texto cifrado arquivado de cada época a que pertenceram, e avançam uma época por vez.
  • As mensagens da época seguinte esperam até o seu commit, e as mais antigas são descartadas primeiro além de 16 MiB. Um dispositivo que esteve ausente lê o arquivo de cada época uma de cada vez, em passadas dentro de 16 MiB de heap, então uma época de qualquer tamanho é lida inteira; as mensagens que ele não conseguiu ler (um valor que não abre, que não combina com a sua chave ou que passa do limite) são relatadas (settle.ErrCatchUp), nunca a época. Toda leitura dos pins pede um limite, então pins hostis não conseguem entregar mais a um dispositivo.

Dispositivos ociosos

Um dispositivo ocioso nunca é removido automaticamente. Um dispositivo que fica offline por muito tempo continua sendo membro e se atualiza quando volta. A própria biblioteca não remove nenhum dispositivo. Uma aplicação pode mostrar uma lista de dispositivos inativos para que uma pessoa ou um admin remova um dispositivo à mão.

Isso tem custos. Um dispositivo esquecido mantém a sua chave antiga na árvore e continua recebendo segredos novos, então, se for roubado mais tarde, quem o tiver pode ler o que foi enviado depois da sua última atualização até ele ser removido. O disco dele guarda os segredos da sua última época. E todo commit do grupo precisa continuar disponível nos pins enquanto o grupo viver.

Padrões

Um valor zero de uma configuração significa o seu padrão, e o comentário de documentação de cada configuração diz o que um valor negativo faz (sem limite, não guardar nenhum, ou recusa); os limites dos papéis e o cache de identidades tomam como padrão qualquer valor de zero ou menos. Todo limite é configurável, exceto os que o próprio formato fixa, e cada padrão tem uma fonte escrita: o RFC, uma especificação publicada ou uma medição. Os tamanhos são verificados antes de qualquer alocação, e nenhuma alocação é dimensionada a partir de um tamanho não confiável. Uma configuração citada sem pacote pertence ao pacote raiz kolomls.

Mensagens e chaves:

LimiteConfiguraçãoPadrãoPor quê
Janela de gerações guardadas por remetente, para entrega fora de ordemConfig.OutOfOrderTolerance5 por remetente e tipo de mensagem, incluindo a geração mais nova lida, então 4 mais antigas continuam legíveismemória e forward secrecy dentro de uma época; o valor de uma implementação de MLS publicada
Passos do ratchet para a frente em uma mensagemConfig.MaxForwardDistance1.000CPU contra um número de geração hostil; o valor da mesma implementação
Maior janela ou distância para a frente que pode ser configuradafixo65.536CPU por mensagem recebida: uma mensagem que move um ratchet tão longe e guarda cada chave custa cerca de 0,15 s de CPU, medido
Época anterior guardada para mensagens atrasadasConfig.PastEpochWindow10 segundos depois de um commit ser aplicado, só a época anterior, para as mensagens de aplicação dos membros que ficam; um valor negativo não guarda nenhumaforward secrecy contra a entrega atrasada; um protocolo publicado de mídia em grupo guarda as chaves da época anterior por 10 segundos; o relógio de quem chama encerra a janela
Mensagens por remetente e por épocafixo2^32 - 1, o contador de geração (RFC 9420, seção 6.3.2)espaço de nonces
Chaves de retomada de épocas passadas guardadasConfig.ResumptionPSKsnenhuma: só as da época atual; um valor negativo é recusadoforward secrecy das épocas passadas; o RFC 9420, seção 8.6, pede um limite definido
Intervalo de atualização de um dispositivo onlinea política da aplicaçãouma por diasegurança pós-comprometimento; o exemplo do RFC 9420, seção 3.2; uma política que a aplicação segue

Tamanhos e decodificação:

LimiteConfiguraçãoPadrãoPor quê
Validade de um key packageKeyPackageOptions.Lifetime para um key package novo; Config.MaxLeafLifetime para o limite que quem recebe confere (negativo é sem limite)84 dias, começando uma hora antes da criação por causa do desvio de relógio; as folhas cuja validade é maior que 84 dias e uma hora são recusadaschaves de entrada vencidas; 84 dias é o padrão de uma implementação de MLS publicada, e o RFC 9420, seção 7.2, exige um máximo
Tamanho de uma mensagem MLSo da biblioteca transportadorao que a biblioteca transportadora definirmemória, entrada hostil
Tamanho de um welcomeo da biblioteca transportadoradefinido pela aplicação que o entregamemória
Bytes de ratchet tree aceitos ao entrarJoinOptions.MaxTreeBytes128 MiB; um valor negativo é sem limitememória; medido: um grupo de 100.000 membros com credenciais grandes precisa de cerca de 83 MB, e a árvore hostil mais cara que se mediu ocupa cerca de 7 bytes de memória por byte recebido, então o padrão limita uma entrada perto de 0,9 GiB
Credencial do Kolofixo (cred.MaxBody)581 bytesdecodificação; o maior certificado de dispositivo com o seu pai aprovador (514), o seu tamanho, uma versão e a assinatura do dispositivo, o máximo do próprio formato
Identidades de cliente em cachecred.Authenticator.MaxCached524.288memória; mais que as folhas da maior árvore que quem entra aceita por padrão (a menor folha do Kolo, medida em 471 bytes, dá no máximo 284.359 em 128 MiB); o cache é esvaziado quando enche
Propostas em cache em uma épocaPolicy.CheckProposaldeixadas para a política da aplicação; os grupos do Kolo guardam só a remoção do próprio membro, só nos admins, no máximo uma por membro e menos que o número de membros do grupomemória; os commits do Kolo levam as suas propostas por valor

Papéis e commits:

LimiteConfiguraçãoPadrãoPor quê
Admins e settlers nos papéis de um gruposettle.Policy.Limits.MaxAdmins e settle.Policy.Limits.MaxSettlersnenhum: zero ou menos é sem limite, e um valor positivo é um limite que a aplicação escolhememória e trabalho de assinaturas por commit: um número maior que as chaves que cabem na extensão (32 bytes cada uma) é recusado, e o transporte limita a extensão; o trabalho de assinaturas é no máximo uma verificação por settler
Assinaturas em um commit assentadosegue o limite de settlersno máximo uma por settler do grupotrabalho de assinaturas por commit
Referências de um adminfixoum candidato por vez: a próxima referência de um admin só conta depois que a anterior foi rejeitadaliveness
Espera por um commit nos pins antes de um settler votar contrabraid.Options.FetchTimeout60 segundos, em qualquer erro de busca; o relógio de quem chama, mantido entre reinícios; um valor negativo é recusadoliveness do grupo; o tempo limite de mensagem da camada de streams sobre a qual o braid sincroniza
Leituras do registro na posição de uma referênciafixouma por certificado de folha candidato e época, mantida durante a época, uma de cada vezCPU e armazenamento; cada leitura reproduz o braid desde a última leitura desse tipo

Recuperar o atraso:

LimiteConfiguraçãoPadrãoPor quê
Mensagens da época seguinte guardadas para depoissettle.MemberOptions.MaxBufferedBytes16 MiB, e as mais antigas são descartadas primeiro; um valor negativo não guarda nenhumamemória; o limite que o braid dos admins põe nas entradas que esperam por uma anterior. As épocas posteriores são buscadas de novo depois de se atualizar
Mensagens arquivadas lidas por época ao se atualizarsettle.MemberOptions.MaxCatchUpBytes16 MiB de heap por passada, que é também a maior mensagem arquivada; uma época de qualquer tamanho é lida em passadas dentro desse limite (cerca de 54.000 mensagens por passada), e cada passada lê todas as mensagens da época, sem pular nenhuma; um valor que passa do limite, um que não combina com a sua chave ou não abre, e uma listagem que os pins fizeram errada são relatados com um erro enquanto a época continua sendo aplicada; um valor negativo é sem limitememória
Commit lido dos pinssettle.MemberOptions.MaxCommitBytes128 MiB; um valor negativo é sem limitememória; o limite da árvore, porque os KeyPackages que um Commit adiciona viram as folhas da árvore
Commit assentado lido dos pinssegue o limite de settlers512 bytes mais 96 por assinatura de settlermemória; vem da codificação
Árvore cifrada lida dos pinssegue JoinOptions.MaxTreeByteso limite de árvore de quem entra mais 48 bytes, pedido aos pins antes de o blob ser lidomemória

O tamanho do grupo, os membros por pessoa e o número de grupos não são limites da biblioteca. Os dispositivos ociosos nunca são removidos automaticamente, e os commits ficam nos pins enquanto o grupo viver, porque nenhum dispositivo é expulso por estar ocioso. A camada do Kolo recebe o relógio da aplicação (settle.NewConfig, braid.Options.Now) e se recusa a rodar sem um; o núcleo usa Config.Now para a validade das folhas que envia e para a janela da época anterior, e recorre ao relógio do sistema quando ele não está configurado.

Segurança

  • Quem entra mais tarde lê só as mensagens a partir do momento em que entrou. Não há histórico para essa pessoa nem uma interface de histórico.
  • Um grupo muda só quando um Commit é aplicado. Em um grupo do Kolo, um dispositivo aplica um Commit só com assinaturas de um quórum dos dispositivos settlers do grupo, então um dispositivo admin sozinho não consegue dividir o grupo nem mudar os seus membros.
  • Se um dos seus dispositivos for roubado, remova-o: a partir daí ele não lê nada novo. Um dispositivo que você deixa de usar não é removido sozinho: ele continua no grupo e pode ler mensagens novas quando volta, então remova os dispositivos que você não usa mais.
  • As chaves são apagadas depois de usadas, na mesma escrita que as registra como usadas, então um dispositivo que seja roubado mais tarde não consegue abrir cópias cifradas antigas com as chaves da biblioteca. Apagar do disco é um melhor esforço: o backendstore remove as chaves do lote, mas backups, snapshots e blocos liberados podem manter os seus bytes, e uma imagem do disco tirada antes de um apagamento guarda o que guardava então. Um dispositivo ocioso mantém no disco os segredos da sua última época.
  • Uma mensagem gasta a sua chave só depois que a assinatura é conferida. Com o envelope do Kolo, um membro não consegue repetir a mensagem assinada de outro membro sob uma geração posterior para gastar essa geração.
  • Nenhuma API devolve um segredo de época: Export deriva um segredo para um rótulo e EpochAuthenticator devolve o autenticador de época. Close zera os segredos guardados em memória. Chaves privadas, sementes e segredos de época nunca vão para um log nem para uma mensagem de erro.

O que o MLS não dá:

  • O MLS não dá histórico a quem entra mais tarde, nem jeito de ler de novo o que um dispositivo já consumiu e apagou.
  • O MLS não protege o que um membro removido já tem.
  • O MLS não protege contra um Authentication Service comprometido. No Kolo, isso é a frase de recuperação e os dispositivos aprovadores da kolo-id.
  • O MLS não dá garantia de entrega: quem carrega as mensagens pode atrasá-las ou descartá-las.
  • O MLS não protege contra o replay por quem está dentro do grupo em uma época, a menos que a aplicação configure um Envelope, como fazem os grupos do Kolo (o envelope de geração).
  • Não há defesa contra um Commit malicioso que só alguns membros conseguem detectar. Um membro que não consegue seguir um Commit assentado mantém o seu estado e relata settle.ErrSettledMismatch.
  • Não há proteção contra negação de serviço. Settlers que votam contra tudo param todo commit, e um admin pode remover do braid settlers honestos e travar o grupo; com um ou dois settlers, um dispositivo settler roubado pode travar o grupo até que um grupo sucessor seja criado.
  • O ID de grupo, a época e os tempos ficam visíveis em cada mensagem, e o transporte mostra qual dispositivo a enviou. Aceita-se que os dispositivos possam ser ligados entre si.
  • Uma remoção espera enquanto há menos de um quórum de settlers online. Mantenha pelo menos dois dispositivos admin.

O que a biblioteca espera de quem a chama:

  • Um só Group (ou settle.Member) por ID de grupo de cada vez em um Store, e nunca duas cópias do estado de um dispositivo: duas escreveriam árvores de segredos que divergem. Create, Join e Open de um mesmo ID de grupo não rodam ao mesmo tempo.
  • Um Store cujo Apply seja atômico e durável, e seguro para uso concorrente quando compartilhado. Uma escrita que falha faz o Group recusar toda chamada até ser aberto de novo.
  • Um relógio. A camada do Kolo se recusa a rodar sem um; o núcleo recorre ao relógio do sistema. A biblioteca não tem timers: chame ExpirePastEpoch e braid.Admin.Step de novo nos momentos que eles devolvem (Admin.NextDeadline).
  • Um Authenticator e uma Policy que decidam do mesmo jeito em todos os membros. Membros que decidem diferente dividem o grupo (RFC 9750, seção 6.5).
  • Entregar os Commits ao Process em ordem de época, um por época, e em um grupo do Kolo só com o seu SettledCommit (settle.Member.ApplySettled).
  • Entregar as propostas referenciadas antes do Commit que as nomeia, e um Welcome só depois que o seu Commit estiver assentado e assinado.
  • Guardar toda mensagem de uma época futura e entregá-la de novo depois de se atualizar (o settle.Member guarda dentro de um limite).
  • Manter nos pins todo Commit, o seu SettledCommit e a árvore cifrada enquanto o grupo viver, e as mensagens arquivadas de cada época enquanto um membro dessa época puder estar atrasado.
  • Chamar ApplyPending ou DiscardPending quando o Delivery Service tiver escolhido o Commit da época.
  • Em um grupo do Kolo, rodar o laço do membro (Receive, ApplySettled, CatchUp, ExpirePastEpoch) em todo dispositivo e o laço do admin (Step depois de cada evento do braid e em NextDeadline) em todo dispositivo admin, e decidir as mudanças de papéis em braid.Options.ApproveRoles.

Status

Experimental. A API pode mudar antes da v1.0.0. A versão 0.1.0 está etiquetada.

  • Feito: o núcleo do RFC 9420 para a suíte de cifragem 0x0001 (grupos, KeyPackages, Welcomes com valores GREASE, cada verificação de propostas e de Commit, mensagens de aplicação, handshakes como PublicMessage e PrivateMessage, a janela da época anterior, o Store com um lote atômico por mudança); a API pública (o pacote raiz kolomls e os pacotes cred, settle, braid e backendstore, com examples/basic); a camada do Kolo (a credencial 0xF001, a extensão de papéis 0xF002, a regra de commit, o envelope de geração, os commits assentados, o lado admin sobre a kolo-braid, os dispositivos membros que se atualizam a partir dos pins, a árvore cifrada para quem entra e o grupo sucessor); e uma verificação cruzada com implementações independentes.
  • Testado: os vetores de teste oficiais do MLS (baixados com scripts/fetch-vectors.sh em um commit fixado e com o SHA-256 conferido, e exigidos por scripts/release-check.sh), testes unitários e de cenários em memória, o programa examples/basic conferido por um teste, sobre braids reais e entre processos em 127.0.0.1, alvos de fuzz para os decodificadores do núcleo e da camada do Kolo, e testes que falham quando uma regra de validação é removida.
  • Não incluído: adicionar de novo os membros que não conseguem seguir um Commit assentado (eles são relatados com settle.ErrSettledMismatch). Os commits externos, as propostas externas e o ReInit são recusados pela política.
  • Não verificado: o tempo que uma remoção leva para se espalhar (a biblioteca não o limita).

Erros

ErroMensagem
ErrClosedkolomls: group closed
ErrConfirmationTagkolomls: invalid confirmation tag
ErrCredentialkolomls: credential refused
ErrDecryptkolomls: decryption failed
ErrFutureEpochkolomls: message for a future epoch
ErrGenerationExhaustedkolomls: generations exhausted
ErrGroupExistskolomls: group already exists
ErrInvalidArgumentkolomls: invalid argument
ErrInvalidCommitkolomls: invalid commit
ErrInvalidKeyPackagekolomls: invalid key package
ErrInvalidLeafkolomls: invalid leaf node
ErrInvalidProposalkolomls: invalid proposal
ErrInvalidTreekolomls: invalid ratchet tree
ErrInvalidWelcomekolomls: invalid welcome
ErrKeyPackageNotFoundkolomls: key package not found
ErrMalformedkolomls: malformed encoding
ErrMembershipTagkolomls: invalid membership tag
ErrNotFoundkolomls: not found
ErrPSKNotFoundkolomls: pre-shared key not found
ErrPendingCommitkolomls: pending commit
ErrPendingProposalskolomls: proposals pending
ErrPolicykolomls: refused by policy
ErrRemovedkolomls: removed from the group
ErrReplaykolomls: generation already used
ErrSignaturekolomls: invalid signature
ErrStorekolomls: store failed
ErrTooFarAheadkolomls: generation too far ahead
ErrTooLongkolomls: vector longer than 2^30 - 1 bytes
ErrTooOldkolomls: generation too old
ErrUnknownProposalkolomls: unknown proposal reference
ErrUnknownSenderkolomls: sender is not a member
ErrUnsupportedkolomls: unsupported
ErrWrongEpochkolomls: message for a past epoch
ErrWrongGroupkolomls: message for another group
cred.ErrCredentialkolomls: invalid Kolo credential
settle.ErrBufferedkolomls: message of the next epoch kept for later
settle.ErrCatchUpkolomls: epoch archive refused
settle.ErrEnvelopekolomls: invalid authenticated data envelope
settle.ErrEquivocationkolomls: two settled commits for one epoch
settle.ErrHaltedkolomls: member halted
settle.ErrMissingkolomls: not on pins
settle.ErrNotHeldkolomls: leave requests are held by admins only
settle.ErrNotSettledkolomls: commit not settled
settle.ErrPinTooLargekolomls: pinned data past the bound
settle.ErrRevokedSenderkolomls: message of a revoked device dropped
settle.ErrRoleskolomls: invalid roles extension
settle.ErrRulekolomls: Kolo group rule
settle.ErrSealedTreekolomls: encrypted tree does not open
settle.ErrSettledMismatchkolomls: settled commit does not match
braid.ErrDecisionkolomls: decision differs from the signed one
braid.ErrEntrykolomls: invalid braid entry
braid.ErrNotApprovedkolomls: roles change not approved
braid.ErrRosterkolomls: roles do not match the braid

A tabela lista os erros do pacote raiz e de cred, settle e braid, estes três com o nome do seu pacote. Teste os erros com errors.Is. As mensagens de erro próprias da biblioteca começam com kolomls:. ErrCredential, ErrPolicy e ErrStore envolvem um erro do Authenticator, da Policy e do Store, e cred.ErrCredential envolve os erros da kolo-id.

Referências

  • RFC 9420, The Messaging Layer Security (MLS) Protocol (Proposed Standard, julho de 2023).
    • Usa: o protocolo: o framing, o ratchet tree, o TreeKEM, o key schedule, as propostas, os commits, o Welcome e os code points, para a suíte de cifragem 0x0001.
    • Não implementa: outras suítes de cifragem. Os commits externos, as propostas externas e o ReInit são analisados e a política os recusa.
  • RFC 9750, The Messaging Layer Security (MLS) Architecture (Informational, abril de 2025).
    • Usa: os papéis do Authentication Service e do Delivery Service e as considerações de segurança que dão forma ao design, incluindo o vínculo da geração da seção 8.6.
    • Não implementa: um Delivery Service ou um Authentication Service próprios. Ele não define nenhum protocolo.
  • RFC 9180, Hybrid Public Key Encryption (Informational, fevereiro de 2022).
    • Usa: o esquema HPKE que o RFC 9420 usa para cifrar segredos para a chave de um membro (DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM), por meio de crypto/hpke.
    • Não implementa: outros KEMs, KDFs e AEADs.
  • RFC 9846, The Transport Layer Security (TLS) Protocol Version 1.3, seção 3, "Presentation Language" (Proposed Standard, julho de 2026; substitui o RFC 8446).
    • Usa: a notação e a codificação de cada estrutura do MLS. O RFC 9420 foi escrito sobre o RFC 8446, cuja seção 3 define a mesma linguagem.
    • Não implementa: o resto do TLS.
  • Vetores de teste do grupo de trabalho do MLS, repositório mlswg/mls-implementations no commit 2034fe72e0c805a683ba76165660c834f2a8142a.
    • Usa: os vetores de teste oficiais que o núcleo precisa passar. O repositório não tem arquivo de licença, então os vetores são baixados para testar e nunca copiados para o repositório da kolo-mls.
    • Não implementa: nada; são só entrada de testes.