kolo-mls da a los grupos cifrado de extremo a extremo con el protocolo Messaging Layer Security (RFC 9420, con la arquitectura en RFC 9750) para la suite de cifrado 0x0001 (X25519, AES-128-GCM, SHA-256, Ed25519), escrita solo sobre la biblioteca estándar de Go. Los mensajes de un grupo solo pueden leerlos los miembros actuales: el historial de un grupo es una cadena de épocas, y cada época empieza con un commit que da secretos nuevos solo a los miembros de esa época. Cada dispositivo es un miembro (una hoja, o leaf, del árbol del grupo), y su identidad es una cadena de certificados de dispositivo de kolo-id. Los dispositivos admin del grupo deciden el commit de cada época a través de kolo-braid, y la aplicación lleva los commits (por ejemplo por kolo-gossip) y los guarda en pins (kolo-pin), para que un dispositivo que estuvo desconectado pueda ponerse al día. La aplicación también entrega el welcome de un miembro nuevo; kolo-mls no lo conecta a ninguna biblioteca de transporte. Los formatos propios de Kolo alrededor de MLS usan kolo-codec.
El paquete raíz kolomls es el núcleo MLS, con el estado del grupo guardado en un Store que aportas tú. Un grupo de Kolo añade los paquetes cred (la credencial de un dispositivo de kolo-id), settle (las reglas de un dispositivo miembro: un commit se aplica solo con firmas de un quórum de settlers) y braid (el lado de los admins sobre kolo-braid), y backendstore guarda los grupos en un backend de kolo-store.
La aplicación aporta cinco cosas: un Authenticator que comprueba las credenciales (en un grupo de Kolo, cred.Authenticator, cuya función Expect es la comprobación de si una persona puede estar en el grupo; sin ella, se acepta a cualquier persona que añadan los admins), una Policy con las reglas de la aplicación (en un grupo de Kolo, settle.Policy), un Store que guarda el estado del grupo (MemStore en memoria, o backendstore.New sobre un backend de kolo-store), un reloj y las llamadas que la biblioteca pide en los momentos que devuelve (no tiene temporizadores), y al menos dos dispositivos admin.
Un cambio de época, asentado por los admins
El braid solo contiene los dispositivos admin, y cada miembro aplica un Commit solo con un quórum de firmas de settlers.
- En la época n cada dispositivo miembro es una hoja del ratchet tree del grupo. El braid del grupo solo contiene los dispositivos admin, y los settlers están entre ellos.
- Un admin crea un Commit, aquí para eliminar el dispositivo D. Guarda los bytes del Commit en los pins y escribe una referencia a ellos en el braid de los admins: el grupo, la época y el hash del Commit.
- Los settlers votan a partir del orden asentado del braid: la primera referencia aún sin decidir gana con un quórum de votos a favor. Tres settlers con la regla de mayoría necesitan dos.
- Los settlers firman el Commit decidido bajo el contexto kolo-mls/commit-settled/v0. Un quórum de estas firmas forma el commit asentado, que un admin guarda en los pins.
- La aplicación lleva el Commit y las firmas a los miembros. Cada miembro aplica el Commit solo con firmas de un quórum de los settlers de la época, y pasa a la época n + 1 con secretos nuevos. El dispositivo eliminado D no puede calcularlos.
- Cuando un Commit añade un miembro, su welcome se envía solo cuando ya existen las firmas de los settlers. La aplicación se lo entrega a ese miembro, que entra con el welcome, el commit asentado y el árbol cifrado de los pins.
Instalación
go get github.com/ciranda-dev/kolo-mlsNecesita Go 1.26 o posterior y es Go puro: sin cgo y sin nada que instalar. El paquete raíz importa solo la biblioteca estándar; cred, settle, braid y backendstore traen además módulos de Kolo (kolo-id, kolo-codec, kolo-braid, kolo-store). Un dispositivo miembro (settle, con cred y el núcleo) solo necesita el núcleo, kolo-id y kolo-codec. El lado admin (braid) funciona sobre kolo-braid y backendstore sobre un backend de kolo-store; el backend en disco de kolo-store compila con CGO_ENABLED=0 (con cgo activo, enlaza una biblioteca de compresión en C). kolo-mls está etiquetada como v0.1.0: para fijarla, ejecuta go get github.com/ciranda-dev/kolo-mls@v0.1.0.
Inicio rápido
Dos miembros en memoria: alice crea un grupo con un KeyPackage propio, añade a bob con el KeyPackage de él, el ratchet tree le llega junto al Welcome, y ella le envía un mensaje. Las credenciales son básicas y las comprueba un pequeño directorio que vincula cada nombre a una clave (un Authenticator), un sobre (Envelope) ata la generación de cada mensaje a sus datos autenticados (RFC 9750, sección 8.6), y la Policy no añade ninguna regla aparte de las del RFC 9420. Este es examples/basic del repositorio; ejecútalo con go run ./examples/basic en un clon.
// 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
}Imprime:
$ go run ./examples/basic
bob read "hello, bob" in epoch 1
members: 2
same epoch authenticator: trueUn grupo de Kolo usa en su lugar cred, settle y braid: la credencial es un certificado de dispositivo de kolo-id, un commit se aplica solo con firmas de un quórum de settlers, y los admins deciden cada época a través de kolo-braid. Conviene saber explica las épocas, los commits, los admins y los settlers.
Formatos
Los mensajes MLS usan la codificación del RFC 9420, cuya notación es el lenguaje de presentación de la sección 3 de RFC 9846, y no kolo-codec. Es una excepción deliberada a la regla de que los formatos de red de Kolo usan kolo-codec: los vectores de prueba oficiales y otras implementaciones exigen la codificación del RFC. Los sobres propios de Kolo alrededor de los mensajes MLS usan kolo-codec. La única suite de cifrado es la 0x0001, MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519, construida sobre crypto/hpke, crypto/ecdh, crypto/hkdf, crypto/ed25519, crypto/aes, crypto/cipher, crypto/sha256 y crypto/hmac, sin ninguna primitiva nueva. Los commits externos, las propuestas externas y ReInit se analizan y se comprueban en su sintaxis, y luego la política los rechaza con un error tipado.
| Formato | Dónde | Contenido, en kolo-codec |
|---|---|---|
Credencial de Kolo, tipo 0xF001 (cred) | la credencial de una hoja | un uvarint de versión (0), el certificado de dispositivo de kolo-id como bytes y la firma de 64 bytes del dispositivo sobre el binding |
Extensión de roles, tipo 0xF002 (settle) | una extensión del GroupContext | un uvarint de versión (0), el ID de grupo de 32 bytes del braid de los admins, un uvarint con la regla de quórum (1 Majority, 2 TwoThirds), y luego las claves de los dispositivos admin y las de los dispositivos settler, cada una con un contador y claves de 32 bytes en orden estrictamente creciente |
Sobre de generación (settle) | los datos autenticados de cada PrivateMessage de un grupo de Kolo | un uvarint de versión (0), la generación como uvarint y los datos autenticados de la aplicación como bytes |
Commit asentado (settle) | lo lleva la aplicación, y pins | la cadena kolo-mls/settled-commit/v0, la parte firmada que se describe abajo, un uvarint con el número de firmas y, para cada una, la clave de dispositivo de 32 bytes del settler y su firma de 64 bytes, con las claves en orden estrictamente creciente |
Entradas del braid (braid) | el braid de los admins | una referencia a un commit, un voto y una parte de firma, abajo |
El binding que firma un dispositivo es un uvarint de versión (0), la suite de cifrado como uvarint, la clave de firma MLS de 32 bytes de la hoja y el SHA-256 del certificado de dispositivo. La credencial ocupa como máximo 581 bytes (cred.MaxBody): una versión (1), la longitud del certificado (2), el mayor certificado con su padre aprobador (514) y la firma (64). La clave del dispositivo nunca firma bytes de MLS por sí misma: cada hoja tiene su propia clave de firma MLS.
La parte firmada de un commit asentado es un uvarint de versión (0), el ID de grupo de 32 bytes como bytes, la época como uvarint, cuatro valores de 32 bytes (el SHA-256 del MLSMessage del Commit, el del GroupContext de la época, el del GroupContext de la época siguiente y el ID de grupo del braid) y la posición asentada de la referencia del commit como uvarint. Cada settler la firma con la clave de su dispositivo, y un miembro aplica el commit solo con firmas válidas de un quórum de los settlers de la época.
Las tres entradas del braid empiezan con las cadenas kolo-mls/commit-ref/v0, kolo-mls/commit-vote/v0 y kolo-mls/commit-sig/v0 y llevan como bytes el certificado de dispositivo de quien las escribe. Una referencia añade el ID de grupo, la época y el SHA-256 del Commit. Un voto añade lo mismo, el SHA-256 del contexto anterior, un bool (aceptar o rechazar) y un uvarint con el motivo. Una parte de firma añade la parte firmada de arriba y la firma de 64 bytes del settler. kolo-log firma las entradas, como en cualquier entrada de un braid.
En los pins, las claves (settle.ObjectKey, SettledKey, TreeKey y ArchiveKey) empiezan con kolo-mls/object/ (un Commit, bajo el SHA-256 en hexadecimal de su MLSMessage), kolo-mls/settled/ y kolo-mls/tree/ (un commit asentado y un ratchet tree cifrado, cada uno bajo el ID de grupo en hexadecimal y la época) y kolo-mls/archive/ (los mensajes archivados de una época, bajo el ID de grupo en hexadecimal, la época y el SHA-256 en hexadecimal del mensaje). El árbol cifrado (settle.SealTree y settle.OpenTree) usa AES-128-GCM: la clave y el nonce se exportan de la época (RFC 9420, sección 8.5) con las etiquetas kolo-mls/ratchet-tree/v0 y kolo-mls/ratchet-tree-nonce/v0 y con la clave del dispositivo del admin que lo cifra como contexto, el ID de grupo y la época son los datos adicionales, y el resultado es esa clave de dispositivo de 32 bytes seguida del texto cifrado.
Dos firmas son propias de Kolo, cada una con su propia cadena de contexto Ed25519ctx, así que una firma hecha para un fin nunca se verifica como otro: kolo-mls/leaf-key/v0 (cred.LeafKeyContext, la firma del dispositivo sobre el binding) y kolo-mls/commit-settled/v0 (settle.SettledContext, la firma de un settler sobre un commit asentado). Este esquema de firmas es diseño propio de Kolo y no está en ningún RFC.
Los mensajes cifrados se rellenan hasta la longitud Padmé, como mucho alrededor de un 12 % más largos (RFC 9420, secciones 6.3 y 15.1).
Los key packages, sus hojas y los welcomes llevan valores GREASE aleatorios (RFC 9420, sección 13.5), para que los peers que rechazan valores desconocidos se descubran pronto, y los valores desconocidos que se reciben se ignoran donde lo dice la sección 13.4. Una implementación independiente rechaza una extensión GREASE en una hoja, un KeyPackage o un GroupInfo, en contra de las secciones 13.4, 13.5 y 17.3 del RFC 9420, así que rechaza estos key packages y welcomes. kolo-mls sigue el RFC.
Referencia de la API
La referencia de la API se genera a partir del código Go y está en inglés.
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.HourDefaultKeyPackageLifetime is the default lifetime of a new KeyPackage, which starts one hour before its creation.
const DefaultMaxLeafLifetime = 84*24*time.Hour + time.HourDefaultMaxLeafLifetime is the default bound on not_after - not_before of a key_package leaf: 84 days and one hour.
const DefaultMaxTreeBytes = 128 << 20DefaultMaxTreeBytes is the default bound on a ratchet tree a joiner accepts.
const DefaultPastEpochWindow = 10 * time.SecondDefaultPastEpochWindow is how long the previous epoch stays readable for late application messages after a Commit is applied.
Variables
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
)Funciones
func DeleteKeyPackage
func DeleteKeyPackage(st Store, keyPackage []byte) errorDeleteKeyPackage 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.CapabilitiesCapabilities 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.CredentialCredential 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 uint8Event 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.ExtensionExtension 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) errorApply 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() errorApplyPending 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() [][]byteCachedProposals 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() errorDiscardPending 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() uint64Epoch 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() []ExtensionExtensions returns a copy of the GroupContext extensions of the current epoch.
func (Group) GroupContext
func (g *Group) GroupContext() []byteGroupContext returns the encoded GroupContext of the current epoch.
func (Group) GroupID
func (g *Group) GroupID() []byteGroupID returns the group id.
func (Group) OwnLeaf
func (g *Group) OwnLeaf() uint32OwnLeaf 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() *PendingCommitPending returns the stored pending Commit, nil when there is none.
func (Group) PendingLeaves
func (g *Group) PendingLeaves() []*LeafNodePendingLeaves 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() boolRemoved reports whether an applied Commit removed this member.
func (Group) Tree
func (g *Group) Tree() TreeViewTree returns a read-only view of the ratchet tree of the current epoch.
type GroupContext
type GroupContext = schedule.GroupContextGroupContext 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.LeafNodeLeafNode 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() *MemStoreNewMemStore returns an empty MemStore.
func (MemStore) Apply
func (s *MemStore) Apply(b Batch) errorApply 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() *MemStoreClone 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.PSKIDPSKID 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() []byteCommit returns the Commit as an encoded MLSMessage.
func (PendingCommit) GroupContext
func (pc *PendingCommit) GroupContext() []byteGroupContext 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() []byteWelcome 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.ProposalProposal 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() []uint32Added returns the leaf indices the Commit adds.
func (StagedCommit) Committer
func (sc *StagedCommit) Committer() uint32Committer 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() []ExtensionExtensions returns the GroupContext extensions of the new epoch, also when the Commit removes this member.
func (StagedCommit) GroupContext
func (sc *StagedCommit) GroupContext() []byteGroupContext returns the encoded GroupContext of the new epoch, nil when this member is removed.
func (StagedCommit) Leaves
func (sc *StagedCommit) Leaves() []*LeafNodeLeaves 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() []uint32Removed returns the leaf indices the Commit removes, in increasing order.
func (StagedCommit) RemovesSelf
func (sc *StagedCommit) RemovesSelf() boolRemovesSelf 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) *LeafNodeLeaf 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() []uint32Members returns the indices of the non-blank leaves in increasing order.
Paquete 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 << 19DefaultMaxCached 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.SignatureSizeMaxBody is the largest credential body: version, the certificate with its length and the signature.
const Type = tree.CredentialKoloDeviceType is the credential type 0xF001 of a Kolo device, from the private-use range of RFC 9420 section 17.5.
Variables
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.
Funciones
func Binding
func Binding(signatureKey []byte, cert *koloid.DeviceCert) []byteBinding 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) errorRevoked 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) errorSuccessor 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) errorValidate 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.PublicKeyDevice returns the certified device key, nil without a certificate.
func (Credential) Encode
func (c *Credential) Encode() kolomls.CredentialEncode returns c as an MLS Credential, an empty one without a certificate.
func (Credential) Person
func (c *Credential) Person() ed25519.PublicKeyPerson returns the person key the certificate names, an unverified claim; nil without a certificate.
Paquete 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 = 0xF002RolesExtension 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.
Variables
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.
Funciones
func ArchiveKey
func ArchiveKey(gid []byte, epoch uint64, msg []byte) stringArchiveKey is the key of an archived message of epoch of group gid.
func ArchivePrefix
func ArchivePrefix(gid []byte, epoch uint64) stringArchivePrefix is the prefix of the archived messages of epoch of group gid: the messages sent in it.
func Capabilities
func Capabilities() kolomls.CapabilitiesCapabilities 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.ConfigNewConfig 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) stringObjectKey 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) stringSettledKey is the key of the SettledCommit of epoch of group gid.
func TreeKey
func TreeKey(gid []byte, epoch uint64) stringTreeKey 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.PSKIDID 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.LeafNodeAppliedLeaves 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() errorDiscardPending 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() uint64Epoch 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.ExtensionExtensions returns the GroupContext extensions of the current epoch.
func (Member) GroupContext
func (m *Member) GroupContext() []byteGroupContext returns the encoded GroupContext of the current epoch.
func (Member) GroupID
func (m *Member) GroupID() []byteGroupID returns the group id.
func (Member) Halted
func (m *Member) Halted() errorHalted 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() LimitsLimits returns the roles bounds of the group's Policy.
func (Member) MaxCommitBytes
func (m *Member) MaxCommitBytes() intMaxCommitBytes returns the bound on a Commit read from pins.
func (Member) OwnLeaf
func (m *Member) OwnLeaf() uint32OwnLeaf returns this device's leaf index.
func (Member) Pending
func (m *Member) Pending() *kolomls.PendingCommitPending returns this device's pending Commit, nil when there is none.
func (Member) PendingLeaves
func (m *Member) PendingLeaves() []*kolomls.LeafNodePendingLeaves 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() boolRemoved reports whether a settled Commit removed this device.
func (Member) RevokedLeaves
func (m *Member) RevokedLeaves() []uint32RevokedLeaves 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.StoreStore returns the Store the group lives in.
func (Member) Tree
func (m *Member) Tree() kolomls.TreeViewTree 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) errorCheckCommit applies the commit rule.
func (Policy) CheckJoin
func (p *Policy) CheckJoin(v kolomls.JoinView) errorCheckJoin 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) errorCheckProposal 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 uint8Quorum 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) boolAdmin reports whether device is an admin.
func (Roles) Encode
func (r *Roles) Encode() []byteEncode returns the extension data of r.
func (Roles) Extension
func (r *Roles) Extension() kolomls.ExtensionExtension returns r as a GroupContext extension.
func (Roles) Q
func (r *Roles) Q() intQ returns how many settlers a settled Commit needs.
func (Roles) RejectQuorum
func (r *Roles) RejectQuorum() intRejectQuorum 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) boolSettler 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) errorCheck 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() []byteEncode 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) intValid 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 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() []byteEncode returns the bytes a settler signs.
Paquete 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.SecondDefaultFetchTimeout 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.
Variables
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.
Funciones
func Assemble
func Assemble(t *settle.TBS, shares []settle.Share, roles *settle.Roles) *settle.SettledAssemble 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]byteEvidence 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.MemberMember 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) errorRefer 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) errorReference 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) errorReleaseWelcome 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) *BraidOrderNewBraidOrder 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) errorAppend 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]byteID 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) DecisionDecide 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) *IndexNewIndex 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 uint8Reason 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.
Paquete 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) *StoreNew 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) errorApply 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.
Conviene saber
Épocas y commits
- Cada época nueva empieza con un commit que da secretos nuevos solo a los miembros de esa época, así que un miembro quitado no puede calcular los secretos de ninguna época posterior. El coste de un commit crece con el logaritmo del tamaño del grupo, no con el tamaño mismo.
- Los admins hacen commit de los cambios de membresía y de grupo. Un miembro hace commit solo de su propia actualización de clave, y pide salir con una propuesta de su propia eliminación, de la que un admin hace commit. Solo los admins guardan una petición así, como mucho una por miembro, porque una propuesta guardada impide que un dispositivo envíe hasta que haya un commit (RFC 9420, sección 12.4).
- Un commit lleva sus propuestas por valor. Se rechaza un commit que nombre alguna propuesta por referencia, así que cada dispositivo tiene lo que necesita un commit, sean cuales sean las propuestas que leyó.
- Un miembro aplica un commit solo con firmas de un quórum de los settlers de la época, después de comprobar el grupo, la época, el braid, el contexto anterior, el hash del commit y el contexto al que lleva el commit. Un welcome para un miembro nuevo se envía solo después de que existan las firmas de los settlers.
- Un segundo commit asentado para la época que un miembro dejó detiene a ese miembro para siempre (
settle.ErrHalted), también tras un reinicio. Un miembro que no puede seguir un commit asentado conserva su estado y lo notifica (settle.ErrSettledMismatch); la biblioteca no vuelve a añadir a esos miembros. - Un miembro que guarda propuestas hace commit de ellas antes de enviar datos de la aplicación.
- Los commits externos, las propuestas externas y ReInit se rechazan.
Claves de los mensajes
- En los grupos de Kolo, las propuestas, los commits y los mensajes de aplicación viajan siempre cifrados (MLS PrivateMessage). El núcleo también puede enviar propuestas y commits en claro (PublicMessage), como permite el RFC; los datos de la aplicación van siempre cifrados.
- Un mensaje recibido gasta su clave solo después de que su firma se verifique. Un miembro puede construir un texto cifrado válido bajo la clave de otro miembro, porque cada miembro deriva todas las claves de la época, pero no puede firmar como ese miembro. Un commit conserva su clave hasta que se aplica, así que un dispositivo que se detiene a medias puede volver a leer el commit.
- Kolo ata la generación del mensaje a la parte firmada de cada mensaje cifrado (el sobre de generación), así que alguien de dentro no puede reenviar un mensaje firmado de otro miembro bajo una generación posterior y gastar esa generación (RFC 9750, sección 8.6). El núcleo deja esta vinculación a la aplicación (
Config.Envelope), y los grupos de Kolo siempre lo activan (settle.Envelope): sin él, ese reenvío funciona. - Cada clave se borra en la misma escritura de almacenamiento que la registra como usada, y las claves de una época se borran con la época, salvo que la época anterior sigue siendo legible durante 10 segundos después de un commit, para los mensajes de aplicación tardíos de los miembros que se quedan. El reloj de la aplicación termina esa ventana (
Config.PastEpochWindow). - Un receptor guarda una ventana de 5 generaciones por emisor, incluida la más nueva leída, así que un mensaje puede llegar hasta 4 generaciones por detrás de la más nueva. Un mensaje puede adelantar a un emisor como mucho 1.000 generaciones. Los dos valores se pueden configurar hasta 65.536 (
Config.OutOfOrderTolerance,Config.MaxForwardDistance). - Si falla una escritura de almacenamiento, el grupo rechaza todas las llamadas hasta que se vuelva a abrir desde el almacenamiento, porque la escritura pudo haberse hecho.
Identidad y dispositivos
- Un dispositivo es una hoja del árbol del grupo. La credencial es una credencial de Kolo (
cred): la cadena de certificados de dispositivo de kolo-id más la firma del dispositivo sobre la clave de firma MLS de la hoja. - La comprobación de la hoja verifica la cadena de certificados para la persona que nombra el certificado, rechaza una clave de firma de orden pequeño, y luego la aplicación decide si esa persona puede estar aquí (
cred.Authenticator.Expect). Sin una comprobación propia de la aplicación (Expectes nil), se acepta a cualquier persona: los admins decidieron añadir el dispositivo y los settlers firmaron el commit. - Solo el admin que añade un dispositivo comprueba la caducidad del certificado y sus revocaciones (
cred.Authenticator.NowyRevocations). Los settlers comprueban las revocaciones contra el registro de dispositivos del braid tal como estaba justo después de la posición asentada de la referencia del commit, cada vez que lo leen, así que deciden igual. Un miembro que tiene una revocación (settle.MemberOptions.Revocations) descarta los mensajes de ese dispositivo pero sigue aplicando los commits asentados. Todo receptor acepta un certificado caducado, como recomienda la sección 5.3.2 del RFC 9420. - Un dispositivo nuevo de la misma persona entra como una hoja nueva. Un dispositivo revocado se quita del grupo con un commit. Quitar a una persona quita todos sus dispositivos en un solo commit.
Admins y settlers
Las mismas reglas valen para un grupo de tres y para un grupo de treinta mil.
- El braid del grupo contiene solo los dispositivos admin, y los settlers están entre ellos. Los miembros corrientes nunca son miembros del braid. El conjunto de settlers va dentro del propio grupo, en la extensión de roles (
settle.Roles), que solo los admins pueden cambiar. - El orden asentado del braid decide el único commit de cada época. El braid contiene solo una referencia pequeña al commit (grupo, época y el hash de los bytes del commit), un voto y una parte de firma. La aplicación lleva los bytes del commit y las firmas de los settlers (por ejemplo por kolo-gossip) y los guarda en pins.
- La primera referencia aún no decidida gana con un quórum q de votos a favor, o pierde con s - q + 1 votos en contra (s settlers), así que el grupo sigue adelante cuando los settlers no coinciden en si un commit estaba disponible. La siguiente referencia de un admin cuenta solo después de que se rechazó la anterior, así que un admin retrasa al grupo como mucho un tiempo de espera de descarga cada vez.
- Un settler vota en contra de un commit que no pudo descargar en un minuto (ante cualquier error de descarga). Acepta un cambio de roles solo cuando nombra los admins, los asientos de settler y el quórum del propio braid, y solo con la aprobación de su propia aplicación (
braid.Options.ApproveRoles; sin ella, se rechaza todo cambio así) cuando el cambio añade un settler, cambia la regla de quórum o quita a un admin o settler que no está revocado; añadir un admin o quitar un dispositivo revocado no la necesita. - Cada entrada del braid lleva el certificado de dispositivo de quien la escribe, y el apply del braid rechaza una entrada cuyo escritor revoca el registro de dispositivos en la posición de esa misma entrada, así que un admin o settler revocado pierde sus referencias, votos y partes de firma en una misma posición para todos los peers, sin necesidad de quitarlo del braid.
- Un settler registra cada voto, parte de firma y primera descarga fallida antes de escribir, así que un reinicio nunca emite un voto distinto ni reinicia el tiempo de espera, y una vez que firmó en una época no vuelve a votar ni a firmar en ella.
- Después de cada commit, un admin guarda el ratchet tree en los pins, cifrado con una clave exportada de la época nueva para el dispositivo de ese admin, con el ID de grupo y la época atados. Los admins que funcionan sobre kolo-braid lo sirven a quienes se unen.
- Cuando los settlers se pierden para siempre, un settler de la última época inicia un grupo sucesor (
braid.Admin.Succeed) cuyo primer commit lleva una clave de rama de esa época (RFC 9420, sección 11.3). Un miembro se une solo cuando quien lo creó era un settler del grupo antiguo, no está revocado hasta donde sabe el miembro, y todo dispositivo que contiene era miembro de él. La aplicación deja que un miembro acepte un sucesor solo cuando se sabe que el quórum antiguo se perdió (settle.Policy.Predecessor; sin él, se rechaza todo sucesor).
Lo que este diseño no impide:
- s - q + 1 settlers que voten en contra de todo detienen todos los commits, incluida su propia expulsión (con cuatro settlers y la regla de mayoría, dos).
- Un admin cuya referencia se ordena primero puede ganar épocas con commits que no cambian nada, hasta que otro admin lo quite del braid.
- Un admin puede quitar del braid a settlers honestos y detener el grupo.
- Con uno o dos settlers, un dispositivo settler robado puede detener el grupo hasta que se cree un grupo nuevo.
Ponerse al día e historial
- Una persona que se une más tarde a un grupo lee solo los mensajes desde el momento en que se unió. No hay historial para ella, y la biblioteca no tiene ninguna interfaz de historial.
- El nuevo dispositivo de una misma persona solo lee desde el momento en que se une. kolo-mls no tiene ninguna transferencia del historial desde otro dispositivo de esa persona; la aplicación tiene que mover el historial por su cuenta. Si se pierden todos los dispositivos de una persona, la frase de recuperación restaura la identidad, no los mensajes.
- Los dispositivos que estaban en el grupo pero sin conexión se ponen al día desde los pins: descargan los commits posteriores a su última época con las firmas de sus settlers (
settle.Member.CatchUp), y el texto cifrado archivado de cada época a la que pertenecieron, y avanzan una época cada vez. - Los mensajes de la época siguiente esperan hasta su commit, y se descartan primero los más antiguos pasados 16 MiB. Un dispositivo que estuvo ausente lee el archivo de cada época de una en una, en pasadas dentro de 16 MiB de heap, así que una época de cualquier tamaño se lee entera; los mensajes que no pudo leer (un valor que no se abre, que no coincide con su clave o que pasa del límite) se notifican (
settle.ErrCatchUp), nunca la época. Cada lectura desde los pins pide un límite, así que unos pins hostiles no pueden darle más a un dispositivo.
Dispositivos inactivos
Un dispositivo inactivo nunca se quita automáticamente. Un dispositivo que está mucho tiempo sin conexión sigue siendo miembro y se pone al día cuando vuelve. La propia biblioteca no quita ningún dispositivo. Una aplicación puede mostrar una lista de dispositivos inactivos para que una persona o un admin quite un dispositivo a mano.
Esto tiene costes. Un dispositivo olvidado conserva su clave antigua en el árbol y sigue recibiendo secretos nuevos, así que si lo roban más tarde, quien lo tenga puede leer lo que se envió después de su última actualización hasta que se quite. Su disco conserva los secretos de su última época. Y cada commit del grupo debe seguir disponible en los pins mientras el grupo viva.
Valores por defecto
Un valor cero de un ajuste significa su valor por defecto, y el comentario de documentación de cada ajuste dice qué hace un valor negativo (sin límite, no guardar ninguno, o rechazo); los límites de los roles y la caché de identidades toman como valor por defecto cualquier valor de cero o menos. Todo límite es configurable salvo los que fija el propio formato, y cada valor por defecto tiene una fuente escrita: el RFC, una especificación publicada o una medición. Los tamaños se comprueban antes de reservar memoria, y ninguna reserva se dimensiona a partir de una longitud no fiable. Un ajuste nombrado sin paquete pertenece al paquete raíz kolomls.
Mensajes y claves:
| Límite | Ajuste | Valor por defecto | Por qué |
|---|---|---|---|
| Ventana de generaciones que se guardan por emisor, para la entrega desordenada | Config.OutOfOrderTolerance | 5 por emisor y tipo de mensaje, incluida la generación más nueva leída, así que 4 más antiguas siguen siendo legibles | memoria y secreto hacia adelante dentro de una época; el valor de una implementación de MLS publicada |
| Pasos del ratchet hacia adelante para un mensaje | Config.MaxForwardDistance | 1.000 | CPU frente a un número de generación hostil; el valor de la misma implementación |
| Mayor ventana o distancia hacia adelante que se puede configurar | fijo | 65.536 | CPU por mensaje recibido: un mensaje que mueve un ratchet tan lejos y guarda cada clave cuesta unos 0,15 s de CPU, medido |
| Época anterior guardada para mensajes tardíos | Config.PastEpochWindow | 10 segundos después de aplicar un commit, solo la época anterior, para los mensajes de aplicación de los miembros que se quedan; un valor negativo no guarda ninguna | secreto hacia adelante frente a la entrega tardía; un protocolo publicado de medios en grupo guarda las claves de la época anterior durante 10 segundos; el reloj de quien llama termina la ventana |
| Mensajes por emisor y época | fijo | 2^32 - 1, el contador de generación (RFC 9420, sección 6.3.2) | espacio de nonces |
| Claves de reanudación de épocas pasadas que se guardan | Config.ResumptionPSKs | ninguna: solo las de la época actual; se rechaza un valor negativo | secreto hacia adelante de las épocas pasadas; el RFC 9420, sección 8.6, pide un límite definido |
| Intervalo de actualización de un dispositivo en línea | la política de la aplicación | una por día | seguridad posterior al compromiso; el ejemplo del RFC 9420, sección 3.2; una política que sigue la aplicación |
Tamaños y decodificación:
| Límite | Ajuste | Valor por defecto | Por qué |
|---|---|---|---|
| Vida de un key package | KeyPackageOptions.Lifetime para un key package nuevo; Config.MaxLeafLifetime para el límite que comprueba quien recibe (negativo es sin límite) | 84 días, empezando una hora antes de la creación por el desfase de reloj; se rechazan las hojas cuya vida es mayor que 84 días y una hora | claves de unión caducadas; 84 días es el valor por defecto de una implementación de MLS publicada, y el RFC 9420, sección 7.2, exige un máximo |
| Tamaño de un mensaje MLS | el de la biblioteca que lo transporta | el que marque la biblioteca que lo transporta | memoria, entrada hostil |
| Tamaño de un welcome | el de la biblioteca que lo transporta | lo fija la aplicación que lo entrega | memoria |
| Bytes de ratchet tree que se aceptan al unirse | JoinOptions.MaxTreeBytes | 128 MiB; un valor negativo es sin límite | memoria; medido: un grupo de 100.000 miembros con credenciales grandes necesita unos 83 MB, y el árbol hostil más costoso que se midió ocupa unos 7 bytes de memoria por byte recibido, así que el valor por defecto acota una unión cerca de 0,9 GiB |
| Credencial de Kolo | fijo (cred.MaxBody) | 581 bytes | decodificación; el mayor certificado de dispositivo con su padre aprobador (514), su longitud, una versión y la firma del dispositivo, el máximo del propio formato |
| Identidades de cliente en caché | cred.Authenticator.MaxCached | 524.288 | memoria; más que las hojas del mayor árbol que un nuevo miembro acepta por defecto (la hoja de Kolo más pequeña, medida en 471 bytes, da como mucho 284.359 en 128 MiB); la caché se vacía cuando se llena |
| Propuestas en caché en una época | Policy.CheckProposal | las deja a la política de la aplicación; los grupos de Kolo guardan solo la eliminación propia de un miembro, solo en los admins, como mucho una por miembro y menos que miembros tiene el grupo | memoria; los commits de Kolo llevan sus propuestas por valor |
Roles y commits:
| Límite | Ajuste | Valor por defecto | Por qué |
|---|---|---|---|
| Admins y settlers en los roles de un grupo | settle.Policy.Limits.MaxAdmins y settle.Policy.Limits.MaxSettlers | ninguno: cero o menos es sin límite, y un valor positivo es un límite que elige la aplicación | memoria y trabajo de firmas por commit: se rechaza un número mayor que las claves que cabe en la extensión (32 bytes cada una), y el transporte acota la extensión; el trabajo de firmas es como mucho una comprobación por settler |
| Firmas en un commit asentado | sigue el límite de settlers | como mucho una por settler del grupo | trabajo de firmas por commit |
| Referencias de un admin | fijo | un candidato cada vez: la siguiente referencia de un admin cuenta solo después de que se rechazó la anterior | liveness |
| Espera de un commit en los pins antes de que un settler vote en contra | braid.Options.FetchTimeout | 60 segundos, ante cualquier error de descarga; el reloj de quien llama, conservado entre reinicios; se rechaza un valor negativo | liveness del grupo; el tiempo de espera de mensajes de la capa de streams sobre la que se sincroniza el braid |
| Lecturas del registro en la posición de una referencia | fijo | una por certificado de hoja candidato y época, conservada durante la época, de una en una | CPU y almacenamiento; cada lectura reproduce el braid desde la última lectura de ese tipo |
Ponerse al día:
| Límite | Ajuste | Valor por defecto | Por qué |
|---|---|---|---|
| Mensajes de la época siguiente guardados para más tarde | settle.MemberOptions.MaxBufferedBytes | 16 MiB, y se descartan primero los más antiguos; un valor negativo no guarda ninguno | memoria; el límite que el braid de los admins pone a las entradas que esperan a una anterior. Las épocas posteriores se vuelven a descargar tras ponerse al día |
| Mensajes archivados que se leen por época al ponerse al día | settle.MemberOptions.MaxCatchUpBytes | 16 MiB de heap por pasada, que es también el mayor mensaje archivado; una época de cualquier tamaño se lee en pasadas dentro de ese límite (unos 54.000 mensajes por pasada), y cada pasada lee todos los mensajes de la época, sin omitir ninguno; un valor que pasa del límite, uno que no coincide con su clave o no se abre, y un listado que los pins hicieron mal se notifican con un error mientras la época se sigue aplicando; un valor negativo es sin límite | memoria |
| Commit que se lee de los pins | settle.MemberOptions.MaxCommitBytes | 128 MiB; un valor negativo es sin límite | memoria; el límite del árbol, porque los KeyPackages que añade un Commit pasan a ser las hojas del árbol |
| Commit asentado que se lee de los pins | sigue el límite de settlers | 512 bytes más 96 por firma de settler | memoria; sale de la codificación |
| Árbol cifrado que se lee de los pins | sigue JoinOptions.MaxTreeBytes | el límite del árbol de quien se une más 48 bytes, que se pide a los pins antes de leer el blob | memoria |
El tamaño del grupo, los miembros por persona y el número de grupos no son límites de la biblioteca. Los dispositivos inactivos nunca se quitan automáticamente, y los commits se guardan en los pins mientras el grupo viva, porque ningún dispositivo se expulsa por estar inactivo. La capa de Kolo toma el reloj de la aplicación (settle.NewConfig, braid.Options.Now) y se niega a funcionar sin uno; el núcleo usa Config.Now para la vida de las hojas que envía y para la ventana de la época anterior, y recurre al reloj del sistema cuando no se configura.
Seguridad
- Quien se une más tarde lee solo los mensajes desde el momento en que se unió. No hay historial para esa persona ni una interfaz de historial.
- Un grupo cambia solo cuando se aplica un Commit. En un grupo de Kolo un dispositivo aplica un Commit solo con firmas de un quórum de los dispositivos settlers del grupo, así que un dispositivo admin por sí solo no puede dividir el grupo ni cambiar sus miembros.
- Si te roban uno de tus dispositivos, quítalo: desde ese momento no lee nada nuevo. Un dispositivo que dejas de usar no se quita solo: sigue en el grupo y puede leer mensajes nuevos cuando vuelve, así que quita los dispositivos que ya no usas.
- Las claves se borran después de usarse, en la misma escritura que las registra como usadas, así que un dispositivo que se robe más tarde no puede abrir copias cifradas antiguas con las claves de la biblioteca. Borrar del disco es un mejor esfuerzo:
backendstorequita las claves del lote, pero las copias de seguridad, las instantáneas y los bloques liberados pueden conservar sus bytes, y una imagen del disco tomada antes de un borrado contiene lo que contenía entonces. Un dispositivo inactivo conserva en el disco los secretos de su última época. - Un mensaje gasta su clave solo después de que su firma se comprueba. Con el sobre de Kolo, un miembro no puede repetir el mensaje firmado de otro miembro bajo una generación posterior para gastar esa generación.
- Ninguna API devuelve un secreto de época:
Exportderiva un secreto para una etiqueta yEpochAuthenticatordevuelve el autenticador de época.Closepone a cero los secretos que se guardan en memoria. Las claves privadas, las semillas y los secretos de época nunca se registran en un log ni se ponen en un mensaje de error.
Lo que MLS no da:
- MLS no da historial a quienes se unen más tarde, ni forma de volver a leer lo que un dispositivo ya consumió y borró.
- MLS no protege lo que un miembro quitado ya tiene.
- MLS no protege frente a un Authentication Service comprometido. En Kolo eso es la frase de recuperación y los dispositivos aprobadores de kolo-id.
- MLS no da garantía de entrega: quien transporta los mensajes puede retrasarlos o descartarlos.
- MLS no protege frente a que alguien de dentro repita mensajes en una época, salvo que la aplicación configure un
Envelope, como hacen los grupos de Kolo (el sobre de generación). - No hay defensa frente a un Commit malicioso que solo algunos miembros pueden detectar. Un miembro que no puede seguir un Commit asentado conserva su estado y notifica
settle.ErrSettledMismatch. - No hay protección frente a la denegación de servicio. Los settlers que votan en contra de todo detienen cada commit, y un admin puede quitar del braid a settlers honestos y bloquear el grupo; con uno o dos settlers, un dispositivo settler robado puede bloquear el grupo hasta que se crea un grupo sucesor.
- El ID de grupo, la época y los tiempos son visibles en cada mensaje, y el transporte muestra qué dispositivo lo envió. Se acepta que los dispositivos se puedan vincular entre sí.
- Una expulsión espera mientras hay menos de un quórum de settlers en línea. Mantén al menos dos dispositivos admin.
Lo que la biblioteca espera de quien la llama:
- Un solo
Group(osettle.Member) por ID de grupo a la vez en un Store, y nunca dos copias del estado de un dispositivo: dos escribirían árboles de secretos que divergen.Create,JoinyOpende un mismo ID de grupo no se ejecutan a la vez. - Un
StorecuyoApplysea atómico y duradero, y seguro para uso concurrente cuando se comparte. Una escritura fallida hace que el Group rechace cada llamada hasta que se vuelva a abrir. - Un reloj. La capa de Kolo se niega a funcionar sin uno; el núcleo recurre al reloj del sistema. La biblioteca no tiene temporizadores: llama a
ExpirePastEpochy abraid.Admin.Stepde nuevo en los momentos que devuelven (Admin.NextDeadline). - Un
Authenticatory unaPolicyque decidan igual en todos los miembros. Los miembros que deciden distinto dividen el grupo (RFC 9750, sección 6.5). - Entregar los Commits a
Processen orden de época, uno por época, y en un grupo de Kolo solo con su SettledCommit (settle.Member.ApplySettled). - Entregar las propuestas referenciadas antes del Commit que las nombra, y un Welcome solo después de que su Commit esté asentado y firmado.
- Guardar cada mensaje de una época futura y entregarlo de nuevo tras ponerse al día (
settle.Memberlo guarda dentro de un límite). - Mantener en los pins cada Commit, su SettledCommit y el árbol cifrado mientras viva el grupo, y los mensajes archivados de cada época mientras un miembro de esa época pueda ir por detrás.
- Llamar a
ApplyPendingo aDiscardPendingcuando el Delivery Service haya elegido el Commit de la época. - En un grupo de Kolo, ejecutar el bucle del miembro (
Receive,ApplySettled,CatchUp,ExpirePastEpoch) en cada dispositivo y el bucle del admin (Steptras cada evento del braid y enNextDeadline) en cada dispositivo admin, y decidir los cambios de roles enbraid.Options.ApproveRoles.
Estado
Experimental. La API puede cambiar antes de v1.0.0. La versión 0.1.0 está etiquetada.
- Hecho: el núcleo del RFC 9420 para la suite de cifrado 0x0001 (grupos, KeyPackages, Welcomes con valores GREASE, cada comprobación de propuestas y de Commit, mensajes de aplicación, handshakes como PublicMessage y PrivateMessage, la ventana de la época anterior, el Store con un lote atómico por cambio); la API pública (el paquete raíz
kolomlsy los paquetescred,settle,braidybackendstore, conexamples/basic); la capa de Kolo (la credencial 0xF001, la extensión de roles 0xF002, la regla de commit, el sobre de generación, los commits asentados, el lado admin sobre kolo-braid, los dispositivos miembros que se ponen al día desde los pins, el árbol cifrado para quienes se unen y el grupo sucesor); y una comprobación cruzada con implementaciones independientes. - Probado: los vectores de prueba oficiales de MLS (descargados con
scripts/fetch-vectors.shen un commit fijado y con su SHA-256 comprobado, y exigidos porscripts/release-check.sh), tests unitarios y de escenarios en memoria, el programaexamples/basiccomprobado por un test, sobre braids reales y entre procesos en 127.0.0.1, objetivos de fuzz para los decodificadores del núcleo y de la capa de Kolo, y tests que fallan cuando se quita una regla de validación. - No incluido: volver a añadir a los miembros que no pueden seguir un Commit asentado (se notifican con
settle.ErrSettledMismatch). Los commits externos, las propuestas externas y ReInit los rechaza la política. - No verificado: el tiempo que tarda en propagarse una expulsión (la biblioteca no lo acota).
Errores
| Error | Mensaje |
|---|---|
ErrClosed | kolomls: group closed |
ErrConfirmationTag | kolomls: invalid confirmation tag |
ErrCredential | kolomls: credential refused |
ErrDecrypt | kolomls: decryption failed |
ErrFutureEpoch | kolomls: message for a future epoch |
ErrGenerationExhausted | kolomls: generations exhausted |
ErrGroupExists | kolomls: group already exists |
ErrInvalidArgument | kolomls: invalid argument |
ErrInvalidCommit | kolomls: invalid commit |
ErrInvalidKeyPackage | kolomls: invalid key package |
ErrInvalidLeaf | kolomls: invalid leaf node |
ErrInvalidProposal | kolomls: invalid proposal |
ErrInvalidTree | kolomls: invalid ratchet tree |
ErrInvalidWelcome | kolomls: invalid welcome |
ErrKeyPackageNotFound | kolomls: key package not found |
ErrMalformed | kolomls: malformed encoding |
ErrMembershipTag | kolomls: invalid membership tag |
ErrNotFound | kolomls: not found |
ErrPSKNotFound | kolomls: pre-shared key not found |
ErrPendingCommit | kolomls: pending commit |
ErrPendingProposals | kolomls: proposals pending |
ErrPolicy | kolomls: refused by policy |
ErrRemoved | kolomls: removed from the group |
ErrReplay | kolomls: generation already used |
ErrSignature | kolomls: invalid signature |
ErrStore | kolomls: store failed |
ErrTooFarAhead | kolomls: generation too far ahead |
ErrTooLong | kolomls: vector longer than 2^30 - 1 bytes |
ErrTooOld | kolomls: generation too old |
ErrUnknownProposal | kolomls: unknown proposal reference |
ErrUnknownSender | kolomls: sender is not a member |
ErrUnsupported | kolomls: unsupported |
ErrWrongEpoch | kolomls: message for a past epoch |
ErrWrongGroup | kolomls: message for another group |
cred.ErrCredential | kolomls: invalid Kolo credential |
settle.ErrBuffered | kolomls: message of the next epoch kept for later |
settle.ErrCatchUp | kolomls: epoch archive refused |
settle.ErrEnvelope | kolomls: invalid authenticated data envelope |
settle.ErrEquivocation | kolomls: two settled commits for one epoch |
settle.ErrHalted | kolomls: member halted |
settle.ErrMissing | kolomls: not on pins |
settle.ErrNotHeld | kolomls: leave requests are held by admins only |
settle.ErrNotSettled | kolomls: commit not settled |
settle.ErrPinTooLarge | kolomls: pinned data past the bound |
settle.ErrRevokedSender | kolomls: message of a revoked device dropped |
settle.ErrRoles | kolomls: invalid roles extension |
settle.ErrRule | kolomls: Kolo group rule |
settle.ErrSealedTree | kolomls: encrypted tree does not open |
settle.ErrSettledMismatch | kolomls: settled commit does not match |
braid.ErrDecision | kolomls: decision differs from the signed one |
braid.ErrEntry | kolomls: invalid braid entry |
braid.ErrNotApproved | kolomls: roles change not approved |
braid.ErrRoster | kolomls: roles do not match the braid |
La tabla lista los errores del paquete raíz y de cred, settle y braid, estos tres con el nombre de su paquete. Comprueba los errores con errors.Is. Los mensajes de error propios de la biblioteca empiezan por kolomls:. ErrCredential, ErrPolicy y ErrStore envuelven un error del Authenticator, de la Policy y del Store, y cred.ErrCredential envuelve los errores de kolo-id.
Referencias
- RFC 9420, The Messaging Layer Security (MLS) Protocol (Proposed Standard, julio de 2023).
- Toma: el protocolo: el framing, el ratchet tree, TreeKEM, el key schedule, las propuestas, los commits, el Welcome y los code points, para la suite de cifrado 0x0001.
- No implementa: otras suites de cifrado. Los commits externos, las propuestas externas y ReInit se analizan y la política los rechaza.
- RFC 9750, The Messaging Layer Security (MLS) Architecture (Informational, abril de 2025).
- Toma: los roles del Authentication Service y del Delivery Service y las consideraciones de seguridad que dan forma al diseño, incluida la vinculación de la generación de la sección 8.6.
- No implementa: un Delivery Service o un Authentication Service propios. No define ningún protocolo.
- RFC 9180, Hybrid Public Key Encryption (Informational, febrero de 2022).
- Toma: el esquema HPKE que usa el RFC 9420 para cifrar secretos a la clave de un miembro (DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM), mediante
crypto/hpke. - No implementa: otros KEM, KDF y AEAD.
- Toma: el esquema HPKE que usa el RFC 9420 para cifrar secretos a la clave de un miembro (DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM), mediante
- RFC 9846, The Transport Layer Security (TLS) Protocol Version 1.3, sección 3, "Presentation Language" (Proposed Standard, julio de 2026; sustituye al RFC 8446).
- Toma: la notación y la codificación de cada estructura de MLS. El RFC 9420 se escribió sobre el RFC 8446, cuya sección 3 define el mismo lenguaje.
- No implementa: el resto de TLS.
- Vectores de prueba del grupo de trabajo de MLS, repositorio
mlswg/mls-implementationsen el commit2034fe72e0c805a683ba76165660c834f2a8142a.- Toma: los vectores de prueba oficiales que debe pasar el núcleo. El repositorio no tiene archivo de licencia, así que los vectores se descargan para probar y nunca se copian al repositorio de kolo-mls.
- No implementa: nada; son solo entrada de pruebas.