kolo docsbeta

kolo-pin

Un peer que guarda datos cifrados de otros sin poder leerlos.

En esta página

Un peer de anclaje mantiene disponibles los logs de kolo-log de otras personas mientras sus propietarios están desconectados: el historial de un chat, o lo que escribió uno de tus dispositivos, para tus otros dispositivos. Es una réplica de kolo-sync sin claves de entrada, y verifica lo que guarda como lo haría un monitor de Certificate Transparency (RFC 9162). Comprueba y guarda registros firmados, textos cifrados y marcas de borrado, y se los sirve a cualquier cliente de kolo-sync, por pull o con Fetch, pero nunca tiene las claves para leerlos. Un propietario lo autoriza con una capacidad firmada que caduca; no hay cuentas. Select reparte los datos entre peers de anclaje con rendezvous hashing. El paquete de Go se llama pin, y el comando kolo-pin ejecuta un peer de anclaje en un servidor pequeño.

Todos los pasos

Un pin solo guarda texto cifrado

El pin mantiene tu log en línea mientras tus dispositivos están apagados. Ve tamaños, cantidades y momentos, no el contenido.

  1. Tu dispositivo se conecta al pin con kolo-secure y envía ADD con el ID del log y una capacidad.
  2. El pin comprueba la capacidad y luego trae el log de tu dispositivo con kolo-sync. Tu dispositivo lo ofrece solo con acceso al texto cifrado, así que no se envía ninguna clave de entrada.
  3. El pin guarda los registros, el texto cifrado y las marcas de borrado bajo el propietario, y responde con las entradas, los bytes usados, la cuota y la caducidad.
  4. Cualquier peer que conozca la clave del propietario y el ID del log puede traer el log desde el pin, como texto cifrado.
  5. Las claves de entrada solo salen de los dispositivos del propietario. Sin ellas, ni el pin ni los otros peers pueden leer las entradas.

Instalación

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

Compila con CGO_ENABLED=0 para obtener un binario estático. El comando está en cmd/kolo-pin; Ejecuta un peer de anclaje en un VPS lo explica paso a paso.

Inicio rápido

Este programa ejecuta un peer de anclaje por loopback con sus datos en un directorio temporal. Alice ancla un log y se desconecta, y después su móvil hace pull del texto cifrado del log desde el peer de anclaje.

main.go
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	koloid "github.com/ciranda-dev/kolo-id"
	"github.com/ciranda-dev/kolo-pin"
	kolosecure "github.com/ciranda-dev/kolo-secure"
	kolostore "github.com/ciranda-dev/kolo-store"
	kolosync "github.com/ciranda-dev/kolo-sync"
)

func main() {
	dir, err := os.MkdirTemp("", "kolo-pin")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// The pinning peer: its key and store live in dir.
	pid, err := pin.LoadIdentity(dir)
	if err != nil {
		log.Fatal(err)
	}
	ln, err := kolosecure.Listen(ctx, "127.0.0.1:0", pid, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()
	sctx, stop := context.WithCancel(ctx)
	served := make(chan error, 1)
	go func() { served <- pin.Serve(sctx, ln, pin.Options{Dir: dir}) }()
	peer := pin.Peer{ID: pid.PublicKey(), Addr: ln.Addr().String()}

	// Alice writes a log and lets the pinning peer keep it for 30 days, up to 100 MB.
	alice, err := koloid.Generate()
	if err != nil {
		log.Fatal(err)
	}
	as := kolostore.New(kolostore.NewMemory())
	l, err := as.Create(alice)
	if err != nil {
		log.Fatal(err)
	}
	for _, v := range []string{"hello", "from", "alice"} {
		if _, err := l.Append([]byte(v)); err != nil {
			log.Fatal(err)
		}
	}
	capability, err := pin.Issue(alice, pin.Capability{Peer: peer.ID, Expires: time.Now().Add(30 * 24 * time.Hour), Quota: 100_000_000})
	if err != nil {
		log.Fatal(err)
	}
	info, err := pin.Add(ctx, alice, peer, l, capability)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("pinned %d entries, %d bytes used\n", info.Entries, info.Used)
	logID := l.ID()
	as.Close() // alice goes offline

	// Her phone pulls the ciphertext from the pinning peer and checks it against her key.
	phone, err := koloid.Generate()
	if err != nil {
		log.Fatal(err)
	}
	conn, err := kolosecure.Dial(ctx, peer.Addr, phone, peer.ID, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	ps := kolostore.New(kolostore.NewMemory())
	defer ps.Close()
	header, err := kolosync.FetchHeader(ctx, conn, alice.PublicKey(), logID)
	if err != nil {
		log.Fatal(err)
	}
	rep, err := ps.OpenReplica(alice.PublicKey(), logID, header)
	if err != nil {
		log.Fatal(err)
	}
	if err := kolosync.Pull(ctx, conn, rep); err != nil {
		log.Fatal(err)
	}
	_, err = rep.Get(0)
	fmt.Printf("phone holds %d verified entries; reading one without its key: %v\n", rep.Len(), err)

	stop()
	if err := <-served; err != context.Canceled {
		log.Fatal(err)
	}
}

Imprime:

Texto
pinned 3 entries, 2305 bytes used
phone holds 3 verified entries; reading one without its key: kololog: entry key not available

Más tarde, el móvil recibe las claves de las entradas de los propios dispositivos de Alice, con acceso Keys de kolo-sync. Entonces solo viajan las claves, porque el texto cifrado ya está allí. Para guardar un log en varios peers de anclaje, consulta Cómo elegir peers de anclaje.

Referencia de la API

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

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

Package pin runs and uses pinning peers: a peer that stores encrypted data for others without being able to read it.

A pinning peer keeps kolo-log logs available while their owners are offline. Serve runs one on a kolo-secure listener. Add makes it pull an owner's log over kolo-sync, as a replica without entry keys, under a capability the owner signed; Status and Remove ask about or delete a log, and Revoke delivers a revoke note. Any kolo-sync client pulls or fetches the hosted logs from it like from any other replica, as ciphertext only. Select and AddMany spread a log over several pinning peers.

Experimental: the API may change before v1.0.0.

Comando

kolo-pin
usage:
  kolo-pin run -data DIR [flags]   run a pinning peer
  kolo-pin id -data DIR            print the pinning peer's public key, creating it if needed

Run "kolo-pin run -h" for the flags and their environment variables.

kolo-pin run

kolo-pin run
Usage of kolo-pin run:
  -add-timeout time
    	the most time one add may spend pulling a log, such as 10m; default none (KOLO_PIN_ADD_TIMEOUT)
  -data dir
    	data dir, private (0700): identity.key and the store (KOLO_PIN_DATA)
  -health address
    	TCP address of the HTTP health endpoint /healthz, IPv4, or "off" (KOLO_PIN_HEALTH) (default "127.0.0.1:7451")
  -listen address
    	UDP address for kolo-secure connections, IPv4; "0.0.0.0:7450" on a VPS (KOLO_PIN_LISTEN) (default "127.0.0.1:7450")
  -log-format format
    	format of the logs on stderr: text or json (KOLO_PIN_LOG_FORMAT) (default "text")
  -log-level level
    	level: debug, info, warn or error (KOLO_PIN_LOG_LEVEL) (default "info")
  -max-bytes bytes
    	the most bytes stored for all owners, such as 500MB or 2TiB (KOLO_PIN_MAX_BYTES) (default "100GB")
  -max-conns string
    	the most connections at once, handshaking or open; default 100, up to 10000 (KOLO_PIN_MAX_CONNS)
  -max-conns-per-ip string
    	the most connections from one source address; default 4, at most -max-conns (KOLO_PIN_MAX_CONNS_PER_IP)
  -max-owners string
    	the most owner records kept, one per owner key ever seen; default 100000 (KOLO_PIN_MAX_OWNERS)
  -metrics address
    	TCP address of the Prometheus endpoint /metrics, IPv4, or "off" (KOLO_PIN_METRICS) (default "127.0.0.1:7452")
  -owners keys
    	comma-separated hex owner keys to accept; empty accepts any owner, and anyone can then fill the disk (KOLO_PIN_OWNERS)

kolo-pin id

kolo-pin id
Usage of kolo-pin id:
  -data dir
    	data dir, private (0700): identity.key and the store (KOLO_PIN_DATA)

Constantes

const (
	// CapabilityContext is the Ed25519ctx context of a capability signature.
	CapabilityContext = "kolo-pin/capability/v0"
	// RevokeContext is the Ed25519ctx context of a revoke note signature.
	RevokeContext = "kolo-pin/revoke/v0"
	// MaxLogs is the most log IDs one capability lists.
	MaxLogs = 256
	// MaxCapabilitySize is the size of a capability that lists MaxLogs logs.
	MaxCapabilitySize = 1 + 2*32 + 3*10 + 2 + MaxLogs*32 + ed25519.SignatureSize
)
const (
	// DefaultCopies is the number of pinning peers Select and AddMany choose when n is 0 or less.
	DefaultCopies = 2
	// MaxFallback is how many more peers AddMany tries, in Select's order, when chosen ones are unreachable.
	MaxFallback = 2
)
const (
	// MaxRequestSize is the largest request a pinning peer reads: an ADD with a capability of MaxLogs logs.
	MaxRequestSize = 1 + 1 + kololog.LogIDSize + 2 + MaxCapabilitySize
	// Timeout bounds reading one request and writing one answer.
	Timeout = 60 * time.Second
)
const DefaultMaxBytes = 100_000_000_000

DefaultMaxBytes is the default Options.MaxBytes: 100 GB.

const DefaultMaxOwners = 100_000

DefaultMaxOwners is the default Options.MaxOwners: a revoke-only record is about 50 bytes and a capability at most 8353, so 100,000 records take at most 0.8 GB.

Variables

var (
	// ErrInvalidArgument means a nil identity, log or listener, a key of the wrong size (also in a log's header), or a missing option.
	ErrInvalidArgument = errors.New("pin: invalid argument")
	// ErrInvalidCapability means a capability or revoke note that is malformed or whose signature does not verify.
	ErrInvalidCapability = errors.New("pin: invalid capability")
	// ErrUnauthorized means the pinning peer refused the capability: another peer or owner, a log it does not
	// cover, an owner the peer does not accept, a bad signature, or an issue time in the future.
	ErrUnauthorized = errors.New("pin: not authorized")
	// ErrExpired means the capability has expired.
	ErrExpired = errors.New("pin: capability expired")
	// ErrRevoked means the capability was revoked, or replaced by a newer one from the same owner.
	ErrRevoked = errors.New("pin: capability revoked or replaced")
	// ErrQuotaExceeded means the write would take the owner past the quota in its capability.
	ErrQuotaExceeded = errors.New("pin: owner quota exceeded")
	// ErrDiskFull means the write would take the pinning peer past its total byte limit.
	ErrDiskFull = errors.New("pin: pinning peer disk full")
	// ErrOwnerLimit means the pinning peer already keeps the most owner records it accepts and the owner is not one of them.
	ErrOwnerLimit = errors.New("pin: owner limit reached")
	// ErrNotFound means the pinning peer does not hold the log for this owner.
	ErrNotFound = errors.New("pin: log not found")
	// ErrInvalid means the log the pinning peer pulled does not verify; nothing past the last valid entry was kept.
	ErrInvalid = errors.New("pin: log data does not verify")
	// ErrTooLarge means a message or log entry over kolo-sync's MaxMessageSize, or a request over MaxRequestSize.
	ErrTooLarge = errors.New("pin: too large")
	// ErrBusy means the pinning peer could not finish now, for example a sync that timed out; try again later.
	ErrBusy = errors.New("pin: pinning peer busy")
	// ErrProtocol means a malformed, truncated or unexpected message, or another protocol version.
	ErrProtocol = errors.New("pin: protocol error")
	// ErrUnreachable means the pinning peer could not be reached, or the connection broke before it answered.
	ErrUnreachable = errors.New("pin: pinning peer unreachable")
	// ErrNoPeer means AddMany found no pinning peer that accepted the log.
	ErrNoPeer = errors.New("pin: no pinning peer accepted the log")
)

Funciones

func Issue

func Issue(owner *koloid.Identity, c Capability) ([]byte, error)

Issue signs c with the owner's identity and returns the encoded capability, in whole seconds.

func IssueMany

func IssueMany(owner *koloid.Identity, peers []Peer, c Capability) ([][]byte, error)

IssueMany issues c for each peer, all with the same issue time, in the order of peers.

func IssueRevocation

func IssueRevocation(owner *koloid.Identity, peer ed25519.PublicKey, through time.Time) ([]byte, error)

IssueRevocation signs a revoke note: peer drops owner's logs if its capability was issued at or before through.

func LoadIdentity

func LoadIdentity(dir string) (*koloid.Identity, error)

LoadIdentity returns the pinning peer's identity in dir, creating it (mode 0600) on first use.

func Remove

func Remove(ctx context.Context, id *koloid.Identity, peer Peer, logID kololog.LogID) error

Remove asks the pinning peer to delete the log logID; id must be the log's owner.

func Revoke

func Revoke(ctx context.Context, id *koloid.Identity, peer Peer, note []byte) error

Revoke gives the pinning peer a revoke note from IssueRevocation; anyone may deliver it.

func Serve

func Serve(ctx context.Context, node *kolosecure.Listener, opts Options) error

Serve runs a pinning peer on node, which must listen with LoadIdentity(opts.Dir), until ctx is done. It closes the connections it accepted and its store before it returns ctx.Err() or the listener's error.

Tipos

type Capability

type Capability struct {
	Owner   ed25519.PublicKey // the log owner who signs it; Issue sets it
	Peer    ed25519.PublicKey // the one pinning peer it is for
	Logs    []kololog.LogID   // the logs it covers; empty means every log of Owner
	Issued  time.Time         // newer capabilities replace older ones; zero means now in Issue
	Expires time.Time         // after this the pinning peer drops the logs
	Quota   uint64            // the most bytes Owner's logs may take on Peer; 0 means only the peer's own limit
}

Capability lets one pinning peer keep and serve an owner's logs until it expires; the owner signs it.

func ParseCapability
func ParseCapability(b []byte) (Capability, error)

ParseCapability decodes a capability and checks its owner's signature; it never panics on untrusted input. It does not check the time: the pinning peer does, against its own clock.

func (Capability) Covers
func (c Capability) Covers(logID kololog.LogID) bool

Covers reports whether c covers the log logID.

type Info

type Info struct {
	Entries uint64    // entries of the log it holds
	Used    uint64    // bytes the owner's logs take on it
	Quota   uint64    // the owner's quota from the capability in use; 0 means none
	Expires time.Time // when that capability expires and the logs are dropped
}

Info is what a pinning peer holds of one log and its owner.

func Add
func Add(ctx context.Context, id *koloid.Identity, peer Peer, log kolosync.Source, capability []byte) (Info, error)

Add asks the pinning peer to keep log under capability, and serves it the log's ciphertext until it has pulled and verified it. Call it again after new entries or deletes. id only opens the connection.

func Status
func Status(ctx context.Context, id *koloid.Identity, peer Peer, logID kololog.LogID) (Info, error)

Status returns what the pinning peer holds of the log logID; id must be the log's owner.

type Options

type Options struct {
	// Dir is the data directory, holding identity.key and the store. It must be private; it is created with mode 0700.
	Dir string
	// MaxBytes is the most bytes the peer stores for all owners together. Default DefaultMaxBytes.
	MaxBytes uint64
	// Owners lists the owner keys the peer accepts capabilities and revoke notes from. Empty accepts any owner, and
	// Serve then logs a warning: anyone can fill MaxBytes and MaxOwners.
	Owners []ed25519.PublicKey
	// MaxOwners is the most owner records the peer keeps: one per owner key with a capability in use, a held log or a
	// revoke note, which stays after expiry so a revoked capability is never accepted again. A request that would
	// add one past it is ErrOwnerLimit; owners already kept are not affected. Default DefaultMaxOwners.
	MaxOwners uint64
	// AddTimeout bounds the time one Add may spend pulling a log, entries already stored are kept. Zero means no
	// limit but the connection's idle timeout and the owner's quota.
	AddTimeout time.Duration
	// Logger receives the peer's events; nil discards them.
	Logger *slog.Logger
	// Metrics, if set, gets the peer's kolo_pin_* metrics while Serve runs. Their labels never hold keys, IDs or addresses.
	Metrics prometheus.Registerer
}

Options configures Serve.

type Outcome

type Outcome int

Outcome is what happened when AddMany tried one peer.

const (
	// Accepted means the peer pulled and verified the log.
	Accepted Outcome = iota + 1
	// Refused means the peer answered with an error, or no capability named it.
	Refused
	// Unreachable means the peer could not be reached or the connection broke.
	Unreachable
)
func (Outcome) String
func (o Outcome) String() string

String returns "accepted", "refused" or "unreachable".

type Peer

type Peer struct {
	ID    ed25519.PublicKey
	Addr  string // host:port, IPv4
	Group string // where it is hosted, such as a provider or region; used by Select
}

Peer is a pinning peer: its kolo-id key, its IPv4 address and an optional group label.

type Report

type Report struct {
	Results      []Result // every peer tried, in order
	Accepted     int      // how many peers accepted the log
	SharedGroups bool     // as in Selection
}

Report is the result of AddMany.

func AddMany
func AddMany(ctx context.Context, id *koloid.Identity, peers []Peer, log kolosync.Source, capabilities [][]byte, n int) (Report, error)

AddMany adds log to the n peers Select chooses, using the capability that names each one. An unreachable peer is replaced by the next peer in Select's order that was not chosen, at most MaxFallback times. It returns ErrNoPeer if none accepted, and ctx.Err() if ctx ended first; the Report always lists the tries made.

type Result

type Result struct {
	Peer    Peer
	Outcome Outcome
	Info    Info  // set when Accepted
	Err     error // set unless Accepted
}

Result is one peer AddMany tried.

type Revocation

type Revocation struct {
	Owner   ed25519.PublicKey
	Peer    ed25519.PublicKey
	Through time.Time
}

Revocation revokes every capability an owner issued for one pinning peer at or before Through.

func ParseRevocation
func ParseRevocation(b []byte) (Revocation, error)

ParseRevocation decodes a revoke note and checks its owner's signature; it never panics on untrusted input.

type Selection

type Selection struct {
	Peers        []Peer // the chosen peers, highest weight first
	SharedGroups bool   // there were fewer groups than peers to choose, so some chosen peers share a group
}

Selection is the result of Select.

func Select
func Select(peers []Peer, logID kololog.LogID, n int) Selection

Select returns the n peers with the highest rendezvous weight for logID, from different groups when it can. A peer without a group counts as its own group. Peers with an invalid ID are skipped, and of repeated IDs one is kept.

Conviene saber

Todos los pasos

Cómo se elige un pin

Hashing de rendezvous: todos los dispositivos calculan la misma elección para un log, sin coordinarse. Aquí los pesos van acortados.

  1. Para cada pin, el cliente calcula un peso: SHA-256 del ID del pin y del ID del log.
  2. Los pins se ordenan por peso, del más pesado al más ligero.
  3. Select toma el pin más pesado de cada grupo hasta tener copias suficientes, 2 por defecto. El pin 1 se salta: su grupo ya tiene el pin 3. Si hay pocos grupos, completan los siguientes más pesados.
  4. Añade el pin 5, en un grupo nuevo. Para este log queda segundo, así que ocupa el sitio del pin 4. Un log en el que no queda arriba se queda como estaba.
Todos los pasos

Capacidad y cuota

Una capacidad es el permiso firmado del propietario para un pin: qué logs, cuántos bytes, hasta cuándo.

  1. El propietario emite una capacidad para un pin: la clave del pin, la fecha de emisión y de caducidad, una cuota en bytes y los logs que cubre (si no lista ninguno, todos), firmada por el propietario.
  2. Un dispositivo la envía en ADD. La capacidad, no la conexión, dice de quién es el espacio que usa el log.
  3. El pin comprueba la firma, que nombra a este pin y cubre el log, que el propietario está permitido, que no se emitió más de 60 segundos por delante del reloj del pin y que no ha caducado.
  4. En cada escritura el pin suma los bytes nuevos al total del propietario. Pasar la cuota da ErrQuotaExceeded y pasar el límite del pin, ErrDiskFull. Los borrados siempre pasan; nada se desaloja.
  5. Cada minuto el pin elimina los logs de los propietarios cuya capacidad ha caducado.
  6. REVOKE, firmado por el propietario, anula todas las capacidades emitidas hasta un momento. El pin elimina los logs del propietario si la actual queda anulada.

Límites

  • Solo IPv4. Peer.Addr es un host:port IPv4. El comando kolo-pin rechaza una dirección IPv6 en -listen, -health o -metrics, incluida la forma v4-mapped, y sale con 2.
  • Options.MaxBytes, el total de todos los propietarios: DefaultMaxBytes, 100 GB. Una escritura que lo supera es ErrDiskFull.
  • Capability.Quota, por propietario, en bytes: 0 significa solo el límite propio del peer. Una escritura que la supera es ErrQuotaExceeded.
  • Options.MaxOwners (-max-owners): los registros de propietario que guarda el peer, uno por clave de propietario con una capacidad o nota de revocación aceptada alguna vez, DefaultMaxOwners, 100.000. Una nota o capacidad de una clave nueva por encima del límite es ErrOwnerLimit (código de respuesta 11), así que unas claves desechables no pueden llenar el disco ni hacer que cada arranque lea una lista sin límite. Los propietarios ya guardados nunca se rechazan, y el registro de una clave no crece con sus notas. Las métricas kolo_pin_owner_records y kolo_pin_owner_records_max lo muestran.
  • Options.AddTimeout (-add-timeout): el máximo de tiempo que puede gastar un Add, el pull incluido. Pasado ese tiempo el Add da ErrBusy y se conservan las entradas guardadas hasta entonces. Por defecto no hay límite.
  • Las conexiones salen de los límites de kolo-transport, fijados con -max-conns (100 por defecto, de 1 a 10.000, en handshake o abiertas) y -max-conns-per-ip (4 por defecto, como mucho -max-conns), o con KOLO_PIN_MAX_CONNS y KOLO_PIN_MAX_CONNS_PER_IP. Los propietarios detrás de un mismo NAT comparten una dirección: sube -max-conns-per-ip para ellos.
  • Los dos límites se comprueban antes de guardar nada, y no se expulsa nada para hacer sitio. Los bytes se cuentan como claves y valores guardados, no como bloques de disco. Los borrados siempre pasan, así que un propietario que supera una cuota reducida todavía puede borrar.
  • Si un borrado falla (un error de disco, o el log del propietario abierto en el mismo proceso), el log se queda en disco y sigue contando para la cuota del propietario, MaxBytes y Used hasta que se borre, así que un Add puede responder ErrQuotaExceeded o ErrDiskFull por un espacio que el propietario no ve. Un log que la capacidad en uso todavía cubre se sigue sirviendo, así que el siguiente Add lo ancla, y Remove responde ErrBusy mientras su borrado falla. Un log que no cubre ni se ofrece ni se informa: el barrido vuelve a intentar el borrado al cabo de un minuto, y luego tras el doble de tiempo cada vez, hasta 64 minutos, igual que el siguiente arranque. El comando registra delete failed, log kept una vez, y dropped after retry cuando un intento posterior funciona.
  • Una entrada tiene que caber en un mensaje de kolo-sync, MaxMessageSize (4 MiB), junto con su registro y la sobrecarga del cifrado, o Add devuelve ErrTooLarge. Una entrada de 4 MiB exactos ya es demasiado grande. Divide los archivos grandes en varias entradas.
  • Una capacidad lista como máximo MaxLogs (256) IDs de log, o ninguno para todos los logs del propietario, y ocupa como máximo MaxCapabilitySize (8353) bytes. Las horas son segundos Unix enteros hasta 2^53-1, y Expires tiene que ser posterior a Issued.
  • El peer de anclaje acepta una hora de emisión como máximo 60s en su propio futuro, y busca capacidades caducadas cada minuto.
  • Una petición ocupa como máximo MaxRequestSize (8389) bytes. Las peticiones de una conexión se responden de una en una, y cada una se lee y se responde dentro de Timeout (60s).
  • Conectarse a un peer de anclaje se abandona al cabo de 10s, con ErrUnreachable.
  • Un log abierto se cierra después de un minuto sin uso, y como máximo hay 64 abiertos a la vez. Primero se cierran los usados hace más tiempo, nunca uno en el que se está haciendo pull.
  • Select y AddMany eligen DefaultCopies (2) peers cuando n es 0 o menos. AddMany sustituye un peer inalcanzable como máximo MaxFallback (2) veces.
  • Options.Dir tiene que ser privado. Se crea con modo 0700, e identity.key con modo 0600. Se rechaza un directorio al que otros pueden acceder.
  • El comando kolo-pin: por defecto, -listen es 127.0.0.1:7450, -health es 127.0.0.1:7451, -metrics es 127.0.0.1:7452 y -max-bytes es 100GB. Sale con 0 después de SIGINT o SIGTERM, con 1 cuando no consigue arrancar (como un puerto ya en uso) y con 2 ante un flag incorrecto, también una dirección no válida en -listen, -health o -metrics.

Seguridad

  • El peer de anclaje ve qué claves de propietario e IDs de log aloja, cuántas entradas tienen y cuánto ocupan, los registros firmados, cuándo crece cada log, cuándo se borra algo de él o cuándo se hace pull de él y, en cada petición, la clave, la dirección IP y los tiempos de quien la hace. No puede leer las entradas. Cualquiera que conozca una clave de propietario y un ID de log puede hacer pull de su texto cifrado y sus registros, o pedirlos con Fetch, y saber lo mismo.
  • Todo lo que guarda ha pasado por Replica.Update o Replica.ApplyDelete de kolo-store, que comprueban antes cada firma, hash y prueba, así que nunca guarda una entrada falsificada. ErrInvalid significa que el log no se pudo verificar, y solo se conserva lo que se verificó antes.
  • Las capacidades y las notas de revocación son firmas Ed25519ctx del propietario, con los contextos kolo-pin/capability/v0 y kolo-pin/revoke/v0. ParseCapability y ParseRevocation nunca entran en pánico ante entradas no fiables.
  • Por cada propietario, el peer de anclaje guarda la capacidad más reciente. Una más antigua, u otra con la misma hora de emisión, es ErrRevoked; la misma otra vez no da problemas. Una más reciente la sustituye al momento: los logs que ya no cubre se borran, y su cuota se aplica desde entonces.
  • Cuando la capacidad caduca, o una nota de revocación de IssueRevocation la cubre, se borran todos los logs de ese propietario. Una nota de revocación va firmada, así que cualquiera puede entregarla con Revoke.
  • Add funciona con cualquier identidad, porque la autoridad la lleva la capacidad. Status y Remove necesitan que la clave de la conexión sea la del propietario del log.
  • El borrado es de mejor esfuerzo. El peer de anclaje aplica las marcas de borrado nuevas de un propietario en el siguiente Add, a medida que kolo-sync se las entrega, y elimina sus textos cifrados en esa misma escritura. Un peer que no sigue el protocolo conserva lo que tiene, y los bloques antiguos del disco pueden contener todavía bytes borrados. Consulta Borrado.
  • Ningún error lleva bytes que haya enviado un peer. Los logs del comando kolo-pin contienen claves públicas, IDs de log, direcciones y tamaños, nunca una clave privada, una semilla ni una clave de entrada.
  • El comando kolo-pin sirve métricas de Prometheus en 127.0.0.1:7452 (-metrics, off para desactivarlas), y Options.Metrics da las mismas métricas kolo_pin_* a quien usa la biblioteca. Solo contienen totales de todo el peer y valores fijos de etiqueta, nunca una clave de propietario, un ID de log, una clave de peer, una dirección IP ni una cifra por propietario. El endpoint no tiene autenticación, así que mantenlo en loopback. Consulta Monitorizar un peer de anclaje.

Límites conocidos

  • AddMany no reintenta en segundo plano. Vuelve a llamarlo.
  • Los clientes llegan a un peer de anclaje directamente, en la dirección en la que escucha, así que necesita una dirección a la que lleguen todos. Kolo Chat nunca llega a un pin a través de un relay.
  • No hay límite de frecuencia de peticiones aparte de la cuota del propietario, MaxBytes y los límites de conexiones, streams, tamaño y tiempo de kolo-transport y kolo-sync.
  • Un log abierto mantiene en memoria los hashes de su árbol y una copia compacta de cada registro, unos 250 bytes por entrada, y lee los textos cifrados del disco. El límite de 64 logs abiertos cuenta logs, no entradas, así que esa memoria la limita el disco, no la RAM. En el peor caso, 64 logs abiertos que llenan MaxBytes con las entradas más pequeñas ocupan en memoria unas 0,42 veces MaxBytes, unos 40 GB para un peer lleno de 100 GB, y cualquier peer que conozca sus claves de propietario e IDs de log puede hacer que el peer de anclaje los abra. Ajusta MaxBytes (-max-bytes) y las cuotas de los propietarios a la RAM que tengas.
  • Abrir un log lo lee y lo verifica entero, así que leer muchos logs inactivos le cuesta al peer de anclaje CPU y lecturas de disco.
  • Todas las pruebas se ejecutan en 127.0.0.1. No se han probado el paso por un NAT real, un VPS real, almacenes de muchos gigabytes, un sistema de archivos lleno (se indica como ErrBusy), un desfase de reloj de más de 60s ni el uso de memoria a largo plazo con muchos propietarios.
  • Experimental. La API puede cambiar antes de v1.0.0.

Errores

ErrorMensaje
ErrBusypin: pinning peer busy
ErrDiskFullpin: pinning peer disk full
ErrExpiredpin: capability expired
ErrInvalidpin: log data does not verify
ErrInvalidArgumentpin: invalid argument
ErrInvalidCapabilitypin: invalid capability
ErrNoPeerpin: no pinning peer accepted the log
ErrNotFoundpin: log not found
ErrOwnerLimitpin: owner limit reached
ErrProtocolpin: protocol error
ErrQuotaExceededpin: owner quota exceeded
ErrRevokedpin: capability revoked or replaced
ErrTooLargepin: too large
ErrUnauthorizedpin: not authorized
ErrUnreachablepin: pinning peer unreachable

Comprueba los errores con errors.Is. Una respuesta del peer de anclaje vuelve como el propio valor de error, por ejemplo ErrQuotaExceeded. ErrUnreachable y ErrInvalidArgument de una conexión fallida envuelven el error de kolo-secure. Cuando ctx termina antes, las funciones del cliente devuelven ctx.Err(), y AddMany también, en lugar de ErrNoPeer; cada Result de su Report conserva su propio Err.

Referencias