Prueba de trabajo · 03
Por qué Go, específicamente.
Porque un lenguaje que compila a un único binario estático, planifica cien mil conversaciones concurrentes en una máquina de 4 GB, y convierte ignorar un error en un acto visible de vandalismo es la única elección honesta para las dos restricciones de arriba. Así se ve esa disciplina en el código real.
internal/vault/seal.go
Sin fallos silenciosos
package vault
import (
"context"
"crypto/aes"
"crypto/cipher"
crand "crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
// A version byte prefix lets keys or algorithms rotate later with no data migration.
const (
envelopeV1 = 0x01
nonceSize = 12 // 96-bit GCM nonce
)
// Sentinel errors — internal KMS/network detail never leaks to the caller.
var (
ErrSeal = errors.New("vault: seal failed")
ErrContext = errors.New("vault: context invalid or canceled")
ErrEntropy = errors.New("vault: entropy source failure")
)
// Seal encrypts one PII field with a per-record data key from KMS and returns a
// self-describing envelope. The plaintext data key never outlives this call.
func (v *Vault) Seal(ctx context.Context, plaintext []byte) (_ []byte, err error) {
if len(plaintext) == 0 {
return nil, fmt.Errorf("%w: empty payload", ErrSeal)
}
// One span per seal; success/error recorded on the way out.
ctx, span := v.tracer.Start(ctx, "Vault.Seal", trace.WithAttributes(
attribute.String("kms.key_id", v.keyID),
attribute.Int("payload.bytes", len(plaintext)),
))
defer func() {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
v.metrics.SealErrors.Inc()
}
span.End()
}()
// Bound the call only if the caller gave us no deadline of its own.
if _, ok := ctx.Deadline(); !ok && v.kmsTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, v.kmsTimeout)
defer cancel()
}
if err = ctx.Err(); err != nil {
return nil, fmt.Errorf("%w: %w", ErrContext, err)
}
// KMS data key, with latency recorded for the SLO.
start := time.Now()
dek, err := v.kms.GenerateDataKey(ctx, v.keyID)
v.metrics.KMSLatency.Observe(time.Since(start).Seconds())
if err != nil {
return nil, fmt.Errorf("%w: generate data key", ErrSeal)
}
defer wipe(dek.Plaintext) // zeroed on every path, including panic
block, err := aes.NewCipher(dek.Plaintext)
if err != nil {
return nil, fmt.Errorf("%w: new cipher", ErrSeal)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("%w: new gcm", ErrSeal)
}
// One allocation for the whole envelope.
size := 1 + 2 + len(v.keyID) + 2 + len(dek.Ciphertext) + nonceSize + len(plaintext) + gcm.Overhead()
out := make([]byte, 0, size)
out = append(out, envelopeV1)
out = binary.BigEndian.AppendUint16(out, uint16(len(v.keyID)))
out = append(out, v.keyID...)
out = binary.BigEndian.AppendUint16(out, uint16(len(dek.Ciphertext)))
out = append(out, dek.Ciphertext...)
// Reserve the nonce and fill it from the OS CSPRNG.
ivStart := len(out)
out = out[:ivStart+nonceSize]
if _, err = io.ReadFull(crand.Reader, out[ivStart:]); err != nil {
return nil, fmt.Errorf("%w: %w", ErrEntropy, err)
}
// Seal in place: ciphertext+tag land in the same backing array.
out = gcm.Seal(out, out[ivStart:], plaintext, nil)
return out, nil
}
1 binario
Sin runtime que instalar, parchear o explotar
Un binario estático de Go en un contenedor distroless y non-root. Nada interpretado, sin árbol de dependencias en tiempo de ejecución, y un arranque en frío medido en milisegundos. Por eso una instancia modesta sostiene toda la plataforma.
~4 KB
Concurrencia cotizada en kilobytes, no megabytes
Una goroutine arranca con un par de kilobytes de stack. Los runtimes de thread-per-request arrancan con un megabyte. Esa proporción es precisamente por qué los streams de audio en tiempo real y los workers de sincronización en segundo plano coexisten en hardware que cuesta un solo dígito al mes.
0 ocultos
Errores que no puedes ignorar por accidente
Go convierte cada fallo en un valor explícito. Combinado con errcheck como merge gate, un error sin manejar detiene el pipeline. Eso no es ceremonia — es por qué los incidentes de producción llegan con una causa legible en lugar de un stack trace.